废话不多说,直接贴代码
public class Web3jUtils {
public static boolean isSignatureValid(final String address, final String signature, final String message) {
log.info("isSignatureValid invoked for Address {} with Signature {} and Message {} ", address, signature,
message);
final String personalMessagePrefix = "\u0019Ethereum Signed Message:\n";
boolean match = false;
final String prefix = personalMessagePrefix + message.length();
final byte[] msgHash = Hash.sha3((prefix + message).getBytes());
final byte[] signatureBytes = Numeric.hexStringToByteArray(signature);
byte v = signatureBytes[64];
if (v < 27) {
v += 27;
}
final Sign.SignatureData sd = new Sign.SignatureData(v,
Arrays.copyOfRange(signatureBytes, 0, 32),
Arrays.copyOfRange(signatureBytes, 32, 64));
String addressRecovered = null;
// Iterate for each possible key to recover
for (int i = 0; i < 4; i++) {
final 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(address)) {
match = true;
break;
}
}
}
return match;
}
}