aesDecrypt function
Uint8List
aesDecrypt(
- dynamic cipherText,
- dynamic key, {
- bool isCipherTextHexa = true,
- bool isKeyHexa = true,
})
Implementation
Uint8List aesDecrypt(
dynamic cipherText,
dynamic key, {
bool isCipherTextHexa = true,
bool isKeyHexa = true,
}) {
if (cipherText is! Uint8List && cipherText is! String) {
throw "'cipherText' must be a string or Uint8List";
}
if (key is! Uint8List && key is! String) {
throw "'key' must be a string or Uint8List";
}
if (cipherText is String) {
if (isCipherTextHexa && !isHex(cipherText)) {
throw const FormatException("'cipherText' must be an hexadecimal string");
}
if (isCipherTextHexa) {
cipherText = Uint8List.fromList(hexToUint8List(cipherText));
} else {
throw "'cipherText' must be an hexadecimal string";
}
}
if (key is String) {
if (isKeyHexa && !isHex(key)) {
throw const FormatException("'key' must be an hexadecimal string");
}
if (isKeyHexa) {
key = Uint8List.fromList(hexToUint8List(key));
} else {
throw "'key' must be an hexadecimal string";
}
}
final keyPair = crypto_keys.KeyPair.symmetric(
crypto_keys.SymmetricKey(keyValue: Uint8List.fromList(key)),
);
final Uint8List iv = cipherText.sublist(0, 12);
final Uint8List tag = cipherText.sublist(12, 12 + 16);
final Uint8List encrypted = cipherText.sublist(28, cipherText.length);
final encrypter = keyPair.privateKey!
.createEncrypter(crypto_keys.algorithms.encryption.aes.gcm);
final decrypted = encrypter.decrypt(
crypto_keys.EncryptionResult(
encrypted,
initializationVector: iv,
authenticationTag: tag,
),
);
return decrypted;
}