Misframe

Jan 17, 2020

Encrypting files with GPG

I often have to securely share sensitive files with colleagues. I do this several times a day so to save time I have a few scripts that run GPG commands to encrypt and decrypt files.

These are all shell scripts that I place in ~/bin, which is in my PATH.

generate-password

The first thing I do before encrypting a file is generate a password using generate-password. I read 12 bytes out of /dev/urandom and use the base64 representation.

#!/bin/sh

dd if=/dev/urandom bs=12 count=1 2>/dev/null | base64

encrypt-artifact

Next I encrypt the artifact using encrypt-artifact. It runs gpg2 using symmetric AES256 mode. When prompted for the password, I use the string generated by the previous command.

#!/bin/sh

echo "Encrypting $1..."

gpg2 -c --cipher-algo AES256 $1

decrypt-artifact

To decrypt, I use decrypt-artifact.

#!/bin/sh

# Decrypt `file` to `file_decrypted`, or `file.gpg` to `file`.
OUTPUT="$1_decrypted"
if [[ $1 == *.gpg ]]; then
	OUTPUT=$(dirname "$1")/$(basename "$1" ".gpg")
fi

echo "Decrypting $1 to $OUTPUT..."
gpg2 --output "$OUTPUT" --decrypt "$1"

Usage

Here’s what the output looks when I run everything:

∂ ~: generate-password 
Jp74CRyX07OERjJv

∂ ~: echo "test" >> foo.txt

∂ ~: encrypt-artifact foo.txt
Encrypting foo.txt...

∂ ~: decrypt-artifact foo.txt.gpg
Decrypting foo.txt.gpg to ./foo.txt...
gpg: AES256 encrypted data
gpg: encrypted with 1 passphrase