Uint8List
aesEncrypt(- dynamic data,
- dynamic key
)
Implementation
Uint8List aesEncrypt(data, key) {
if (!(data is Uint8List) && !(data is String)) {
throw "'data' must be a string or Uint8List";
}
if (!(key is Uint8List) && !(key is String)) {
throw "'key' must be a string or Uint8List";
}
if (data is String) {
if (isHex(data)) {
data = hexToUint8List(data);
} else {
data = Uint8List.fromList(utf8.encode(data));
}
}
if (key is String) {
if (isHex(key)) {
key = hexToUint8List(key);
} else {
throw "'key' must be an hexadecimal string";
}
}
final Uint8List aad = Uint8List.fromList(
List<int>.generate(16, (int i) => Random.secure().nextInt(256)));
final Uint8List iv = Uint8List.fromList(
List<int>.generate(12, (int i) => Random.secure().nextInt(256)));
final GCMBlockCipher encrypter = GCMBlockCipher(AESFastEngine());
final AEADParameters<KeyParameter> params =
AEADParameters(KeyParameter(key), 16 * 8, iv, aad);
encrypter.init(true, params);
final Uint8List cipherText = encrypter.process(data);
final Uint8List result = concatUint8List([
encrypter.nonce,
encrypter.aad!,
Uint8List.fromList(cipherText.sublist(0, 5))
]);
return result;
}