Any way for openssl to generate private key with 400 (-r——–) permissions from the start

file-permissionsopensslumask

I use openssl to generate private keys and CSRs in a script. The script needs to generate the key first, then call chmod 400 whatever.key to change the permissions of the private key to something more secure.

Is there any way to eliminate the second step and have openssl create the file with appropriate permissions from the start? It would seem cleaner to me to not have the private key readable by other processes, even for a millisecond.

Can you use umask in a script to do something like this or is there another way?

Best Answer

I found an answer to my question over at unix.stackexchange.com.

The idea is to use umask and run the commands in round brackets to execute it in a subshell, so umask doesn't affect the rest of the script.

( umask 077; openssl rsa -in secure.key -out insecure.key )