当前位置: 首页 > 工具软件 > web3j > 使用案例 >

Web3j签名与验签

禹正阳
2023-12-01

        闲时,给大家讲讲本人在做项目过程中涉及到的区块链签名相关业务,希望对做区块链行业的同行有所帮助。

        主要是针对Java程序员围绕web3j库进行区块链以太坊开发,本地签名与验签。

代码实例:

/**
 * @Description: Web3j签名验签
 */
public class Web3j {
    // 钱包私钥
    private static final String priKey = "e62248374af86aa480f9cebd44f04cd02b915130d4fbda885a201488257b0a17";
    // 钱包地址
    private static final String walletAddress = "0x5ebacac108d665819398e5c37e12b0162d781398";

    public static void main(String[] args) {
        // 原文
        String content = "青年人的责任重大!努力吧...";

        // 原文摘要字节数组
        byte[] contentHashBytes = Hash.sha3(content.getBytes());

        // 原文摘要16进制字符串
        String contentHashHex = Hex.toHexString(contentHashBytes);

        Credentials credentials = Credentials.create(priKey);
        Sign.SignatureData signMessage = Sign.signPrefixedMessage(contentHashBytes, credentials.getEcKeyPair());
        System.out.println(Hex.toHexString(signMessage.getR()));
        System.out.println(Hex.toHexString(signMessage.getS()));
        System.out.println(Hex.toHexString(signMessage.getV()));

        // 签名后的字符串
        String signStr = "0x" + Hex.toHexString(signMessage.getR()) + Hex.toHexString(signMessage.getS()) + Hex.toHexString(signMessage.getV());
        System.out.println("signStr=" + signStr);

        try {
            // 原文摘要 添加 ETH签名头信息后再生成摘要
            byte[] messageHash = Sign.getEthereumMessageHash(Hex.decode(contentHashHex));

            //通过摘要和签名后的数据,还原公钥
            Sign.SignatureData signatureData = new Sign.SignatureData(signMessage.getV(), signMessage.getR(), signMessage.getS());
            BigInteger publicKey = Sign.signedMessageHashToKey(messageHash, signatureData);

            //还原地址 0x5E32cc9cF83e6f346830fc11e207ac4b91213f30
            String parseAddress = "0x" + Keys.getAddress(publicKey);

            System.err.println("Address::" + parseAddress);
        } catch (SignatureException e) {
            e.printStackTrace();
        }
    }
}

青年人的责任重大!努力吧...

 类似资料: