Skip to content

Instantly share code, notes, and snippets.

@MiguelXCruz
Created February 20, 2024 16:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MiguelXCruz/1c81a4aea79cc1b965f25f54286bd92b to your computer and use it in GitHub Desktop.
Save MiguelXCruz/1c81a4aea79cc1b965f25f54286bd92b to your computer and use it in GitHub Desktop.
This piece of code compares if the recovered walletAddress from the signedMessage and Signature matches the desired WalletAddress. This way you can check if the ECDSA signature is valid
// This piece of code compares if the recovered walletAddress from the signedMessage and Signature matches the desired WalletAddress.
// This way you can check if the ECDSA signature is valid
public boolean isECDSAValidSignature(String walletAddress, String signature, String originalMessage)
throws SignatureException, UnsupportedEncodingException {
if (signature.startsWith("0x")) {
signature = signature.substring(2);
}
String r = signature.substring(0, 64);
String s = signature.substring(64, 128);
String v = signature.substring(128, 130);
byte[] messageHash = originalMessage.getBytes("UTF-8");
byte[] messageHashBinary = Hash.sha3(messageHash);
// Using Sign.signedPrefixedMessageToKey for EIP-712 compliant signatures.
String pubkey = Sign.signedPrefixedMessageToKey(messageHashBinary,
new Sign.SignatureData(
hexStringToByteArray(v)[0],
hexStringToByteArray(r),
hexStringToByteArray(s)))
.toString(16);
String recoveredAddress = "0x" + Keys.getAddress(pubkey);
recoveredAddress = Keys.toChecksumAddress(recoveredAddress);
if (recoveredAddress.equals(walletAddress)){
return true;
}
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment