chacha20Poly1305Encrypt method

Map<String, Uint8List> chacha20Poly1305Encrypt({
  1. required Uint8List data,
  2. required Uint8List key,
  3. required Uint8List iv,
  4. Uint8List? aad,
})
inherited

Encrypts data using ChaCha20-Poly1305 (AEAD).

Implementation

Map<String, Uint8List> chacha20Poly1305Encrypt({
  required Uint8List data,
  required Uint8List key,
  required Uint8List iv,
  Uint8List? aad,
}) {
  if (key.length != 32) throw ArgumentError('Key must be 32 bytes for ChaCha20-Poly1305');

  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);

  final outPtr = calloc<Uint8>(data.length + 16);
  final outLen = calloc<Int>();

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

    if (iv.length != 12) {
      if (bindings.EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_IVLEN, iv.length, nullptr) != 1) {
        throw OpenSslException('Failed to set IV length');
      }
    }

    if (bindings.EVP_EncryptInit_ex(ctx, nullptr, nullptr, keyPtr.cast(), ivPtr.cast()) != 1) {
      throw OpenSslException('Failed to set Key and IV');
    }

    if (aad != null && aad.isNotEmpty) {
      final aadPtr = calloc<Uint8>(aad.length);
      aadPtr.asTypedList(aad.length).setAll(0, aad);
      try {
        if (bindings.EVP_EncryptUpdate(ctx, nullptr, outLen, aadPtr.cast(), aad.length) != 1) {
          throw OpenSslException('Failed to set AAD');
        }
      } finally {
        calloc.free(aadPtr);
      }
    }

    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;

    final tagPtr = calloc<Uint8>(16);
    try {
      if (bindings.EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_GET_TAG, 16, tagPtr.cast()) != 1) {
        throw OpenSslException('Failed to get Poly1305 Tag');
      }

      return {
        'ciphertext': Uint8List.fromList(outPtr.asTypedList(totalLen)),
        'tag': Uint8List.fromList(tagPtr.asTypedList(16)),
      };
    } finally {
      calloc.free(tagPtr);
    }
  } finally {
    calloc.free(outPtr);
    calloc.free(outLen);
    calloc.free(keyPtr);
    calloc.free(ivPtr);
    bindings.EVP_CIPHER_CTX_free(ctx);
  }
}