Open, Edit & Save Encrypted Files with Vim and GPG

If you’ve ever want to save sensitive text on your computer - encrypting it is the only way to ensure it is secure. Using vim and gpg we can open, edit, and save only the encrypted file and leave nothing in plain text on the hard drive.

Note: In order to run gpg on OS X, you’ll need to first install MacGPG2.

To Open an Encrypted File (from shell)

gpg -d myfile.mkdn.gpg | vim - -n -i "NONE" "+set filetype=markdown"
  • -d to decrypt
  • | pipe stdout of gpg into vim
  • - to accept stdin instead of file
  • -n turns off swap file - important!
  • -i turns off .viminfo - important!
  • +set filetype set the file type (for syntax highlighting, etc) since there is no file name for vim to detect

Bonus: Add a function (and easy alias) to your ~/.bash_profile file:

vimdecrypt() { gpg -d "$1" | vim - -n -i "NONE" "+set filetype=$2"; }
alias vd="vimdecrypt"

You can now simply type (2nd argument optional):

$ vd myfile.mkdn.gpg markdown

To Encrypt and Save a File (from vim)

:w !gpg -c -o myfile.mkdn.gpg
  • :w to write buffer
  • !gpg escape to shell and run gpg, accepts vim buffer as stdin
  • -c to set symetric encryption
  • -o to set file name

Bonus: Add a command to your ~/.vimrc file:

command -nargs=1 WriteEncrypted w !gpg -c -o <q-args>

Now, from within vim you type

WriteEncrypted myfile.txt.gpg
  1. bernardb reblogged this from jasonseney and added:
    A really nice way to encrypt a simple text file on the fly.
  2. invaderxir reblogged this from jasonseney and added:
  3. jasonseney posted this