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



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

def encrypt(self, text):
"""
加密 :先补位,再AES加密,后base64编码
:param text: 需加密的明文
:return:
"""
# text = pad(text) 包pycrypto的写法,加密函数可以接受str也可以接受bytess
text = pad(text).encode() # 包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).decode('utf-8')

测试

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