1

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.

3

If 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 the private key.

3
  • Thanks. I think this is the shortest method, in the sense it is least typing and easy to remember. The only downside is that OpenSSL libraries and tools are somewhat painto to get installed on macOS sometime. Apr 30 '20 at 19:23
  • In the case, what happens if you create a number that is not a valid on the elliptic curve? Would I get a compromisable address or would tools complain when I import it as an account? Apr 30 '20 at 19:25
  • 1
    @MikkoOhtamaa Good wallet should reject invalid input, poorly programmed will carry on but the output will be undeterministic and might be incompatible other. In the worst case they will assume that it is valid and generate an address that cannot be used. The private key will not generate a valid signature, so you cannot spend funds from the address. Best case wallets will complain and refuse to use the private key.
    – Ismael
    Apr 30 '20 at 21:25
1

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

More technical information about Ethereum accounts.

0
1

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");
3
  • Yep! This is good. I was also hoping to find something ultra portable, so that the generation method can be done on any standard POSIX environment Apr 30 '20 at 19:26
  • @MikkoOhtamaa: Any NodeJS solution is ultra portable by definition (since NodeJS is OS agnostic). Apr 30 '20 at 22:05
  • yes, but you still need to install Node.js. It does not come with the default macOS installation. And installing Node just to create a private key is a bit overkill. May 1 '20 at 12:48

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.