encapsulate method

  1. @override
EncapsulationResult encapsulate(
  1. Uint8List publicKey, {
  2. Uint8List? coins,
})
inherited

Implementation

@override
EncapsulationResult encapsulate(Uint8List publicKey, {Uint8List? coins}) {
  if (publicKey.length != _params.publicKeyBytes) {
    throw MLKEMPublicKeyWrongLengthException();
  }

  final pk = calloc<ffi.Uint8>(_params.publicKeyBytes);
  pk.asTypedList(_params.publicKeyBytes).setAll(0, publicKey);

  final ct = calloc<ffi.Uint8>(_params.ciphertextBytes);
  final ss = calloc<ffi.Uint8>(_params.sharedBytes);

  int result;
  ffi.Pointer<ffi.Uint8>? coinsPtr;
  if (coins != null) {
    if (coins.length != randomCoinsSize) {
      throw MLKEMCoinsWrongSize();
    }
    coinsPtr = calloc<ffi.Uint8>(randomCoinsSize);
    coinsPtr.asTypedList(randomCoinsSize).setAll(0, coins);
    result = _params.encDerand(ct, ss, pk, coinsPtr);
  } else {
    result = _params.enc(ct, ss, pk);
  }

  if (result != 0) {
    calloc.free(pk);
    calloc.free(ct);
    calloc.free(ss);
    if (coinsPtr != null) {
      calloc.free(coinsPtr);
    }
    throw MLKEMEncapsulationFailedException(result);
  }

  final ctBytes = Uint8List.fromList(ct.asTypedList(_params.ciphertextBytes));
  final ssBytes = Uint8List.fromList(ss.asTypedList(_params.sharedBytes));

  calloc.free(pk);
  calloc.free(ct);
  calloc.free(ss);

  if (coinsPtr != null) {
    calloc.free(coinsPtr);
  }

  return EncapsulationResult(ciphertext: ctBytes, sharedSecret: ssBytes);
}