# GPG and Vim

In my previous post, I mentioned that I used to use Vim to automatically encrypt and decrypt my file of user names and passwords. A reader emailed to ask for the configuration file that allowed this transparent behavior, so here it is. It’s called gpg.vim and is kept in the ~/.vim/plugin directory.

" Transparent editing of gpg encrypted files.
" By Wouter Hanegraaff <wouter@blub.net>
augroup encrypted
au!

" First make sure nothing is written to ~/.viminfo while editing
" an encrypted file.
" We don't want a swap file, as it writes unencrypted data to disk
" Switch to binary mode to read the encrypted file
" Switch to normal mode for editing

" Convert all text to encrypted text before writing
autocmd BufWritePre,FileWritePre    *.asc   '[,']!gpg --default-recipient-self -ae 2>/dev/null
" Undo the encryption so we are back in the normal text, directly
" after the file has been written.
autocmd BufWritePost,FileWritePost    *.asc   u

" First make sure nothing is written to ~/.viminfo while editing
" an encrypted file.
" We don't want a swap file, as it writes unencrypted data to disk
" Switch to binary mode to read the encrypted file
" Switch to normal mode for editing

" Convert all text to encrypted text before writing
autocmd BufWritePre,FileWritePre    *.gpg   '[,']!gpg --default-recipient-self -e 2>/dev/null
" Undo the encryption so we are back in the normal text, directly
" after the file has been written.
autocmd BufWritePost,FileWritePost    *.gpg   u

augroup END


As you can tell from the top line, this file is not original with me but was downloaded from somewhere lost in the mists of memory and modified. Googling “Wouter Hanegraaff gpg” will get you a shorter version that handles only binary encrypted files, not ASCII-armored files. I guess the lines that work with *.asc files are mine, although I can’t take much credit for them--they are nothing more than an obvious rewrite of the lines that handle *.gpg files.

If you are a Vim user, you may want to look into another GPG configuration file, written by Markus Braun. You can find it here (thanks to Karsten Hokamp for the tip).

Tags: