Tuesday, September 18, 2012

How to ROT13 a line of text in vim

By Vasudev Ram

ROT13 (which stands for "rotate by 13 places") is a simple substitution cipher. It encodes letters of the English alphabet by replacing each letter by the one 13 letters after it, wrapping around to A and beyond for letters after M.

I came across this capability of vim while checking out ROT13 for a program I'm writing. You can ROT13 a line of text in the vim text editor with this command:
See the Wikipedia ROT13 page for more on what ROT13 is, and for another vim example.

An interesting property of ROT13 is that it is its own inverse; i.e. ROT13(ROT13(x)) == x. The XOR (exclusive OR) operator also has the same property in some cases. E.g. if you XOR (*) an ASCII character, say x, with some other constant character c, you get, say, the character y (c, x and y are meant as placeholders, not the actual letters c, x and y). Then if you XOR y with the same fixed character c, you get x again. I had used this long ago to write a simple encryption program in C that would encrypt text files using this algorithm.

UPDATE: Forgot to mention that, due to this self-inverse property of XOR, the decryption program code was exactly the same as the encryption program, except for different prompts or error messages (e.g. "enter name of file to encrypt" vs. "enter name of file to decrypt"). Of course, the encryption would be trivial to break, for anyone with some basic knowledge of cryptography. I just wrote it as an exercise for learning.

(*) Here, by XOR ASCII characters, I mean treat the characters as eight-bit bytes and do the XOR operations on them. This process is transparent in C because characters are really stored as ints anyway.

- Vasudev Ram - Dancing Bison Enterprises

No comments: