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.
2 Answers
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
4 Comments
echo -n with printf, especially if your script needs to be portable.Try openssl. It is a command available on UNIX and it can hash your password for you.
2 Comments
./test.sh -p "myhashedpassword"
ssh, you can avoid the need by requiring users to have pubkey authentication; if it'ssudo, look at editing your/etc/sudoers, etc. As a last resort, you could arrange for the script to read a password from a file provided by each user (e.g. in$HOME/.secret/myapp), and if you're feeling nice, you could even check it's not readable by others.psortopwill do).