deriveKeyPair function Null safety

KeyPair deriveKeyPair(
  1. String seed,
  2. int index,
  3. {String curve = 'ed25519'}
)

Implementation

KeyPair deriveKeyPair(String seed, int index, {String curve = 'ed25519'}) {
  if (!(seed is String)) {
    throw "'seed' must be a string";
  }

  if (!(index is int) || index < 0) {
    throw "index' must be a positive number";
  }

  final Uint8List pvBuf = derivePrivateKey(seed, index);

  switch (curve) {
    case 'ed25519':
      final Uint8List curveIdBuf = Uint8List.fromList([0]);
      final ed25519.SigningKey signingKey = ed25519.SigningKey(seed: pvBuf);
      final Uint8List pubBuf = signingKey.publicKey.toUint8List();
      return KeyPair(
          privateKey: concatUint8List([curveIdBuf, pvBuf]),
          publicKey: concatUint8List([curveIdBuf, pubBuf]));

    case 'P256':
      final Uint8List curveIdBuf = Uint8List.fromList([1]);
      final ECCurve_prime256v1 p256 = ECCurve_prime256v1();

      final ECPoint point = p256.G;

      final BigInt bigInt = BigInt.parse(hex.encode(pvBuf), radix: 16);
      final ECPoint? curvePoint = point * bigInt;
      final Uint8List pubBuf = curvePoint!.getEncoded(false);
      return KeyPair(
          privateKey: concatUint8List([curveIdBuf, pvBuf]),
          publicKey: concatUint8List([curveIdBuf, pubBuf]));

    case 'secp256k1':
      final Uint8List curveIdBuf = Uint8List.fromList([2]);
      final ECCurve_secp256k1 secp256k1 = ECCurve_secp256k1();

      final ECPoint point = secp256k1.G;

      final BigInt bigInt = BigInt.parse(hex.encode(pvBuf), radix: 16);

      final ECPoint? curvePoint = point * bigInt;
      final Uint8List pubBuf = curvePoint!.getEncoded(false);

      return KeyPair(
          privateKey: concatUint8List([curveIdBuf, pvBuf]),
          publicKey: concatUint8List([curveIdBuf, pubBuf]));

    default:
      throw 'Curve not supported';
  }
}