1.根据私钥获取密钥
public static void main(String[] args) {
String priKey = "45e62c6b91ae6bc0e1a69ba630eea7ad50ef42411358b3c4784c0da01092423a";
String pubKey = "0207c200b9751a48313ee8e5fd01c9925659d290abd6e0dbfbdef73f518af560cc";
Credentials credentials = Credentials.create(priKey);
BigInteger publicKey = credentials.getEcKeyPair().getPublicKey();
Long l = System.currentTimeMillis();
String s = l.toString();
Sign.SignatureData signMessage = Sign.signMessage(s.getBytes(), credentials.getEcKeyPair());
System.out.println("公钥:" + publicKey);
System.out.println("地址:" + credentials.getAddress());
System.out.println("content" + s);
System.out.println("0x" + Hex.toHexString(signMessage.getR()) + Hex.toHexString(signMessage.getS()) + Hex.toHexString(signMessage.getV()));
}```
private boolean verifySignResult(String userPublicKey, String content, String signature) {
// 公钥去解析密文
byte[] bytes = Hash.sha3(content.getBytes());
// byte[] loginHashBytes = Hex.decode(content);
// byte[] messageHash = Sign.getEthereumMessageHash(loginHashBytes);
//还原r,s,v
byte[] r = Hex.decode(signature.substring(2, 66));
byte[] s = Hex.decode(signature.substring(66, 130));
byte[] v = Hex.decode(signature.substring(130, 132));
Sign.SignatureData signatureData = new Sign.SignatureData(v, r, s);
//获得被签名的原文
String publicKey = null;
try {
publicKey = Sign.signedMessageHashToKey(bytes, signatureData).toString();
} catch (SignatureException e) {
e.printStackTrace();
}
//还原时间戳原文
// String timeStamp = bigInteger.toString();
//还原时间戳
// log.info("timeStamp={}", timeStamp);
return userPublicKey.equals(publicKey);
}
private static boolean verify(String userPublicKey, String content, String signature) {
byte[] s = Hash.sha3(content.getBytes());
byte[] bytes = Numeric.hexStringToByteArray(signature);
byte v = bytes[64];
if (v < 27) {
v += 27;
}
Sign.SignatureData signatureData = new Sign.SignatureData(v, Arrays.copyOfRange(bytes, 0, 32),
Arrays.copyOfRange(bytes, 32, 64));
boolean match = false;
for (int i = 0; i < 4; i++) {
BigInteger publicKey = Sign.recoverFromSignature(
(byte) i,
new ECDSASignature(new BigInteger(1, signatureData.getR()), new BigInteger(1, signatureData.getS())),
s);
if (publicKey != null) {
match = userPublicKey.equals(publicKey.toString());
if (match) {
return match;
}
}
}
return match;
}