aesEncrypt method
Implementation
Uint8List aesEncrypt(Uint8List data) {
AesCryptArgumentError.checkNullOrEmpty(
_aesKey, 'AES encryption key is null or 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 encData = Uint8List(data.length); // returned cipher text;
Uint8List t = Uint8List(
16); // 16-byte block to hold the temporary input of the cipher
Uint8List block16 = Uint8List.fromList(
_aesIV); // 16-byte block to hold the temporary output of the cipher
switch (_aesMode) {
case AesMode.ecb:
// put a 16-byte block into t, encrypt it and add it to the result
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;
}
}
block16 = aesEncryptBlock(t);
encData.setRange(i, i + 16, block16);
}
break;
case AesMode.cbc:
// put a 16-byte block into t, encrypt it and add it to the result
for (int i = 0; i < data.length; i += 16) {
for (int j = 0; j < 16; ++j) {
// XOR this block of plaintext with the initialization vector
t[j] = ((i + j) < data.length ? data[i + j] : 0) ^ block16[j];
}
block16 = aesEncryptBlock(t);
encData.setRange(i, i + 16, block16);
}
break;
case AesMode.cfb:
for (int i = 0; i < data.length; i += 16) {
// Encrypt the initialization vector/cipher output then XOR with the plaintext
block16 = aesEncryptBlock(block16);
for (int j = 0; j < 16; ++j) {
// XOR the cipher output with the plaintext.
block16[j] = ((i + j) < data.length ? data[i + j] : 0) ^ block16[j];
}
encData.setRange(i, i + 16, block16);
}
break;
case AesMode.ofb:
for (int i = 0; i < data.length; i += 16) {
// Encrypt the initialization vector/cipher output then XOR with the plaintext
t = aesEncryptBlock(block16);
for (int j = 0; j < 16; ++j) {
// XOR the cipher output with the plaintext.
block16[j] = ((i + j) < data.length ? data[i + j] : 0) ^ t[j];
}
encData.setRange(i, i + 16, block16);
block16 = Uint8List.fromList(t);
}
break;
}
return encData;
}