aes128CbcDecrypt method
Decrypts ciphertext using AES-128-CBC with PKCS#7 padding.
Implementation
Uint8List aes128CbcDecrypt({
required Uint8List ciphertext,
required Uint8List key,
required Uint8List iv,
}) {
if (key.length != 16) {
throw ArgumentError('Key must be 16 bytes for AES-128-CBC');
}
if (iv.length != 16) {
throw ArgumentError('IV must be 16 bytes for AES-128-CBC');
}
final ctx = bindings.EVP_CIPHER_CTX_new();
if (ctx == nullptr) throw OpenSslException('Failed to create EVP_CIPHER_CTX');
final keyPtr = calloc<Uint8>(key.length);
keyPtr.asTypedList(key.length).setAll(0, key);
final ivPtr = calloc<Uint8>(iv.length);
ivPtr.asTypedList(iv.length).setAll(0, iv);
final outPtr = calloc<Uint8>(ciphertext.length + 16);
final outLen = calloc<Int>();
try {
final cipher = bindings.EVP_aes_128_cbc();
if (bindings.EVP_DecryptInit_ex(ctx, cipher, nullptr, keyPtr.cast(), ivPtr.cast()) != 1) {
throw OpenSslException('EVP_DecryptInit_ex failed');
}
final inPtr = calloc<Uint8>(ciphertext.length);
inPtr.asTypedList(ciphertext.length).setAll(0, ciphertext);
int totalLen = 0;
try {
if (bindings.EVP_DecryptUpdate(ctx, outPtr.cast(), outLen, inPtr.cast(), ciphertext.length) != 1) {
throw OpenSslException('EVP_DecryptUpdate failed');
}
totalLen = outLen.value;
} finally {
calloc.free(inPtr);
}
if (bindings.EVP_DecryptFinal_ex(ctx, (outPtr + totalLen).cast(), outLen) != 1) {
throw OpenSslException('EVP_DecryptFinal_ex failed');
}
totalLen += outLen.value;
return Uint8List.fromList(outPtr.asTypedList(totalLen));
} finally {
calloc.free(outPtr);
calloc.free(outLen);
calloc.free(keyPtr);
calloc.free(ivPtr);
bindings.EVP_CIPHER_CTX_free(ctx);
}
}