当前位置: 代码迷 >> 综合 >> Web3-Js:以太坊签名数据以及验证
  详细解决方案

Web3-Js:以太坊签名数据以及验证

热度:51   发布时间:2024-02-13 13:48:47.0

数据签名:
web3.eth.sign(data, address )
解锁账户:
web3.eth.personal.unlockAccount(address, password, unlockDuraction)
unlockDuration 帐户保持解锁状态的持续时间
验证签名:
web3.eth.accounts.recover();

const Web3 = require('web3');
const ethereumUri = 'http://127.0.0.1:8545';
const web3 = new Web3(new Web3.providers.HttpProvider(ethereumUri));
const address = "以太坊账户";  //签名账户,需要解锁let msg = web3.utils.utf8ToHex("Hello world")  //要发送的data
//let msg = "Hello world";
//签名 有好多种方式去签名
let signature = web3.eth.sign(msg,address).then(function(receipte){console.log(receipte);let r = receipte.slice(0, 66)let s = '0x' + receipte.slice(66, 130)let v = '0x' + receipte.slice(130, 132)console.log('r', r) //签名的前32个字节console.log('s', s) //签名的后32个字节console.log('v', v)//恢复值+ 27console.log(web3.utils.toDecimal(v));//验证console.log("原始rlp编码验证:",web3.eth.accounts.recover(msg,receipte ));// message, v, r, sconsole.log("vrs验证:",web3.eth.accounts.recover(msg,v,r,s));//打印下签名的人console.log("签名者是",address)}).catch((error)=>{console.log(error);});