Friday, May 25, 2012

File encryption with vim

You may not know it, but you can encrypt your files using vim... and it's pretty easy to do.

Turning encryption on for a file

If you're editing a file, to encrypt it, simply enter X at the : prompt.

Vim will then prompt you for a key.  A key is the password for decrypting the file in the future.  You'll have to enter it twice to ensure you typed it correctly.

Once you've entered your key, the next time you save/write, the file should be encrypted, see the status text at the bottom to be sure.

Once the file is encrypted, it will be unreadable to others.
Vim auto-detects whether files are encrypted.  If you try to open an encrypted file, vim will prompt you for the key.
Vim uses whatever you enter for the key to decrypt the file.  If you enter the correct things will look great.  If you enter an invalid key, vim will present you with garbage to edit.
The encryption will stay on for the file until you tell vim you'd like to remove it.

Be mindful of your key.  If you forget it, you will not be able to retrieve the contents of your file.

Turning off encryption for a file

Turning encryption off is equally as easy.  Simply set the key setting to nothing.  With the command:

:set key=

Be sure to write the file.  Note that it is no longer encrypted (status text)

Wait!  Before you go

As of vim 7.3, vim uses one of two encryption methods: zip and blowfish.  Zip is the same encryption that PkZip uses and is somewhat weak (can be cracked).  Conversely, blowfish is more contemporary and is much harder to crack.  Zip, unfortunately, is the default encryption method in vim.  I would strongly suggest that you use blowfish when encrypting your files.  To do this is simple enough.  Simply enter the command:

:set cm=blowfish

I put it in my .vimrc file so it's always set.

1 comment:

  1. Great article, thanks. This is a tad outdated, now, though, since blowfish has a huge security hole. The recommendation is to use blowfish2 as long as you're using vim 7.4.399 or later.