encrypt method
Uint8List
encrypt({
- required Uint8List data,
- required Uint8List key,
- Uint8List? iv,
- BLOCK_CIPHER_MODE mode = BLOCK_CIPHER_MODE.CBC,
- bool padding = false,
Implementation
Uint8List encrypt(
{required Uint8List data,
required Uint8List key,
Uint8List? iv,
BLOCK_CIPHER_MODE mode = BLOCK_CIPHER_MODE.CBC,
bool padding = false}) {
_log.finest(
"AESCipher.encrypt; data size: ${data.length}, data: ${data.hex()}");
_log.sdVerbose(
"AESCipher.encrypt; data:${data.hex()}, key size: ${key.length}, key: ${key.hex()}");
if (key.length != size) {
_log.error(
"AESCipher.encrypt; AES${size * 8} key length must be ${size * 8} bits.");
throw AESCipherError(
"AESCipher.encrypt; AES${size * 8} key length must be ${size * 8} bits.");
}
if (iv != null) {
_log.sdVerbose(
"AESCipher.encrypt; iv size: ${iv.length}, iv: ${iv.hex()}");
if (iv.length != AES_BLOCK_SIZE) {
_log.error("AESCipher.encrypt; iv length is not 128 bits.");
throw AESCipherError("AESCipher.encrypt; iv length is not 128 bits.");
}
} else if (mode == BLOCK_CIPHER_MODE.CBC) {
iv = Uint8List(AES_BLOCK_SIZE);
_log.sdVerbose("AESCipher.encrypt; iv is null");
}
final paddedData;
if (padding) {
_log.finest("Padding data with zeros to block size: $AES_BLOCK_SIZE");
paddedData =
pad(data: data, blockSize: AES_BLOCK_SIZE); //AES has no padding
} else {
_log.finest("Data will not be padded.");
paddedData = data;
}
var cipher;
if (mode == BLOCK_CIPHER_MODE.CBC)
cipher = CBCBlockCipher(_factory())
..init(true, ParametersWithIV(KeyParameter(key), iv!));
else
cipher = ECBBlockCipher(_factory())
..init(true, KeyParameter(key)); //ECB mode
//return cipher.process(paddedData);
return _processBlocks(cipher: cipher, data: paddedData);
}