# 如何对加密消息进行签名和验证？

By [89ew56sdf](https://paragraph.com/@89ew56sdf) · 2023-07-07

---

加密签名和验证对于数字世界中的安全通信至关重要。对消息进行签名涉及使用私钥生成可以使用相应的公钥进行验证的唯一签名。验证签名消息涉及根据原始消息和公钥检查签名。在这个答案中，我们将讨论如何以加密方式对签名消息进行签名和验证。

要签署消息，您需要有权访问私钥。私钥用于生成可以使用相应的公钥进行验证的唯一签名。有多个库可用于使用不同的编程语言对消息进行签名，例如 Web3.js、Ethers.js 和 Solidity。

Web3.js 是一个流行的 JavaScript 库，用于与以太坊区块链交互。要使用 Web3.js 对消息进行签名和验证，您需要执行以下步骤：

1.  创建 Web3.js 提供程序的实例。
    
2.  使用您的私钥创建以太坊钱包实例。
    
3.  使用signMessageEthers.js 的功能对您的消息进行签名。
    
4.  使用 Ethers.js 的功能验证您的签名消息recoverAddress。
    

下面是一个示例代码片段，演示了如何使用 Web3.js 对消息进行签名和验证：

const Web3 = require('web3'); const web3 = new Web3('[https://mainnet.infura.io/v3/YOUR-PROJECT-ID](https://mainnet.infura.io/v3/YOUR-PROJECT-ID)'); const privateKey = 'YOUR-PRIVATE-KEY'; const account = web3.eth.accounts.privateKeyToAccount(privateKey); const message = 'Hello World!'; const signature = await account.sign(message); console.log(signature.signature); // prints the signature const signerAddress = await web3.eth.accounts.recover(message, signature.signature); console.log(signerAddress); // prints the signer address

Ethers.js 是另一个流行的 JavaScript 库，用于与以太坊区块链交互。要使用 Ethers.js 签名和验证消息，您需要执行以下步骤：

1.  创建 Ethers 提供程序的实例。
    
2.  使用您的私钥创建以太坊钱包实例。
    
3.  使用signMessage以太坊功能对您的消息进行签名。
    
4.  使用以太坊功能验证您的签名消息。recoverAddress
    

下面是一个示例代码片段，演示了如何使用 Ethers.js 签名和验证消息：

const { ethers } = require('ethers'); const privateKey = 'YOUR-PRIVATE-KEY'; const providerUrl = '[https://mainnet.infura.io/v3/Y](https://mainnet.infura.io/v3/Y)

---

*Originally published on [89ew56sdf](https://paragraph.com/@89ew56sdf/5cI7jhVA6vsEsEeh477q)*
