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.


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.


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


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.


echo "Encrypting $1..."

gpg2 -c --cipher-algo AES256 $1


To decrypt, I use decrypt-artifact.


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

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


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

∂ ~: generate-password 

∂ ~: 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
Next read these:
Nov 23, 2023
Jan 11, 2023