Java和Python3实现AES/CBC/PKCS5padding加密解密

该博客介绍了如何使用Java和Python实现AES加密解密。提供了详细的代码示例,包括Java的AESUtil类和Python的AESCipher类。这两个类都使用了CBC模式和PKCS5Padding填充方式,并通过Base64编码处理加密后的数据。文章还列出了必要的依赖库,如Java的Apache Commons Codec和Python的pycryptodome。测试部分展示了加密和解密字符串的用法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Java版

代码

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;

import java.nio.charset.StandardCharsets;

class AESUtil {
    private static String sKey = "0123456789ABCDEF0123456789ABCDEF"; //密钥是string类型 长度是16、24、32
    private static String ivParameter = sKey.substring(0, 16); ; //偏移量是密钥截取16位,也是string类型
    static String encrypt(String str) throws Exception {
        try {
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            byte[] raw = sKey.getBytes();  // 密钥转成byte
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            IvParameterSpec iv = new IvParameterSpec(ivParameter.getBytes()); //偏移量转成byte
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
            byte[] encrypted = cipher.doFinal(str.getBytes(StandardCharsets.UTF_8));
            return Base64.encodeBase64String(encrypted); //base64编码
        } catch (Exception ex) {
            return null;
        }
    }

    static String decrypt(String str) throws Exception {
        try {
            byte[] raw = sKey.getBytes();
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            IvParameterSpec iv = new IvParameterSpec(ivParameter.getBytes()); //偏移量
            cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
            byte[] encrypted1 = Base64.decodeBase64(str);
            byte[] original = cipher.doFinal(encrypted1);
            return new String(original, "utf-8");
        } catch (Exception ex) {
            return null;
        }
    }
}

依赖

<dependency>
    <groupId>commons-codec</groupId>
    <artifactId>commons-codec</artifactId>
    <version>1.10</version>
</dependency>

测试

public class Test {
    public static void main(String[] args) throws Exception {
        System.out.println(AESUtil.encrypt("aaa"));
        System.out.println(AESUtil.decrypt("U8657ZVdorE5b4nHugHYaA=="));
    }
}

Python版

依赖

安装依赖模块:

pip install pycryptodome

代码

from Crypto.Cipher import AES
from base64 import b64decode, b64encode
from Crypto.Util.Padding import pad, unpad


class AESCipher:
    def __init__(self, secretkey: str):
        self.key = secretkey  # 密钥
        self.iv = secretkey[0:16]  # 偏移量
        # self.iv = "0000000000000000"  # 偏移量

    def encrypt(self, text):
        """
        加密 :先补位,再AES加密,后base64编码
        :param text: 需加密的明文
        :return:
        """
        # text = pad(text) 包pycrypto的写法,加密函数可以接受str也可以接受bytess
        text = pad(text.encode(), block_size=AES.block_size)  # 包pycryptodome 的加密函数不接受str
        cipher = AES.new(key=self.key.encode(), mode=AES.MODE_CBC, IV=self.iv.encode())
        encrypted_text = cipher.encrypt(text)
        # 进行64位的编码,返回得到加密后的bytes,decode成字符串
        return b64encode(encrypted_text).decode('utf-8')

    def decrypt(self, encrypted_text):
        """
        解密 :偏移量为key[0:16];先base64解,再AES解密,后取消补位
        :param encrypted_text : 已经加密的密文
        :return:
        """
        encrypted_text = b64decode(encrypted_text)
        cipher = AES.new(key=self.key.encode(), mode=AES.MODE_CBC, IV=self.iv.encode())
        decrypted_text = cipher.decrypt(encrypted_text)
        return unpad(decrypted_text, cipher.block_size).decode('utf-8')

测试

encrypted_text = AESCipher(secretkey).encrypt("aaa")
print(encrypted_text)
secretkey = "0123456789ABCDEF0123456789ABCDEF"
decrypted_text = AESCipher(secretkey).decrypt(encrypted_text)
print(decrypted_text)

参考

https://www.cnblogs.com/shenzhuang/p/10302182.html
https://pengshiyu.blog.csdn.net/article/details/103646639
http://www.metools.info/code/aes275.html
https://blog.csdn.net/gqv2009/article/details/113590271
https://www.mklab.cn/utils/aes

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小龙在山东

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值