I am writing a shell script which executes a command which requires a password. I cannot put password in plain text in the script. I read about openssl encrypt decrypt mechanism but for encrypting a file again I need a password which again I cannot put in the script. I am clueless what is the best way to have a script execute a command using a secure password.
After reading about "Using OpenSSL to encrypt messages and files on Linux", the following approach might work for you.
Assuming you have private and public key generated for your machine
openssl genrsa -out passwordPrivKey.pem 2048
openssl rsa -in passwordPrivKey.pem -out passwordPubKey.pem -outform PEM -pubout
OpenSSL could be used than to encrypt and decrypt a password. Providing a script stub which will demonstrate how to use the command.
#!/bin/bash
printf "password" > PASSWORD.plain
# To encrypt
openssl rsautl -encrypt -inkey ./passwordPubKey.pem -pubin -in PASSWORD.plain -out PASSWORD.dat
# To decrypt
DECRYPTED=$(openssl rsautl -decrypt -inkey ./passwordPrivKey.pem -in PASSWORD.dat)
echo $DECRYPTED
On the machine where the password is needed unencrypted later, only PASSWORD.dat and passwordPrivKey.pem would be stored.
Further Reading and Similar Q&A
You may also be interested in
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With