Security and Cryptography

The ability to share messages safely, keep secrets and identify people has always mattered to humanity. There are records showing cryptography was already used in Mesopotamia to protect information more than 3500 years ago.
In times of war, such skills prove even more important. A few centuries before Christ, the Spartans were already using transposition ciphers and Roman soldiers already had a password system. The Germans made heavy use of cryptography during the Second World War, which also drove many advances in cryptanalysis.
Security and privacy are among the subjects that interest me most, especially the parts tied to the various areas related to cryptography, such as:
- Computing: symmetric-key algorithms, public-key algorithms, hash functions, cryptanalysis techniques, deniable encryption, steganography
- Mathematics: discrete mathematics, linear algebra, group theory
- History: ancient ciphers, military use of cryptography in wars
- Sociology: social, political and philosophical debates that every now and then stir up a lot of controversy, laws such as the United Kingdom’s RIPA.
As is easy to see, cryptography is a very broad field, which means I cannot go into much detail here. Details about how the algorithms work, benchmarks and other deeper analyses can be found in books and on other sites. The aim of this post is only to talk about a few methods for encrypting messages and files using programs and algorithms that I use and recommend.
File encryption
Vim
This is not secure encryption! (see: https://dgl.cx/2014/10/vim-blowfish)
Encrypting files
You can encrypt files (text, images, and so on) straight from Vim in the following ways:
ROT13
A little-known Vim secret is the
g?[movement]command, which applies ROT13 to the stretch between the start and the end of the movement.ROT13 is a Caesar cipher with a shift of 13, which makes the encoding process identical to the decoding one.
This kind of encryption is far too weak to protect a document, but it has a few fun uses.
Example: say you applied ROT13 only to the second line of a text, which holds the answer to the riddle (in Portuguese):
P: Por que tem uma cama elástica no polo norte? E: Cnen b hefb CBYNE!To read the answer, just apply ROT13 again (
2Gg?$or:2 norm! g?$):P: Por que tem uma cama elástica no polo norte? R: Para o urso POLAR!If you want to encrypt a whole file, or you found some obfuscated message on the internet, tr is probably a better option than Vim, since you do not have to open the file — just redirect stdin into
tr a-zA-Z n-za-mN-ZA-M.As an example, I will let you try the following command, a tribute to Bruce Schneier, creator of Blowfish and one of today’s most important cryptographers. Taken from schneierfacts.com
julio@acer ~> echo "Vs lbh nfxrq Oehpr Fpuarvre gb qrpelcg guvf, \ ur'q pehfu lbhe fxhyy jvgu uvf ynhtu." | tr a-zA-Z n-za-mN-ZA-MUsing the -x parameter from the terminal
julio@acer ~> vim -x segredo.txtVim will ask for a password to use as the file’s encryption key.
This works both for new files and for existing ones.
You will now have to supply the password every time you edit the file.
If you type an invalid password you will see something like
q,§Â²îu]2©^D!¸¡á^?%°ç]^[.julio@acer ~> file segredo.txt segredo.txt: Vim encrypted file datajulio@acer ~> cat segredo.txt VimCrypt~01!xOî4QLÉ ©è¢i¶@h@$[¾M%:XThis has the same effect as the previous option: Vim will ask you to type a password twice and will encrypt the file using the key you typed.
Changing the password
To change the password, just use the +X parameter in the terminal, type the old password and then the new one both times Vim asks.
julio@acer ~> vim +X segredo.txt
Removing the password
To remove the password, just open the file with vim and clear the key option.
:set key=
Changing the encryption algorithm
Vim has two symmetric-key algorithms:
pkzip
Do not use it — a weak algorithm and easy to crack.
:setlocal cryptmethod=zipA strong algorithm. Recommended.
:setlocal cm=blowfish
Note that cm is just an abbreviation for cryptmethod.
Gnu Privacy Guard (GPG)
One disadvantage of Vim is that it only lets you use two algorithms (Pkzip and Blowfish), which are relatively weak in some situations, and both are symmetric-key only — that is, the sender (Alice) has to share the key with the recipient (Bob) beforehand.
If Alice has no secure means of communication with Bob, how does she pass on the encrypted file’s password safely? That is what asymmetric algorithms are for. Alice can simply send the password encrypted with Bob’s public key.
GPG is ideal for cases like this, since it has 3 asymmetric algorithms and several other symmetric ones, including Blowfish and others that are stronger still. Besides encryption algorithms, GPG also has some for hashing and compression.
A list of the available algorithms can be had with the following command:
julio@acer ~> gpg --version
Supported algorithms:
Pubkey: RSA, ELG, DSA
Cipher: 3DES, CAST5, BLOWFISH, AES, AES192, AES256, TWOFISH, CAMELLIA128,
CAMELLIA192, CAMELLIA256
Hash: <del>MD5</del>, SHA1, RIPEMD160, SHA256, SHA384, SHA512, SHA224
Compression: Uncompressed, ZIP, ZLIB, BZIP2
Asymmetric cryptography
Generate your private and public key pair
A key pair is needed for encryption, decryption, signing and verification.
People will use your public key to encrypt messages meant for you, and you will use the matching private key to decrypt that message. So the public key can be handed out publicly, but the private key has to be kept secret somewhere safe.
Generate your private key
julio@acer ~> gpg --gen-keyRSA 2048 should be enough (you can go up to 4096), as long as you use a secure passphrase and not passwords open to dictionary attacks or simple brute-forcing.
In other words: no short passwords, no numeric passwords, no your chihuahua’s name and no common words.
The passphrase
_ThisIs1VeryNiceSite!_is far better than_banana1_, and as strong as the password_$%Sh4x0rq56lohap[3é-!_, but much easier to remember.The obligatory comic for this kind of post: https://xkcd.com/936/
Generate an ASCII version of your public key
julio@acer ~> gpg --armor --output juliopub.asc --export julio@juliobs.com--armormakes sure the output will be ASCII (Base64)
Sharing public keys
After generating an ASCII file with your public key, you can share it with other people. They will
have to import your public key using gpg --import, and you will have to do the same to send a
reply:
julio@acer ~> gpg --import < alice.asc
One way to check the authenticity of Alice’s public key is to compare the fingerprint she gave you
with the output of gpg --fingerprint.
Importing a private key
Importing private keys can be useful in 3 cases:
- You use more than one computer and want to be able to decrypt messages on all of them
- You reformatted the disk and want to import the private key you backed up
- You are part of a group of people who share the same key
For all of those cases, the command is:
julio@acer ~> gpg --allow-secret-key-import --import private_key.asc
Encrypt a file
julio@acer ~> gpg --encrypt --recipient julio@juliobs.com segredo.txt
julio@acer ~> gpg --encrypt --armor --recipient julio@juliobs.com segredo.txt
The first command generates a binary file called segredo.txt.gpg and the second a text file called
segredo.txt.asc. If you need to paste the encrypted message into an email, use the second one
(with --armor); otherwise the first is preferable, since it produces a smaller file:
julio@acer ~> file segredo.txt*; ls -lh segredo.txt*
segredo.txt: UTF-8 Unicode text
segredo.txt.asc: PGP message
segredo.txt.gpg: GPG encrypted data
-rw-r--r-- 1 julio users 163 Jun 10 20:58 segredo.txt
-rw-r--r-- 1 julio users 1.1K Jun 10 21:01 segredo.txt.asc
-rw-r--r-- 1 julio users 740 Jun 10 20:59 segredo.txt.gpg
Symmetric cryptography
Using the default AES128 algorithm (it used to be CAST-128)
julio@acer ~> gpg --symmetric lol.ttUsing AES-256 (Rijndael)
AES-256 is one of the strongest algorithms, and is currently used by the US government to encrypt Top Secret files
julio@acer ~> gpg --cipher-algo AES256 --symmetric segredo.txt
Hybrid cryptography
Decrypt a file
julio@acer ~> gpg --output arquivo_decriptado.txt --decrypt segredo.txt.gpg
Type your password when asked and the secret file will be decrypted and saved as
arquivo_decriptado.txt.
Graphical interface
Seahorse
Seahorse is a program that makes managing your keys easier. It can also be used to create PGP and Secure Shell keys and to store passwords.
It can be installed with the following command:
julio@acer ~> sudo pacman -S seahorse
Kgpg
Kgpg is a graphical interface on top of GPG.
Install the gnupg plugin for Vim
To install it, just copy the plugin into ~/.vim/plugin or, if you use Vundle to manage your
plugins, just add Bundle 'git://gitorious.org/vim-gnupg/vim-gnupg.git' to .vimrc and run
:BundleInstall!
You can now open .gpg files without having to type gpg --decrypt; Vim will ask for your
password.
My public key (generated in step 1.2)
OpenSSL
We can also use OpenSSL to encrypt files.
julio@acer ~> openssl aes-256-cbc -salt -in segredo.txt -out segredo.aes
enter aes-256-cbc encryption password:
Verifying - enter aes-256-cbc encryption password:
julio@acer ~> cat segredo.aes
Salted_Ø$5ÝGa$´³1äÄõýÓË
julio@acer ~> openssl aes-256-cbc -d -salt -in segredo.aes -out segredo.txt
enter aes-256-cbc decryption password:
julio@acer ~> cat segredo.txt
Este arquivo é secreto!
Mcrypt
Install Mcrypt
julio@acer ~> sudo pacman -S mcryptEncrypt a file
julio@acer ~> mcrypt -a rijndael-128 segredo.txt Enter the passphrase (maximum of 512 characters) Please use a combination of upper and lower case letters and numbers. Enter passphrase: Enter passphrase: File segredo.txt was encrypted.Decrypt a file
julio@acer ~> mcrypt -d segredo.txt.nc Enter passphrase: File segredo.txt.nc was decrypted.
7zip
7zip also lets you encrypt files with AES-256
julio@acer ~> 7z a -p -mem=AES256 -tzip segredo.7z segredo.txt
7-Zip [64] 9.20 Copyright (c) 1999-2010 Igor Pavlov 2010-11-18
p7zip Version 9.20 (locale=en_US.UTF-8,Utf16=on,HugeFiles=on,2 CPUs)
Scanning
Creating archive segredo.7z
Enter password (will not be echoed) :
Verify password (will not be echoed) :
Compressing segredo.txt
Everything is Ok
julio@acer ~> 7z l -slt segredo.7z | grep Method
Method = AES-256 Deflate
Note that even though the algorithms are the same, there are differences in the implementations, which means a file encrypted with OpenSSL will not be decrypted with GPG, for example.
Password cracking
There are some programs for working out a file’s password using dictionary and brute-force attacks.
I can recommend John the Ripper and Ophcrack.
I have forgotten (more than once) the password of encrypted files, but luckily I roughly knew the pattern of the passwords and was able to build dictionaries to try to crack them.
One of those cases was a macOS sparsebundle disk image.
First I had to extract the hash in a form John the Ripper could attack:
$ dmg2john segredo.sparseimage > segredo.txt
Then I had to build a dictionary. I knew that:
- If the password starts with a number, it is 5, 7, 123 or 321
- Word1, Word2 or Word3 appears in the password
- The end is always -A, -B or -C
A simple way to build a dictionary with every possible password matching those criteria is with Perl:
perl -lwe "print for glob '{5,7,123,321,}{Palavra1,Palavra2,Palavra3}-{A,B,C}'" > wordlist.txt
Then just let JTR run the dictionary attack:
john --fork=4 --wordlist=wordlist.txt segredo.txt
And check whether it managed to find the password:
$ john --show segredo.txt
segredo.sparseimage:123Palavra2-C::::segredo.sparseimage
1 password hash cracked, 0 left
VeraCrypt
(Section added on 26 January 2019)
VeraCrypt is a fork of the discontinued TrueCrypt and is my favorite tool for encrypting disks I need to reach from Linux, Windows and macOS.
It can encrypt a whole partition or create, in a single file, an encrypted container holding a file system.
You can choose between AES, Serpent, Twofish, Camellia, Kuznyechik or a combination of
those algorithms. It also offers several hash functions such as SHA-256, SHA-512, Streebog and
Whirlpool.
Another interesting VeraCrypt feature is hidden volumes — that is, volumes hidden at the end of
other volumes.
Every volume has room for two headers. If the password you enter is the first one’s, the outer
volume is decrypted; if it is the second one’s, then the hidden volume is decrypted instead.
That allows what is called plausible deniability, since it is impossible to prove a hidden volume
exists.
Creating a new volume is quite intuitive.
My recommendation is to use NTFS if the disk is going to be used on Windows, since NTFS is the
only supported file system with journaling. If journaling is not needed, I recommend exFAT.
To mount an encrypted volume on macOS:
/Applications/VeraCrypt.app/Contents/MacOS/VeraCrypt --text --keyfiles="" --pim="0" --protect-hidden="no" /dev/disk3s5 /Volumes/Dev
To unmount it:
$ /Applications/VeraCrypt.app/Contents/MacOS/VeraCrypt --dismount /dev/disk3s5
Links
- http://arstechnica.com/security/2012/08/passwords-under-assault/
- http://irtfweb.ifa.hawaii.edu/~lockhart/gpg/gpg-cs.html
- http://sleepyhead.de/howto/?href=crypt
- http://vim.wikia.com/wiki/Encryption
- http://www.activism.net/cypherpunk/manifesto.html
- http://www.dewinter.com/gnupg_howto/english/GPGMiniHowto.html
- http://www.gnupg.org/gph/en/manual.html
- http://www.lockdown.co.uk/?pg=combi
- http://www.madboa.com/geek/gpg-quickstart/
- http://www.philzimmermann.com/EN/essays/WhyIWrotePGP.html
- http://www.theregister.co.uk/2009/11/24/ripa_jfl/
- http://www.theregister.co.uk/2010/06/28/brazil_banker_crypto_lock_out/
- http://www.wired.com/gadgetlab/2012/11/ff-mat-honan-password-hacker
- http://www.wirelessbrasil.org/wirelessbr/colaboradores/leonardo_vilela/tutorial_pgp.html
- https://en.wikipedia.org/wiki/Password
- https://wiki.archlinux.org/index.php/System_Encryption_with_LUKS_for_dm-crypt
- https://wiki.archlinux.org/index.php/Truecrypt
- Defcon: http://youtu.be/0WPny7wk960

I’m a Brazilian computer engineer based in Germany, passionate about tech, science, photography, and languages.
I’ve been programming for about two decades already, exploring everything from mobile apps and web development to machine learning. These days I focus on cloud SRE and data engineering.
I volunteer in the open source and Python communities, helping organize PyCon DE and PyData Berlin, mentoring, and contributing with code and translations.
On my blog, I share Linux tips, setup guides, and personal notes I’ve written for future reference. I hope others find them helpful as well. The content is available in multiple languages.
Browse my gallery for some of my photography.
Away from the keyboard, you’ll find me at concerts, playing clarinet, cycling, scuba diving, or exploring new places, cultures, and cuisines.
Always happy to connect! 🙂