deriveKeyPair function Null safety

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

Implementation

KeyPair deriveKeyPair(String seed, int index, {String curve = 'P256'}) {
  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);
  final Uint8List softwareIdBuf = Uint8List.fromList([0]);

  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, softwareIdBuf, pvBuf]),
          publicKey: concatUint8List([curveIdBuf, softwareIdBuf, pubBuf]));

    case 'P256':
      final Uint8List curveIdBuf = Uint8List.fromList([1]);
      final elliptic.EllipticCurve ec = elliptic.getP256();
      final elliptic.PrivateKey privateKey =
          elliptic.PrivateKey.fromBytes(ec, pvBuf);
      final elliptic.PublicKey publicKey = ec.privateToPublicKey(privateKey);
      return KeyPair(
          privateKey: concatUint8List([curveIdBuf, softwareIdBuf, pvBuf]),
          publicKey: concatUint8List(
              [curveIdBuf, softwareIdBuf, hexToUint8List(publicKey.toHex())]));

    case 'secp256k1':
      final Uint8List curveIdBuf = Uint8List.fromList([2]);
      final elliptic.Curve ec = elliptic.getSecp256k1();
      final elliptic.PrivateKey privateKey =
          elliptic.PrivateKey.fromBytes(ec, pvBuf);
      final elliptic.PublicKey publicKey = ec.privateToPublicKey(privateKey);
      return KeyPair(
          privateKey: concatUint8List([curveIdBuf, softwareIdBuf, pvBuf]),
          publicKey: concatUint8List(
              [curveIdBuf, softwareIdBuf, hexToUint8List(publicKey.toHex())]));

    default:
      throw 'Curve not supported';
  }
}