aes128GcmDecrypt method
Uint8List
aes128GcmDecrypt({
- required Uint8List ciphertext,
- required Uint8List key,
- required Uint8List iv,
- required Uint8List tag,
- Uint8List? aad,
inherited
Decrypts ciphertext using AES-128-GCM.
Implementation
Uint8List aes128GcmDecrypt({
required Uint8List ciphertext,
required Uint8List key,
required Uint8List iv,
required Uint8List tag,
Uint8List? aad,
}) {
if (key.length != 16) throw ArgumentError('Key must be 16 bytes');
if (tag.length != 16) throw ArgumentError('Tag must be 16 bytes');
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 tagPtr = calloc<Uint8>(tag.length);
tagPtr.asTypedList(tag.length).setAll(0, tag);
final outPtr = calloc<Uint8>(ciphertext.length + 16);
final outLen = calloc<Int>();
try {
final cipher = bindings.EVP_aes_128_gcm();
if (bindings.EVP_DecryptInit_ex(ctx, cipher, nullptr, nullptr, nullptr) != 1) {
throw OpenSslException('EVP_DecryptInit_ex failed');
}
if (iv.length != 12) {
if (bindings.EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, iv.length, nullptr) != 1) {
throw OpenSslException('Failed to set IV length');
}
}
if (bindings.EVP_DecryptInit_ex(ctx, nullptr, nullptr, keyPtr.cast(), ivPtr.cast()) != 1) {
throw OpenSslException('Failed to set Key/IV');
}
if (aad != null && aad.isNotEmpty) {
final aadPtr = calloc<Uint8>(aad.length);
aadPtr.asTypedList(aad.length).setAll(0, aad);
try {
if (bindings.EVP_DecryptUpdate(ctx, nullptr, outLen, aadPtr.cast(), aad.length) != 1) {
throw OpenSslException('Failed to set AAD');
}
} finally {
calloc.free(aadPtr);
}
}
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_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_TAG, 16, tagPtr.cast()) != 1) {
throw OpenSslException('Failed to set expected Tag');
}
final ret = bindings.EVP_DecryptFinal_ex(ctx, (outPtr + totalLen).cast(), outLen);
if (ret <= 0) {
throw OpenSslException('Decryption failed (Tag mismatch or bad data)');
}
totalLen += outLen.value;
return Uint8List.fromList(outPtr.asTypedList(totalLen));
} finally {
calloc.free(outPtr);
calloc.free(outLen);
calloc.free(keyPtr);
calloc.free(ivPtr);
calloc.free(tagPtr);
bindings.EVP_CIPHER_CTX_free(ctx);
}
}