Private keys are the root secret for certificate requests, TLS certificates, and signing workflows, so the key type, output path, and file permissions need to be chosen before OpenSSL writes the file. A key generated with the wrong algorithm can be rejected by the next system in the chain, while a key readable by other users can expose the identity the certificate is meant to protect.
The openssl genpkey command generates private keys through OpenSSL's generic public-key interface. RSA keys use rsa_keygen_bits to set the modulus size, and elliptic-curve keys use ec_paramgen_curve to select a named curve such as P-256.
Service keys are commonly left unencrypted and protected by file permissions so daemons can start without an interactive passphrase prompt. Encrypt private keys that will be moved, archived, or unlocked by a person, and keep passphrases out of shell history, tickets, shared transcripts, and the same directory as broadly readable certificate files.
$ install -m 700 -d ~/tls-keys
$ cd ~/tls-keys
$ umask 077
Files created after this command are not readable by group or other users unless a command changes the mode explicitly.
$ openssl genpkey -quiet -algorithm RSA -pkeyopt rsa_keygen_bits:3072 -out server.key
The -quiet option suppresses RSA generation progress dots. Use a larger RSA size only when policy or the receiving system requires it.
$ openssl genpkey -quiet -algorithm EC -pkeyopt ec_paramgen_curve:P-256 -out server-ecdsa.key
Use one key type for the final request. Keep server.key for RSA workflows, or use server-ecdsa.key when the issuer and application expect an ECDSA key.
$ ls -l server.key -rw------- 1 root root 2484 Jun 5 20:41 server.key
If group or other users can read the key, restrict it before using it in a certificate request or service configuration.
$ openssl pkey -in server.key -check -noout Key is valid
Use server-ecdsa.key in place of server.key if you generated the ECDSA key. Related: How to create a CSR using OpenSSL
$ openssl rand -base64 32 > key.pass
$ chmod 600 key.pass
Do not store a production passphrase file beside the private key unless both files are protected by the same access controls. Remove temporary passphrase files after the encrypted key has been created or moved into the intended secret store.
$ openssl genpkey -quiet -algorithm RSA -pkeyopt rsa_keygen_bits:3072 -aes-256-cbc -pass file:key.pass -out encrypted.key
$ openssl pkey -in encrypted.key -passin file:key.pass -check -noout Key is valid