How one can securely generate a new raw private key from a UNIX command line?
This private key can be then imported to wallet apps or web3.js.
Ethereum Stack Exchange is a question and answer site for users of Ethereum, the decentralized application platform and smart contract enabled blockchain. It only takes a minute to sign up.
Sign up to join this communityIf you have openssl installed, you can run
openssl rand -hex 32
Note: This will generate a 32 bytes sequence. It never verifies that the sequence is a valid private key.
There's a tiny possibility that some outputs will not generate a valid private key (a sequence of 32 zeros bytes), or a number above the elliptic curve order (FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFE BAAEDCE6 AF48A03B BFD25E8C D0364141).
If you are really paranoid, you should verify it is a valid private key.
Well, if you're using NodeJS (as implied from your question), then you may as well do:
const crypto = require("crypto");
const privateKey = "0x" + crypto.randomBytes(32).toString("hex");
You can use /dev/urandom
as a safe cryptographic random number generator. The following reads 32 bytes (256 bits) from the random number generator and formats it as a single hex string.
head -c 32 /dev/urandom|xxd -ps -c 32
Example output:
bf44080bd48031e2d793f2d8b7bc06f8e52be06fe9fd0d0fd1a8411d04686c3a
Generating with Python and web3.py
:
# Web3.py 6.0+
python -c "from web3 import Web3; w3 = Web3(); acc = w3.eth.account.create(); print(f'private key={w3.to_hex(acc._private_key)}, account={acc.address}')"
# Web3.py 5.0 and older
python -c "from web3 import Web3; w3 = Web3(); acc = w3.eth.account.create(); print(f'private key={w3.toHex(acc.privateKey)}, account={acc.address}')"
Outputs:
private key=0xb62774c4d8dbcbe3641e7d78c80fe04899914d531d010f455788b94885f56446,
account=0xCFe4DA2084Db71E83b7833Fb267A6caE459e31dD