Skip to content

Instantly share code, notes, and snippets.

@cmbaughman
Created July 21, 2022 14:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cmbaughman/151e3b5fe59061c5188487a6f0f4b538 to your computer and use it in GitHub Desktop.
Save cmbaughman/151e3b5fe59061c5188487a6f0f4b538 to your computer and use it in GitHub Desktop.
Encrypt and Store Passwords for Shell Scripts

Encrypt and Store Passwords for Shell Scripts

Here's a safe and secure method of storing passwords, encrypted, for use in shell scripts. This is in bash, but can easily be ported to other shells as the bulk of the work is handled by the openssl and sshpass apps.

  1. Install openssl and sshpass:
sudo apt update && sudo apt install openssl sshpass -y
  1. Encrypt password:
echo 'password!here!' | openssl enc -aes-256-cbc -md sha512 -a -pbkdf2 -iter 100000 -salt -pass pass:'pick.your.password'

NOTE: The --pass pass:'pick.your.password' is the password we will use to decrypt.

The result will be something like U2FsdGVkX19H1ZUfQvWYl4x4kPNPp8u0WPgNwZKYIS0=. This is the AES-256 encrypted password.

  1. Decrypt password:
echo U2FsdGVkX19H1ZUfQvWYl4x4kPNPp8u0WPgNwZKYIS0= | openssl enc -aes-256-cbc -md sha512 -a -d -pbkdf2 -iter 100000 -salt -pass pass:'pick.your.password'
  1. Store encrypted password in a dotfile:
echo 'password!here!' | openssl enc -aes-256-cbc -md sha512 -a -pbkdf2 -iter 100000 -salt -pass pass:'pick.your.password' > .credentials
  1. Decrypt stored password:
cat .credentials | openssl enc -aes-256-cbc -md sha512 -a -d -pbkdf2 -iter 100000 -salt -pass pass:'pick.your.password'
  1. Control permissions so no one else can view or edit the contents of .credentials:
chmod 600 .credentials

NOTE: This will make it so the current user is the only one who can view the hash inside the .credentials file.

  1. Using this method from a script:
#!/bin/bash

REMOTE_USER=youruser
REMOTE_PASSWD=$(cat .credentials | openssl enc -aes-256-cbc -md sha512 -a -d -pbkdf2 -iter 100000 -salt -pass pass:'pick.your.password')
REMOTE_LINUX=yourdomain.com

# connect to the remote computer and put a timestamp in a file called sshscript.log
sshpass -p $REMOTE_PASSWD ssh -T $REMOTE_USER@$REMOTE_LINUX << _remote_commands
echo $USER "-" $(date) >> /home/$REMOTE_USER/script.log
_remote_commands
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment