encrypt static method

Future<EncryptedData> encrypt(
  1. Uint8List plaintext,
  2. Uint8List key
)

Encrypts data using AES-256-GCM.

plaintext - The data to encrypt key - The 32-byte AES-256 key

Returns EncryptedData containing ciphertext and nonce. The ciphertext includes the 16-byte authentication tag.

Throws ArgumentError if the key length is incorrect.

Implementation

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

  final nonce = randomBytes(nonceSize);
  final algorithm = crypto.AesGcm.with256bits();

  final secretKey = crypto.SecretKey(key);
  final secretBox = await algorithm.encrypt(
    plaintext,
    secretKey: secretKey,
    nonce: nonce,
  );

  // Combine ciphertext + MAC
  final ciphertext = Uint8List(
    secretBox.cipherText.length + secretBox.mac.bytes.length,
  );
  ciphertext.setAll(0, secretBox.cipherText);
  ciphertext.setAll(secretBox.cipherText.length, secretBox.mac.bytes);

  return EncryptedData(ciphertext: ciphertext, nonce: nonce);
}