DEV Community

Eric F 🇺🇦
Eric F 🇺🇦

Posted on

Encrypting files with #Vim

One of the easiest way to encrypt a file, is to use Vim. Here are two ways on how to set it up, and use it.


Setup

First, it could be good to check if your version actually is built with crypt support:

$ vim --version | grep +crypt
+cryptv            +lispindent        +quickfix          +wildmenu
Enter fullscreen mode Exit fullscreen mode

And then you can check if there's a default value set with:

:set cm?
Enter fullscreen mode Exit fullscreen mode

 

There are 3 cryptmethods:

  • VimCrypt~01: zip,
  • VimCrypt~02: blowfish,
  • VimCrypt~03: blowfish2.

You should use blowfish2, which is the strongest one.

So, to setup Vim for encryption, all you need is to set the cryptmethod (cm). In your .vimrc, you add:

" cryptmethod
set cm=blowfish2
Enter fullscreen mode Exit fullscreen mode

To use it… Just pass the -x option when creating the file. You'll be asked to enter a password, twice - and then you're in.

$ vim -x <file>
Enter fullscreen mode Exit fullscreen mode

Using a separate file

To take it another step, you can use a separate file to work with. In that way you can keep your normal settings in .vimrc - which may include all kinds of viminfo, swap files, backups, etc.

That's maybe not what you want when working with encrypted files. So, to keep the tracks down - create a new file: ~/.vim/vimencrypt, and then add this to the file:

"
" ~/.vim/vimencrypt
"
"
" Usage:
"   $ vim -u ~/.vim/vimencrypt -x <file>
"
" Or add an alias:
"   alias vimx='vim -u ~/.vim/vimencrypt -x '
"
"   $ vimx <file>
"

source ~/.vim/vimrc

set cm=blowfish2

set viminfo=
set nobackup
set noswapfile
set nowritebackup
Enter fullscreen mode Exit fullscreen mode

You may need to adjust the path to where your .vimrc file is.

 

In that way you encrypt your files without using: viminfo, no backup file, no swap, etc. And it sources your standard .vimrc, so you will have your normal environment.


Usage:

$ vim -u ~/.vim/vimencrypt -x <file>
Enter fullscreen mode Exit fullscreen mode

 

If you don't like the xtra typing… Add an alias:

alias vimx='vim -u ~/.vim/vimencrypt -x '

# and use it with:
$ vimx <file>

# Example
$ vimx testfile.txt

#  Result
$ cat testfile.txt
VimCrypt~03!���4����k
����u"E>*�1�~vh���ΊIA(7��@Y�Qj�9l��O
Enter fullscreen mode Exit fullscreen mode

 

To read more about it, use the help:

:h cm

" or if you want it in a seaparate tab
:tab h cm
Enter fullscreen mode Exit fullscreen mode

// Happy hacking… 👍

· Eric

Top comments (0)