decrypt static method

Future<Uint8List> decrypt(
  1. EncryptedData encrypted,
  2. Uint8List key
)

Decrypts AES-256-GCM encrypted data.

encrypted - The encrypted data to decrypt key - The 32-byte AES-256 key

Throws crypto.SecretBoxAuthenticationError if authentication fails. Throws ArgumentError if the key or ciphertext length is incorrect.

Implementation

static Future<Uint8List> decrypt(
  EncryptedData encrypted,
  Uint8List key,
) async {
  if (key.length != keySize) {
    throw ArgumentError('Key must be $keySize bytes (AES-256)');
  }

  final algorithm = crypto.AesGcm.with256bits();
  final secretKey = crypto.SecretKey(key);

  // Split ciphertext and MAC (last 16 bytes)
  final ciphertext = encrypted.ciphertext;
  if (ciphertext.length < tagSize) {
    throw ArgumentError(
      'Ciphertext too short: expected at least $tagSize bytes for the auth tag',
    );
  }

  final macBytes = ciphertext.sublist(ciphertext.length - tagSize);
  final actualCiphertext = ciphertext.sublist(0, ciphertext.length - tagSize);

  final secretBox = crypto.SecretBox(
    actualCiphertext,
    nonce: encrypted.nonce,
    mac: crypto.Mac(macBytes),
  );

  final plaintext = await algorithm.decrypt(secretBox, secretKey: secretKey);
  return Uint8List.fromList(plaintext);
}