encrypt method

  1. @override
Future<EncryptedPayload> encrypt({
  1. required Uint8List data,
  2. required Uint8List key,
  3. Uint8List? iv,
})
override

Encrypt the data with the given key, and an optional nonce.

Implementation

@override
Future<EncryptedPayload> encrypt({
  required Uint8List data,
  required Uint8List key,
  Uint8List? iv,
}) async {
  // AES-CBC with 265 bit keys and HMAC-SHA256 authentication.
  final algorithm = AesCbc.with256bits(macAlgorithm: MacAlgorithm.empty);
  final secretKey = SecretKey(List<int>.unmodifiable(key));
  final nonce = Uint8List.fromList(iv ?? algorithm.newNonce());

  // Encrypt the data
  final box = await algorithm.encrypt(
    data,
    secretKey: secretKey,
    nonce: nonce,
  );

  final hmac = Hmac.sha256();
  final payload = Uint8List.fromList([...box.cipherText, ...box.nonce]);
  final mac = await hmac.calculateMac(payload, secretKey: secretKey);

  return EncryptedPayload(
    data: hex.encode(box.cipherText),
    hmac: hex.encode(mac.bytes),
    iv: hex.encode(box.nonce),
  );
}