encrypt method
Encrypts data using the Galois/Counter Mode (GCM) with associated data (AEAD). Parameters:
nonce: The nonce value used for encryption, must have a length equal to the GCM nonce length (12 bytes).plaintext: The data to be encrypted.associatedData: (Optional) Additional data that is authenticated but not encrypted.dst: (Optional) The destination for the encrypted data and authentication tag. If not provided, a newList<int>is created.
Throws:
CryptoExceptionif the provided nonce has an incorrect length or if the destination size is incorrect.
Implementation
@override
List<int> encrypt(
List<int> nonce,
List<int> plaintext, {
List<int>? associatedData,
List<int>? dst,
}) {
if (nonce.length != nonceLength) {
throw ArgumentException.invalidOperationArguments(
"encrypt",
name: "nonce",
reason: "Incorrect nonce length.",
expecteLen: nonceLength,
);
}
final blockSize = _cipher.blockSize;
final resultLength = plaintext.length + tagLength;
final List<int> result = dst ?? List<int>.filled(resultLength, 0);
if (result.length != resultLength) {
throw ArgumentException.invalidOperationArguments(
"encrypt",
name: "dst",
reason: "Incorrect destination length.",
expecteLen: resultLength,
);
}
final counter = List<int>.filled(blockSize, 0);
counter.setAll(0, nonce);
counter[blockSize - 1] = 1;
final tagMask = List<int>.filled(blockSize, 0);
_cipher.encryptBlock(counter, tagMask);
counter[blockSize - 1] = 2;
final ctr = CTR(_cipher, counter);
ctr.streamXOR(plaintext, result);
ctr.clean();
final calculatedTag = List<int>.filled(tagLength, 0);
final cipherText = result.sublist(0, result.length - tagLength);
_authenticate(calculatedTag, tagMask, cipherText, associatedData);
result.setRange(result.length - tagLength, result.length, calculatedTag);
BinaryOps.zero(counter);
BinaryOps.zero(tagMask);
return result;
}