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))
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix