aesDecrypt method
Implementation
Uint8List aesDecrypt(Uint8List data) {
AesCryptArgumentError.checkNullOrEmpty(
_aesKey, 'AES encryption key null or is empty.');
if (_aesMode != AesMode.ecb && _aesIV.isEmpty) {
throw AesCryptArgumentError(
'The initialization vector is empty. It can not be empty when AES mode is not ECB.');
} else if (data.length % 16 != 0) {
throw AesCryptArgumentError(
'Invalid data length for AES: ${data.length} bytes.');
}
Uint8List decData = Uint8List(data.length); // returned decrypted data;
Uint8List t = Uint8List(16); // 16-byte block
Uint8List x_block;
Uint8List block16 = Uint8List.fromList(
_aesIV); // 16-byte block to hold the temporary output of the cipher
switch (_aesMode) {
case AesMode.ecb:
for (int i = 0; i < data.length; i += 16) {
for (int j = 0; j < 16; ++j) {
if ((i + j) < data.length) {
t[j] = data[i + j];
} else {
t[j] = 0;
}
}
x_block = aesDecryptBlock(t);
decData.setRange(i, i + 16, x_block);
}
break;
case AesMode.cbc:
for (int i = 0; i < data.length; i += 16) {
for (int j = 0; j < 16; ++j) {
if ((i + j) < data.length) {
t[j] = data[i + j];
} else {
t[j] = 0;
}
}
x_block = aesDecryptBlock(t);
// XOR the iv/previous cipher block with this decrypted cipher block
for (int j = 0; j < 16; ++j) {
x_block[j] = x_block[j] ^ block16[j];
}
block16 = Uint8List.fromList(t);
decData.setRange(i, i + 16, x_block);
}
break;
case AesMode.cfb:
for (int i = 0; i < data.length; i += 16) {
// Encrypt the initialization vector/cipher output then XOR with the ciphertext
x_block = aesEncryptBlock(block16);
for (int j = 0; j < 16; ++j) {
// XOR the cipher output with the ciphertext.
x_block[j] = ((i + j) < data.length ? data[i + j] : 0) ^ x_block[j];
block16[j] = data[i + j];
}
decData.setRange(i, i + 16, x_block);
}
break;
case AesMode.ofb:
decData = aesEncrypt(data);
break;
}
return decData;
}