Closed lindeer closed 1 year ago
from Crypto.Util.Padding import pad, unpad from Crypto.Cipher import AES def raw2hex(raw): num = "" for char in raw: num += format(char, "x").rjust(2, '0') return num key="0123456789abcdef".encode('utf-8') def crypt(text): data = text.encode('utf-8') cipher=AES.new(key, AES.MODE_CBC, key) padding = pad(data, AES.block_size) print(padding) r = cipher.encrypt(padding) print(r) return raw2hex(r) print(crypt('a'))
result is '4694c9b4c3f491d04428ebd697e40581'
final cryptKey = utf8.encode('0123456789abcdef'); /// Converts a raw byte array to a hexadecimal string. String raw2hex(List<int> raw) { final buffer = StringBuffer(); for (final byte in raw) { buffer.write(byte.toRadixString(16).padLeft(2, '0')); } return buffer.toString(); } Future<String> crypt(String text) async { final algorithm = AesCbc.with128bits( macAlgorithm: Hmac.sha256(), paddingAlgorithm: PaddingAlgorithm.pkcs7, ); final data = utf8.encode(text); final secretKey = await algorithm.newSecretKeyFromBytes(cryptKey); final encrypted = await algorithm.encrypt(data, secretKey: secretKey); return raw2hex(encrypted.cipherText); } print(crypt('a'))
result is 'da843e13bddc2023d531ecb6b754e3a0'
I tried different macAlgorithms, but none of results is correct. Something wrong with my dart code?
resolved! the iv in Python crypto is the nonce in Dart cryptography, so change as below:
iv
nonce
final encrypted = await algorithm.encrypt(data, secretKey: secretKey, nonce: cryptKey);
result is '4694c9b4c3f491d04428ebd697e40581'
result is 'da843e13bddc2023d531ecb6b754e3a0'
I tried different macAlgorithms, but none of results is correct. Something wrong with my dart code?