web3 的身份验证之以太坊签名消息
https://zhuanlan.zhihu.com/p/535573066
python 实现
#coding=utf-8 from web3 import Web3 from eth_account.messages import encode_defunct if __name__ == '__main__': ''' //hook metamask (function() { 'use strict'; var old = window.ethereum.request window.ethereum.request = function(method,params){ console.log("method:",method); console.log("params:",params); console.log("old:",old); return old.call(this,method,params); }; // Your code here... })(); ''' web3 = Web3(Web3.HTTPProvider('HTTP://127.0.0.1:8545')) #metamask 签名文本 message = 'Welcome to the CREW³ Questboard, please sign this message to verify your identity. Your custom message is: kgfzszccCa1bJ2pVWs~DUjLo0EcTACF2wQsdwgfHyhb8aZBjcvxTmMFRiAGZIpzU' #metamask hook参数 hex_str = '0x57656c636f6d6520746f207468652043524557c2b3205175657374626f6172642c20706c65617365207369676e2074686973206d65737361676520746f2076657269667920796f7572206964656e746974792e20596f757220637573746f6d206d6573736167652069733a206b67667a737a6363436131624a32705657737e44556a4c6f3045635441434632775173647767664879686238615a426a637678546d4d46526941475a49707a55' #下面两种方法是等效的 hex_16 = web3.toBytes(int(hex_str, 16)).decode('utf-8') print(f'hex_16:{hex_16}') print(web3.toText(hexstr=hex_str)) #初始化wallet private_key = 'private_key' wallet = web3.eth.account.from_key(private_key) #编码签名文本 message = encode_defunct(text=message) #得到编码后的hex_str #对hex_str进行签名 signed_message = wallet.sign_message(message) #web3.eth.account.sign_message() 等效方法 #得到签名后的hex字符串 print(web3.toHex(primitive=signed_message.signature))