aes256CbcEncrypt method

Uint8List aes256CbcEncrypt({
  1. required Uint8List data,
  2. required Uint8List key,
  3. required Uint8List iv,
})
inherited

Encrypts data using AES-256-CBC with PKCS#7 padding.

key must be 32 bytes and iv must be 16 bytes.

Implementation

Uint8List aes256CbcEncrypt({
  required Uint8List data,
  required Uint8List key,
  required Uint8List iv,
}) {
  if (key.length != 32) {
    throw ArgumentError('Key must be 32 bytes for AES-256-CBC');
  }
  if (iv.length != 16) {
    throw ArgumentError('IV must be 16 bytes for AES-256-CBC');
  }

  final ctx = bindings.EVP_CIPHER_CTX_new();
  if (ctx == nullptr) {
    throw OpenSslException('Failed to create EVP_CIPHER_CTX');
  }

  final keyPtr = calloc<Uint8>(key.length);
  keyPtr.asTypedList(key.length).setAll(0, key);

  final ivPtr = calloc<Uint8>(iv.length);
  ivPtr.asTypedList(iv.length).setAll(0, iv);

  // Output buffer needs at most input length + block size (16 bytes).
  final outPtr = calloc<Uint8>(data.length + 16);
  final outLen = calloc<Int>();

  try {
    final cipher = bindings.EVP_aes_256_cbc();
    if (bindings.EVP_EncryptInit_ex(ctx, cipher, nullptr, keyPtr.cast(), ivPtr.cast()) != 1) {
      throw OpenSslException('EVP_EncryptInit_ex failed');
    }

    final inPtr = calloc<Uint8>(data.length);
    inPtr.asTypedList(data.length).setAll(0, data);

    int totalLen = 0;
    try {
      if (bindings.EVP_EncryptUpdate(ctx, outPtr.cast(), outLen, inPtr.cast(), data.length) != 1) {
        throw OpenSslException('EVP_EncryptUpdate failed');
      }
      totalLen = outLen.value;
    } finally {
      calloc.free(inPtr);
    }

    if (bindings.EVP_EncryptFinal_ex(ctx, (outPtr + totalLen).cast(), outLen) != 1) {
      throw OpenSslException('EVP_EncryptFinal_ex failed');
    }
    totalLen += outLen.value;

    return Uint8List.fromList(outPtr.asTypedList(totalLen));
  } finally {
    calloc.free(outPtr);
    calloc.free(outLen);
    calloc.free(keyPtr);
    calloc.free(ivPtr);
    bindings.EVP_CIPHER_CTX_free(ctx);
  }
}