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?


Solution 1:

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