encapsulate method

  1. @override
Future<({Uint8List ciphertext, Uint8List sharedSecret})> encapsulate(
  1. Uint8List publicKey
)
override

Encapsulate a fresh shared secret against publicKey.

Returns the ciphertext to transmit to the holder of the matching secret key, together with the sharedSecret that both parties will derive.

Implementation

@override
Future<({Uint8List ciphertext, Uint8List sharedSecret})> encapsulate(
    Uint8List publicKey) async {
  if (publicKey.length != publicKeyLength) {
    throw ArgumentError.value(publicKey.length, 'publicKey',
        'X-Wing public key must be $publicKeyLength bytes');
  }
  final Uint8List mlKemPublic = publicKey.sublist(0, _mlKemPublicKeyLength);
  final Uint8List x25519Public = publicKey.sublist(_mlKemPublicKeyLength);

  final (ciphertext: ctM, sharedSecret: ssM) =
      await _mlKem.encapsulate(mlKemPublic);

  final ephemeral = await _x25519.generateKeyPair();
  final Uint8List ctX = ephemeral.publicKey;
  final Uint8List ssX = await _x25519.dh(ephemeral.privateKey, x25519Public);

  final Uint8List ciphertext = Uint8List(ciphertextLength)
    ..setRange(0, _mlKemCiphertextLength, ctM)
    ..setRange(_mlKemCiphertextLength, ciphertextLength, ctX);
  return (
    ciphertext: ciphertext,
    sharedSecret: _combine(ssM, ssX, ctX, x25519Public),
  );
}