Asymmetric encryption is useful if you want to encrypt data on a remote server via a script. If you use a bash script for the symmetric encryption job, you have to store the password inside this script. So, if the remote server is compromised, you will lose both the encrypted data and the key to decrypt it. Asymmetric encryption allows you not to store the decryption key on the remote machine. So, the data will be safe even if the server is hacked.
Asymmetric encryption is slow and cannot be applied to large files. The solution is to use hybrid symmetric-asymmetric encryption for the big-data situation. It works as follows: the big file is encrypted with a symmetric algorithm with an on-the-fly generated key. The key is stored in the file and encrypted with an asymmetric algorithm.
Bash scripts to encrypt and decrypt files are provided below. To simulate the situation with local and remote machines, create local and remote folders side by side. Change directory to the local folder, create a public and private key pair, and copy the public key (the key names are keyfile.key for the private key and keyfile.pub for the public key) to the remote folder:
1cd local
2openssl genrsa -out keyfile.key 4096
3openssl rsa -in keyfile.key -pubout -out keyfile.pub
4cp keyfile.pub ../remote/
Now change directory to the remote folder. Create the bash script encrypt.sh:
1#!/bin/bash
2
3file=$1
4passfile=${file}_pwd
5pubkey=keyfile.pub
6
7openssl rand 256 > ${passfile}
8
9tar cz $file | openssl enc -aes-256-cbc -salt -out ${file}.enc -pass file:./${passfile}
10openssl rsautl -encrypt -pubin -inkey ${pubkey} -in ${passfile} -out ${passfile}.enc
11
12rm ${file} ${passfile}
13cp ${file}.enc ${passfile}.enc ../local
Make it executable:
1chmod +x ./encrypt.sh
Now you can create testfile with the text “secret data” and encrypt it with the encrypt.sh script. The resulting encrypted files will be copied to the ../local folder.
1echo "secret data" > testfile
2./encrypt.sh testfile
Now change directory to the local folder. Create the bash script decrypt.sh:
1#!/bin/bash
2
3file=$1
4passfile=${file%.enc}_pwd.enc
5privatekey=keyfile.key
6
7openssl rsautl -decrypt -inkey ${privatekey} -in ${passfile} -out ${passfile%.enc}
8openssl enc -d -aes-256-cbc -in ${file} -pass file:./${passfile%.enc} | tar xz
9
10rm ${file} ${passfile} ${passfile%.enc}
Make it executable:
1chmod +x ./decrypt.sh
Now decrypt testfile:
1./decrypt.sh testfile.enc
The decrypted testfile will be placed in the local directory.