Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use encrypted and decrypted passwords in shell script

Tags:

bash

shell

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.

like image 581
codec Avatar asked Nov 19 '25 09:11

codec


1 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

  • Hiding Password in Shell scripts,
  • Password encryption and decryption
  • How does OpenSSL decrypt a password?
  • How to decrypt an AES password in Bash scripting?
  • How to get a password from a Shell script without echoing?
  • Hide/encrypt password in Bash file to stop accidentally seeing it
like image 94
U880D Avatar answered Nov 21 '25 01:11

U880D



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!