public boolean verifySignature(String from, String resource, String signature) {
String prefix = "\u0019Ethereum Signed Message:\n" + resource.length();
byte[] msgHash = Hash.sha3((prefix + resource).getBytes());
byte[] signatureBytes = Numeric.hexStringToByteArray(signature);
byte v = signatureBytes[64];
if (v < 27) {
v += 27;
}
Sign.SignatureData sd = new Sign.SignatureData(
v,
Arrays.copyOfRange(signatureBytes, 0, 32),
Arrays.copyOfRange(signatureBytes, 32, 64));
String addressRecovered = null;
boolean match = false;
for (int i = 0; i < 4; i++) {
BigInteger publicKey = Sign.recoverFromSignature(
(byte) i,
new ECDSASignature(new BigInteger(1, sd.getR()), new BigInteger(1, sd.getS())),
msgHash);
if (publicKey != null) {
addressRecovered = "0x" + Keys.getAddress(publicKey);
if (addressRecovered.equals(from)) {
match = true;
break;
}
}
}
log.info("verify:" + resource + " : " + signature + " ==> " + addressRecovered);
return match;
}
|