Created
February 20, 2024 16:34
-
-
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 file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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