安卓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
你的python代码是不是多加了一步md5
Android使用AES加密数据时的代码可以在Python中翻译为以下代码:
import base64
import hashlib
import os
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
def aes_encrypt(key, plaintext):
# Derive a key and IV to use for AES encryption
d = hashlib.sha256().digest_size
key = hashlib.sha256(key.encode()).digest()[:d]
iv = os.urandom(16)
# Encrypt the plaintext
cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=default_backend())
encryptor = cipher.encryptor()
ciphertext = encryptor.update(plaintext.encode()) + encryptor.finalize()
# Return the encrypted data as a base64 encoded string
return base64.b64encode(iv + ciphertext).decode()
def aes_decrypt(key, ciphertext):
# Decode the base64 encoded string
ciphertext = base64.b64decode(ciphertext)
# Derive the key and IV
d = hashlib.sha256().digest_size
key = hashlib.sha256(key.encode()).digest()[:d]
iv = ciphertext[:16]
# Decrypt the ciphertext
cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=default_backend())
decryptor = cipher.decryptor()
plaintext = decryptor.update(ciphertext[16:]) + decryptor.finalize()
# Return the decrypted data as a string
return plaintext.decode()
这段代码实现了AES加密和解密,使用sha256算法对密钥进行哈希,并使用随机生成的IV作为加密的初始向量。最后,加密后的数据将作为base64编码的字符串返回