web3 第三章 (签名)

366 阅读1分钟

web3 大佬圈

我是 web3 小白,欢迎各大佬进群一起交流、进步。

简单方法的时候, ethers.js v6 中的方法和 v5 中的方法有些许不一样

const msg = "hello web3";
    const msgHash = ethers.hashMessage(msg);
    setHash(msgHash);
    const msgPrefixed = "\x19Ethereum Signed Message:\n" + msg.length + msg;
    const msgPrefixedHash = ethers.id(msgPrefixed);
    setPrefixedHash(msgPrefixedHash);

    const hexString = ethers.hexlify(ethers.toUtf8Bytes(msgPrefixed));
    console.log("hex", hexString);
    setHex(hexString);
    const keccak256Hash = ethers.keccak256(hexString);
    setKeccak256Hash(keccak256Hash);

    const signingKey = new ethers.SigningKey(
      "0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80"
    );

    const sig = signingKey.sign(msgHash);
    console.log("signature", sig);
    console.log("signature.r", sig.r);
    console.log("signature.s", sig.s);
    console.log("signature.v", sig.v);
    console.log("sig.serialized", sig.serialized);
    console.log("sig.compactSerialized", sig.compactSerialized);

    setSignature(sig);

    // 通过 msgHash 验签
    const address = ethers.recoverAddress(msgHash, sig);
    console.log("address", address);
    setAddress(address);

    // 通过 msg 验签
    const address2 = ethers.verifyMessage(msg, sig);
    console.log("address2", address2);
    setAddres2(address2);

image.png

使用的是 Account #0 的 private key 进行签名的, 所以后面获取的 address 就是 Account #0 的地址