安卓AES 加密 用python 翻译后 加密结果不一致
private static byte[] iv = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16};
/**
* AES加密字符串
*
* @param content 需要被加密的字符串
* @param password 加密需要的密码
* @return 密文
*/
public static byte[] encrypt(byte[] content, byte[] password) {
try {
if (password.length != 16) {
password = Arrays.copyOfRange(password, 0, 16);
}
KeyGenerator kgen = KeyGenerator.getInstance("AES");// 创建AES的Key生产者
SecretKeySpec key = new SecretKeySpec(password, "AES");// 转换为AES专用密钥
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");// 创建密码器
cipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(iv));// 初始化为加密模式的密码器
return cipher.doFinal(content);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
python
# 加密函数
def aes_cbc_encrypt(password: str) -> bytes:
# 这里 md5 加密了密码
md = hashlib.md5()
md.update(password.encode())
password_md5 = md.hexdigest()
print(f"密码md5:{password_md5}")
key = password_md5.encode()
print("key", key)
iv = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
iv_byte = bytes(i % 256 for i in iv)
print("iv_byte", iv_byte)
cryptos = AES.new(key, AES.MODE_CBC, iv_byte)
cipher_text = cryptos.encrypt(password_md5.encode())
# 因为AES加密后的字符串不一定是ascii字符集的,输出保存可能存在问题,所以这里转为16进制字符串
aes_cbc_text = b2a_hex(cipher_text)
print(f"AES 后的密码:{aes_cbc_text}")
return aes_cbc_text