deriveKeyPair function

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

Generate a keypair using a derivation function with a seed and an index. Each keys is prepending with a curve identification. @param {String} seed Keypair derivation seed @param {int} index Number to identify the order of keys to generate @param {String} curve Elliptic curve to use (P256", "secp256k1", "ed25519")

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(<int>[0]);

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

    case 'P256':
      final Uint8List curveIdBuf = Uint8List.fromList(<int>[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(<Uint8List>[curveIdBuf, softwareIdBuf, pvBuf]),
          publicKey: concatUint8List(<Uint8List>[
            curveIdBuf,
            softwareIdBuf,
            hexToUint8List(publicKey.toHex())
          ]));

    case 'secp256k1':
      final Uint8List curveIdBuf = Uint8List.fromList(<int>[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(<Uint8List>[curveIdBuf, softwareIdBuf, pvBuf]),
          publicKey: concatUint8List(<Uint8List>[
            curveIdBuf,
            softwareIdBuf,
            hexToUint8List(publicKey.toHex())
          ]));

    default:
      throw 'Curve not supported';
  }
}