Encrypting Files Using SSH Keys


One of the dangers of relying on self-hosted services versus cloud services is data backup. What if your home burns down? Or, more likely for me, what if you misconfigure something and wipe your server?

I decided the best option was to keep three copies of the things that matter (pictures of the family, scanned documents, git repositories, etc…). One copy is the active one on the server, another copy goes to a small NAS in another room and the final copy is in a remote datacenter (a Linode VPS in my case).

Those copies going to Linode and my NAS, need to be encrypted!

Install Go

First, make sure you have Go installed. If you don’t, here is a guide to help with that or you can run the command below.

curl -s https://codingwithcody.com/assets/bash_helpers/install_go.sh | sudo bash

Make an SSH Key

If you don’t have a key you want to use for this, you’ll need to make one. Here is a quick guide to making a key non-interactively.

DO NOT LOSE IT! The only way to decrypt the contents is with the private key.

SSH Vault


You can skip the SSH Vault install steps with the following:

curl -s https://codingwithcody.com/assets/bash_helpers/install_ssh_vault.sh | bash

Or, if you like to take each step:

Clone SSH Vault:

git clone https://github.com/ssh-vault/ssh-vault
cd ssh-vault

Build and install:

chmod +x ssh-vault
sudo mv ssh-vault /usr/local/bin/

Verify it:

which ssh-vault # Should give you /usr/local/bin/ssh-vault
# or
ssh-vault -v # Should give you a version number

Optional cleanup:

cd ..
rm -rf ssh-vault

Make a Tarball

Now we have to find something important to you to package into a tarball for ssh-vault to encrypt.

# Everything from /my/important/directory get bundled up and compressed into /tmp/my_important_files.tar.gz
tar cvfz /tmp/my_important_files.tar.gz /my/important/directory/

Encrypt the Tarball

We have the contents in a single file, now we can encrypt everything.

# Pipe the contents to SSH Vault using your private key to encrypt and output to /tmp/my_encrypted_backup.vault 
cat /tmp/my_important_files.tar.gz | ssh-vault -k ~/.ssh/my_vault_key create /tmp/my_encrypted_backup.vault

# Cleanup the unencrypted tarball
rm /tmp/my_important_files.tar.gz

Decrypt the Vault

There are a lot of ways to ship this encrypted file to a remote server. I’ll explore a couple in future articles.

# Send the decrypted contents of ssh-vault to a new file 
ssh-vault -k ~/.ssh/my_vault_key view /tmp/my_encrypted_backup.vault > /tmp/my_important_files.tar.gz

# Cleanup the encrypted vault file 
rm /tmp/my_encrypted_backup.vault

# Untar and restore the original directory
tar xvfz /tmp/my_important_files.tar.gz