Encrypt files with vim

vim_compWhat if you want to hide the contents of a file from the root user? Encryption is the answer. If it is a plaintext file, you do not need any additional software to encrypt it, vim has the ability to encrypt files using several algorithms. Currently vim supports 3 encryption methods:

zip: weak [default method for backward compatibility]
blowfish: better
blowfish2: best [supported from v7.4.399]

To use an encryption method other than zip (which is the default) set it explicitly in vim command mode:

:setlocal cm=blowfish

You can encrypt a file in 2 ways:

  • Open the file in vim and before quitting press :X in command mode. Note that after setting the password (or key) you must apply it using :w before you quit.
  • Add password to the file using
    $ vim +X myfile

Encryption is a one time operation. You can update the file as many times as you want without changing the password. To reset a password, use any of the two methods above and just press Enter when prompted for new password. You can also empty the key from vim command mode:

:set key=

vim will ask for the password every time you open the encrypted file. You will not be able to view the original contents of the file using any other external editor either. If you enter the wrong password while opening the file in vim, you will see gibberish content. In the latest versions of vim (mine is 7.4.52) saving the file in this state does not corrupt the original content. While editing, the text in the swap file, undo file, and backup files are also encrypted; however, the text in memory is not encrypted.

5 thoughts on “Encrypt files with vim”

Leave a Reply

Your email address will not be published. Required fields are marked *