HTML invokes the wallet signature and returns the verification

1. Need to import web3 link wallet
2. Need to link wallet, as mentioned in the previous article



//生成随机签名码(自定义)
var str = web3.utils.sha3("Some string to be hashed");

function signature() {
    //调取签名并打印
    web3.eth.personal.sign(str,wordAddress).then(function (accounts) {
        
        alert(accounts);
    })

}

The following is the java verification signature code

public final class EcRecoverUtil {

    /**
     * 校验签名,还原地址
     *
     * @param message   消息
     * @param signature 签名结果
     * @return 返回可能的结果,有多个
     */
    public static List<String> ecRecover(String message, String signature) {
        if (message == null || signature == null || signature.isEmpty()) {
            return Collections.emptyList();
        }
        String newMessage = "\u0019Ethereum Signed Message:\n" + message.length() + message;

        byte[] msgHash = Hash.sha3(newMessage.getBytes());
        byte[] signatureBytes = Numeric.hexStringToByteArray(signature);
        if (signatureBytes.length <= 64) {
            return Collections.emptyList();
        }
        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));

        List<String> result = new ArrayList<>();

        // Iterate for each possible key to recover
        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) {
                result.add("0x" + Keys.getAddress(publicKey));
            }
        }
        return result;
    }

    /**
     * 校验签名是否正确
     *
     * @param message   消息
     * @param signature 签名结果
     * @param address   期望地址
     * @return true 地址正确, false 错误
     */
    public static boolean checkEcRecover(String message, String signature, String address) {
        if (address == null) {
            return false;
        }
        List<String> result = ecRecover(message, signature);
        return result.stream().anyMatch(address::equalsIgnoreCase);
    }
}

rely

<dependency>
    <groupId>org.web3j</groupId>
    <artifactId>core</artifactId>
    <version>5.0.0</version>
</dependency>
<dependency>
    <groupId>com.squareup.okhttp3</groupId>
    <artifactId>okhttp</artifactId>
    <version>4.9.0</version>
</dependency>

Guess you like

Origin blog.csdn.net/qq_38935605/article/details/125299714