Skip to content

Instantly share code, notes, and snippets.

@analogic
Last active February 14, 2017 08:54
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 analogic/58e976481a10700e45ecf8e9388f4a7d to your computer and use it in GitHub Desktop.
Save analogic/58e976481a10700e45ecf8e9388f4a7d to your computer and use it in GitHub Desktop.

Simple asymmetric backup encryption

Requirements is OpenSSL and Bash. It generates password for AES encryption, encrypt file and then it encrypt password with your public key. Tested on Ubuntu 16.04...

Encrypting

  1. generate public key from your private key:
openssl rsa -in certificate.pem -out publickey.pem -outform PEM -pubout
  1. transfer publickey.pem, encrypt.sh and decrypt.sh into your server to backup folder

  2. create source file like backup.zip and ancrypt it by calling

./encrypt.sh publickey.pem backup.zip
  1. done!

Decrypting

  1. call this command and paste content of your private key (private key is never saved to disk!)
decrypt.sh backup.zip.aes
  1. done!
#!/bin/bash
set -e
if [ "$#" -ne 1 ]; then
echo "$0 file_to_decrypt.aes"
exit 1;
fi
if [ ! -f $1 ]; then
echo "File not found!"
exit 1;
fi
FILEPATH=$1
TARGET=$(echo $FILEPATH | cut -f 1 -d '.') # strip extension
echo "Please paste your private key (contains \"--BEGIN RSA PRIVATE KEY--\"):"
KEY=""
NEWLINE=$'\n'
while read line
do
KEY="$KEY$NEWLINE$line"
if [[ $line == *"END RSA PRIVATE KEY"* ]]; then
break
fi
done
DECRYPTEDPASS=`/usr/bin/openssl rsautl -decrypt -inkey <( printf "$KEY" ) -in "$TARGET.key.rsa"`
/usr/bin/openssl enc -d -aes-256-cbc -in $FILEPATH -out $TARGET -pass file:<( printf "$DECRYPTEDPASS" )
rm -f "$FILEPATH"
rm -f "$TARGET.key.rsa"
#!/bin/bash
if [ "$#" -ne 2 ]; then
echo "$0 publickey.pem file_to_encrypt.zip"
exit 1;
fi
if [ ! -f $1 ]; then
echo "Public key not found!"
exit 1;
fi
if [ ! -f $2 ]; then
echo "File not found!"
exit 1;
fi
PUBLICKEY=$1
FILEPATH=$2
/usr/bin/openssl rand -base64 128 -out "$FILEPATH.key"
/usr/bin/openssl enc -aes-256-cbc -salt -in "$FILEPATH" -out "$FILEPATH.aes" -pass "file:$FILEPATH.key"
/usr/bin/openssl rsautl -encrypt -inkey $PUBLICKEY -pubin -in "$FILEPATH.key" -out "$FILEPATH.key.rsa"
rm -f "$FILEPATH.key"
rm -f "$FILEPATH"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment