X25519Keypair constructor

X25519Keypair({
  1. required List<int> privateKey,
  2. required List<int> publicKey,
  3. bool validatePublicKey = false,
})

Public constructor with validation of key lengths and public key canonicality.

Implementation

factory X25519Keypair({
  required List<int> privateKey,
  required List<int> publicKey,
  bool validatePublicKey = false,
}) {
  if (privateKey.length != Ed25519KeysConst.privKeyByteLen) {
    throw ArgumentException.invalidOperationArguments(
      "X25519Keypair",
      name: "privateKey",
      reason: 'Invalid private key bytes length',
    );
  }
  if (publicKey.length != Ed25519KeysConst.pubKeyByteLen) {
    throw ArgumentException.invalidOperationArguments(
      "X25519Keypair",
      name: "publicKey",
      reason: 'Invalid public key bytes length',
    );
  }
  final u = BigintUtils.fromBytes(publicKey, byteOrder: Endian.little);
  if (u >= X25519KeyConst.p) {
    throw ArgumentException.invalidOperationArguments(
      "X25519Keypair",
      name: "uBytes",
      reason: 'Invalid public key',
    );
  }
  if (validatePublicKey) {
    final key = X25519.scalarMultBase(privateKey);
    if (!BytesUtils.bytesEqual(key.publicKey, publicKey)) {
      throw CryptoException.failed(
        "X25519Keypair",
        reason: "Validation public key failed.",
      );
    }
  }
  return X25519Keypair._(privateKey: privateKey, publicKey: publicKey);
}