ROT13 Cipher Encoder and Decoder

const text = "Hello World";
const ciphered = text.replace(/[a-zA-Z]/g, (c) => {
  const last = c <= "Z" ? 90 : 122;
  c = c.charCodeAt(0) + 13;
  return String.fromCharCode(last >= c ? c : c - 26);
});

console.log(`ROT13 cipher of ${text}: ${ciphered}`);

The ROT13 cipher

The ROT13 cipher is a Caesar-based cipher that works using the Latin alphabet. Because the Latin alphabet has 26 characters, using a Caesar cipher with a shift of 13 results in a cipher that is its own inverse; that is, its encoding and decoding processes are exactly the same.

While the ROT13 cipher has effectively no cryptographic security, it remains a useful way to obscure information from a casual glance.

Example

Take the following sentence:

The quick brown fox jumps over the lazy dog.

Applying the ROT13 cipher results in the following ciphertext:

Gur dhvpy oebja sbl whzcf bire gur xnmk qbt.

Now, by applying the ROT13 cipher again, the original text should appear, illustrating the invertability of the ROT13 cipher.

The quick brown fox jumps over the lazy dog.

Variants

The ROT13 cipher also has a few variants which may be more useful depending on the situation.

  • The ROT5 variant operates only on the 10 decimal numbers, 0-9. It is a useful way to obscure numbers, because it is not immediately noticable that the number is invalid, unlike Latin text.
  • The ROT18 variant is a combination of ROT5 and ROT13. It will use ROT13 on Latin characters and ROT5 on decimal values.
  • The ROT47 variant operates on all printable ASCII characters, excluding spaces. That is, from the ! character to the ~ character, resulting in an alphabet 94 characters long. This longer alphabet results in a more thorough obfuscation of the source text, while making it more noticable that the text has been tampered with.