Automatically Entering Passphrase in Openssl Command

Automatically Entering Passphrase in Openssl Command

I'm writing a script that automatically enters the user's input for an openssl command, but I can't find a way of entering the required passphrase automatically by the script. What I've tried:

spawn sudo openssl x509 -req -in client.csr -CA /etc/mosquitto/ca_certificates/ca.crt -CAkey /etc/mosquitto/ca_certificates/ca.key -CAcreateserial -out client.crt -days 15; 
expect 'Enter pass phrase for /etc/mosquitto/ca_certificates/ca.key:'
send '1234\n'

Doesn't work (spawn and send not found)

printf '1234\n' | sudo openssl x509 -req -in client.csr -CA /etc/mosquitto/ca_certificates/ca.crt -CAkey /etc/mosquitto/ca_certificates/ca.key -CAcreateserial -out client.crt -days 15; 

Doesn't work, stays waiting for the passphrase and programs never finishes, unless I enter '1234' manually.

In other cases, it works with printf:

printf 'ES\n\n\n\n\nclient'$n'\n\n\n\n' | sudo openssl req -out client.csr -key client.key -new; 

My guess is that printf doesn't work if the input it's hidden. Any ideas?

1

2 Answers

Found a way of doing it without using expect:

You basically need to include --passin pass:'your_passphrase' in the command

For example: sudo openssl x509 -req -in client.csr -CA /etc/mosquitto/ca_certificates/ca.crt -CAkey /etc/mosquitto/ca_certificates/ca.key -CAcreateserial -out client.crt --passin pass:1234 -days 15;

Source

There are other ways of doing it, such as loading a password file, which is more secure, as discussed here

The process that creates a password protected key file needs a password which gets used to store this output file. So, the -passin argument you use is for reading an input file. From the documentation:

-passin arg - The input file password source.

Instead you need the proper option to specify the output password, i.e.

-passout arg - The output file password source.

In this case to open the /etc/mosquitto/ca_certificates/ca.key key you need this:

sudo openssl x509 \
-passin pass:'1234' \
-req \
-in client.csr \
-CA /etc/mosquitto/ca_certificates/ca.crt \
-CAkey /etc/mosquitto/ca_certificates/ca.key 
-CAcreateserial \
-out client.crt \
-days 15 

Your Answer

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

James H. Sterling
Author

James H. Sterling

James Sterling reports on renewable energy developments, climate policy, ecological conservation, and green tech innovations around the globe.