verify function

bool verify(
  1. dynamic sig,
  2. dynamic data,
  3. dynamic publicKey, {
  4. bool isSigHexa = true,
  5. bool isDataHexa = true,
  6. bool isPublicKeyHexa = true,
})

Implementation

bool verify(
  dynamic sig,
  dynamic data,
  dynamic publicKey, {
  bool isSigHexa = true,
  bool isDataHexa = true,
  bool isPublicKeyHexa = true,
}) {
  if (sig is! Uint8List && sig is! String) {
    throw "'sig' must be a string or Uint8List";
  }

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

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

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

    if (isSigHexa) {
      sig = Uint8List.fromList(hexToUint8List(sig));
    } else {
      throw "'signature' must be an hexadecimal string";
    }
  }

  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 (publicKey is String) {
    if (isPublicKeyHexa && !isHex(publicKey)) {
      throw const FormatException("'publicKey' must be an hexadecimal string");
    }

    if (isPublicKeyHexa) {
      publicKey = Uint8List.fromList(hexToUint8List(publicKey));
    } else {
      throw "'publicKey' must be an hexadecimal string";
    }
  }

  final curveBuf = Uint8List.fromList(publicKey.sublist(0, 1));
  final pubBuf = Uint8List.fromList(publicKey.sublist(2, publicKey.length));

  switch (curveBuf[0]) {
    case 0:
      final verifyKey = ed25519.VerifyKey(pubBuf);
      return verifyKey.verify(signature: ed25519.Signature(sig), message: data);
    case 1:
      final sha256 = Digest('SHA-256');
      final msgHash = sha256.process(data);

      final ec = elliptic.getP256();
      final publicKey = elliptic.PublicKey.fromHex(ec, uint8ListToHex(pubBuf));
      final signature = ecdsa.Signature.fromASN1(sig);
      return ecdsa.verify(publicKey, msgHash, signature);
    case 2:
      final sha256 = Digest('SHA-256');
      final msgHash = sha256.process(data);

      final ec = elliptic.getSecp256k1();
      final publicKey = elliptic.PublicKey.fromHex(ec, uint8ListToHex(pubBuf));
      final signature = ecdsa.Signature.fromASN1(sig);
      return ecdsa.verify(publicKey, msgHash, signature);

    default:
      throw 'Curve not supported';
  }
}