When I sign a transacction in a website I do it with Metamask and my private key is safe.

Now I am signing transactions automatically from a NodeJS like the next code.

Can I somehow hide my privateKey in case someone has access to the server?

const privateKey = 'my wallet secret private key';  

const rawTransaction = { "to": 0x000000, "value": value, "gas": 100000 };
web3js.eth.accounts.signTransaction(rawTransaction, privateKey)
    .then(signedTx => web3js.eth.sendSignedTransaction(signedTx.rawTransaction))    
    .then(function(receipt){ console.log("Tranx Done!"); 

I think this is difficult to achieve because even if you encrypt the key and save it in a database, a hacker will be able to access the database and decrypt your key. But you can make it more difficult.

1. You can encrypt your private key with the "crypto-js" package, and save it in an external text file (in a parent folder of your project) and recover it in your NODE script after.

Then you can read that file and decrypt the key to sign your transaction.

It's not perfect but at least it helps make it not so obvious.

Maybe this code helps you to encrypt and decrypt it. Good luck.

var CryptoJS = require("crypto-js");

// Encrypt and save into a external file
var cipherKey = CryptoJS.AES.encrypt('my private key', 'secret password').toString();

// Decrypt in your code
var bytes  = CryptoJS.AES.decrypt(cipherKey , 'secret password');
var privateKey= bytes.toString(CryptoJS.enc.Utf8);

console.log(privateKey); //'mi private key'

2. You can declare your private key in an external environment variable to prevent that your key is hard-coded in your code and accidentally sent to GitHub or somewhere else ;) You can save your key in a .env file in your project directory and read this file with the npm package dotenv

require('dotenv').config({ path: '/full/custom/path/to/your/env/vars' })
var yourKey= process.env.MYKEY;

.env file


3. Both 1 and 2 together ;)


Finally I am saving my private key value in an external .js file in the parent folder of my server project.

const private  = require('../private.js');
var privateKey = private.PRIVATE_KEY;

The code of private.js file to declare the var value

module.exports.PRIVATE_KEY= "00000000000000000";
  • 1
    Cool solution to avoid load third party modules like "dotenv"
    – JR Grande
    Mar 30 at 22:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.