aesEncrypt function

Uint8List aesEncrypt(
  1. Uint8List keyBytes,
  2. Uint8List dataToEncrypt
)

Implementation

Uint8List aesEncrypt(Uint8List keyBytes, Uint8List dataToEncrypt) {
  if (keyBytes.length != 32) {
    return Uint8List(0);
  }

  // Generate 12 random bytes for nonce
  final nonce = Uint8List(12);
  var rnd = Random.secure();
  for (int i = 0; i < 12; i++) {
    nonce[i] = rnd.nextInt(255);
  }

  final cipher = GCMBlockCipher(AESEngine())
    ..init(
        true, // encrypt (or decrypt)
        AEADParameters(
          KeyParameter(keyBytes), // the 256 bit (32 byte) key
          16 * 8, // the mac size (16 bytes)
          nonce, // the 12 byte nonce
          Uint8List(0), // empty extra data
        ));

  var encryptedData = cipher.process(dataToEncrypt);
  var b = BytesBuilder();
  b.add(nonce);
  b.add(encryptedData);
  return b.toBytes();
}