sign function

Uint8List sign(
  1. dynamic data,
  2. dynamic privateKey, {
  3. bool isDataHexa = true,
  4. bool isPrivateKeyHexa = true,
})

Sign the data.

Implementation

Uint8List sign(
  dynamic data,
  dynamic privateKey, {
  bool isDataHexa = true,
  bool isPrivateKeyHexa = true,
}) {
  if (data is! Uint8List && data is! String) {
    throw "'data' must be a string or Uint8List";
  }

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

  if (data is String) {
    if (isDataHexa && !isHex(data)) {
      throw const FormatException("'data' must be an hexadecimal string");
    }

    if (isDataHexa) {
      data = Uint8List.fromList(hexToUint8List(data));
    } else {
      data = Uint8List.fromList(utf8.encode(data));
    }
  }

  if (privateKey is String) {
    if (isPrivateKeyHexa && !isHex(privateKey)) {
      throw const FormatException("'privateKey' must be an hexadecimal string");
    }

    if (isPrivateKeyHexa) {
      privateKey = Uint8List.fromList(hexToUint8List(privateKey));
    } else {
      privateKey = Uint8List.fromList(utf8.encode(privateKey));
    }
  }

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

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

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