Thursday, July 28, 2022

[FIXED] How to sign messages on the server side using web3

Issue

I am building a decentralized app using Node.js. I need the node.js app to receive a message from the frontend, use web3.js to sign the message and send the signature back to the frontend.

I am thinking of passing as a environmental variable a predefined private key to the node.js app. Then use the private key to instantiate Web3 and call web3.personal.sign to sign the message. I need the signing process to occur on the server side, so I don't believe that using a client-side wallet like Metamask would be applicable.

I am new to Blockchain and Web3 development so I am not sure if what I am asking is feasible.


Solution

You can pass the private key to wallet.add(), and then sign the message using web3.eth.sign().

web3.eth.accounts.wallet.add(SIGNER_PRIVATE_KEY);
const message = "Hello world";

// sign
const signature = await web3.eth.sign(message, SIGNER_ADDRESS);

// recover
const recoveredSigner = web3.eth.accounts.recover(message, signature);
console.log(recoveredSigner == SIGNER_ADDRESS);


Answered By - Petr Hejda
Answer Checked By - David Goodson (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.