简体   繁体   English

如何在 Python 中使用以太坊私钥签署消息?

[英]How can I sign message using an Ethereum private key in Python?

On JS I can use ethers to sign message and get v r s在 JS 上,我可以使用 ethers 签署消息并获取 v r s

const { utils } = require("ethers");

// for example types = [address, uint256], params = [0x4F..., 100], privateKey=0x45..
const getSignString = (types=undefined, params=undefined, privateKey=undefined) => {
    const digest = utils.keccak256(utils.solidityPack(types, params));
    return new utils.SigningKey(privateKey).signDigest(digest);
  };

// return obj.r, obj.v, obj.s ...

How can i do this on Python?我怎么能在 Python 上做到这一点?


Find answer for my question为我的问题寻找答案

def custom_sign_message(types: List, params: List, private_key: str) -> SignMessage:
    """
    Sign message
    types: types of data, for example ["address", "uint256", ...]
    params: params to sign. len(types) == len(params)
    private key: customer private key
    return signed message, containing v, r, s for tests
    """
    signature = Web3.toHex(Web3.soliditySha3(types, params))
    message = encode_defunct(hexstr=signature)
    signed_message = w3.eth.account.sign_message(message, private_key)
    res = eth_account.account.Account.signHash(message.body, private_key)
    return SignMessage(
        v=res.v,
        r=Web3.toHex(res.r),
        s=Web3.toHex(res.s),
        message_hash=signed_message.messageHash,
    )

You can use eth_account sign_message method.您可以使用eth_account sign_message方法。

To pack the parameters to binary you can use eth-abi package .要将参数打包为二进制文件,您可以使用eth-abi package

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用 Python 从已知私钥生成以太坊公钥 - How do I generate an Ethereum public key from a known private key using Python 我有模数和私有指数。 如何构建RSA私钥并签名消息? - I have modulus and private exponent. How to construct RSA private key and sign a message? 如何使用 python 从存储在 AWS 的 Secrets Manager 中的私钥生成 OpenSSH RSA 密钥? - How can I generate OpenSSH RSA key using python from the private key stored in Secrets manager in AWS? UnicodeDecodeError:将以太坊私钥的 python 字节串转换为字符串? - UnicodeDecodeError: Converting python bytestring of ethereum private key to string? 如何使用 python 中的 RSA 私钥进行加密? - How can I encrypt with a RSA private key in python? 如何加密消息并使用 PyCryptodome Python 对其进行签名? - How to encrypt a message and sign it using PyCryptodome Python? RSA 在 python 中用私钥对字符串进行签名 - RSA sign a string with private key in python 我们如何使用python的密码库从私钥(受密码保护)中检索公钥? - How can we retrieve public key from private key ( protected with passphrase ) using python's Cryptography library? 如何在 Python 中创建以太坊钱包? - How do I create an ethereum wallet in Python? Python密码术:无法使用PKCS1v15填充使用RSA私钥进行签名 - Python Cryptography: Cannot sign with RSA private key using PKCS1v15 padding
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM