sign function

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

Sign the data @param {String | Uint8List} data Data to sign @param {String | Uint8List} privateKey Private key to use to sign the data

Implementation

Uint8List sign(dynamic data, dynamic 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 = Uint8List.fromList(hexToUint8List(data));
    } else {
      data = Uint8List.fromList(utf8.encode(data));
    }
  }

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

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

  switch (curveBuf[0]) {
    case 0:
      final ed25519.SigningKey signingKey = ed25519.SigningKey(seed: pvBuf);
      final ed25519.SignatureBase sm = signingKey.sign(data).signature;
      return Uint8List.fromList(sm);
    case 1:
      final Digest sha256 = Digest('SHA-256');
      final Uint8List msgHash = sha256.process(data);
      final elliptic.EllipticCurve ec = elliptic.getP256();
      final elliptic.PrivateKey privateKey =
          elliptic.PrivateKey.fromBytes(ec, pvBuf);
      final ecdsa.Signature sig = ecdsa.deterministicSign(privateKey, msgHash);
      return Uint8List.fromList(sig.toDER());
    case 2:
      final Digest sha256 = Digest('SHA-256');
      final Uint8List msgHash = sha256.process(data);

      final elliptic.Curve ec = elliptic.getSecp256k1();
      final elliptic.PrivateKey privateKey =
          elliptic.PrivateKey.fromBytes(ec, pvBuf);
      final ecdsa.Signature sig = ecdsa.deterministicSign(privateKey, msgHash);
      return Uint8List.fromList(sig.toDER());
    default:
      throw 'Curve not supported';
  }
}