sign function

Uint8List sign(
  1. dynamic data,
  2. dynamic privateKey
)

Implementation

Uint8List sign(data, privateKey) {
  if (!(data is Uint8List) && !(data is String)) {
    throw "'data' must be a string or Uint8List";
  }

  if (!(privateKey is Uint8List) && !(privateKey is String)) {
    throw "'privateKey' must be a string or Uint8List";
  }

  if (data is String) {
    if (isHex(data)) {
      data = hexToUint8List(data);
    } else {
      data = Uint8List.fromList(utf8.encode(data));
    }
  }

  if (privateKey is String) {
    if (isHex(privateKey)) {
      privateKey = hexToUint8List(privateKey);
    } else {
      privateKey = Uint8List.fromList(utf8.encode(privateKey));
    }
  }

  Uint8List curveBuf = privateKey.sublist(0, 1);
  Uint8List pvBuf = privateKey.sublist(1, privateKey.length);

  switch (curveBuf[0]) {
    case 0:
      Digest sha512 = new Digest("SHA-512");
      Uint8List msgHash = sha512.process(data);
      var signingKey = ed25519.SigningKey(seed: pvBuf);
      ed25519.SignatureBase sm = signingKey.sign(msgHash).signature;
      return Uint8List.fromList(sm);

    case 1:
      Digest sha256 = new Digest("SHA-256");
      Uint8List msgHash = sha256.process(data);
      final ECDomainParameters _params = ECCurve_prime256v1();

      final digest = SHA256Digest();
      final signer = ECDSASigner(null, HMac(digest, 64));
      final key = ECPrivateKey(decodeBigInt(pvBuf), _params);

      signer.init(true, PrivateKeyParameter(key));
      var sig = signer.generateSignature(msgHash) as ECSignature;

      var topLevel = new asn1lib.ASN1Sequence();
      topLevel.add(asn1lib.ASN1Integer(sig.r));
      topLevel.add(asn1lib.ASN1Integer(sig.s));
      return topLevel.encodedBytes;

    case 2:
      Digest sha256 = new Digest("SHA-256");
      Uint8List msgHash = sha256.process(data);
      final ECDomainParameters _params = ECCurve_secp256k1();

      final digest = SHA256Digest();
      final signer = ECDSASigner(null, HMac(digest, 64));
      final key = ECPrivateKey(decodeBigInt(pvBuf), _params);

      signer.init(true, PrivateKeyParameter(key));
      var sig = signer.generateSignature(msgHash) as ECSignature;

      var topLevel = new asn1lib.ASN1Sequence();
      topLevel.add(asn1lib.ASN1Integer(sig.r));
      topLevel.add(asn1lib.ASN1Integer(sig.s));
      return topLevel.encodedBytes;

    default:
      throw "Curve not supported";
  }
}