ROT13 (ROT-13) is a simple monoalphabetic substitution cipher over 26 characters of the English alphabet. ROT13 is a special case of Caesar cipher.
Description
To cipher and decipher the given text, ROT13 shuffles (rotates) the alphabet by 13 places. Which means that if we write down the alphabet in 2 rows (each containing 13 characters), than we can transform (encipher, decipher) the text by substituting the characters of the first row by characters of the second row (and vice versa).
Examples
ATTACKATDAWN ⇔ NGGNPXNGQNJA
ENEMYATTHEGATES ⇔ RARZLNGGURTNGRF
BLACKHAWKDOWN ⇔ OYNPXUNJXQBJA
ENEMYATTHEGATES ⇔ RARZLNGGURTNGRF
BLACKHAWKDOWN ⇔ OYNPXUNJXQBJA
Code
01.
/**
02.
* ROT13
03.
* @param text text containing only uppercase English characters
04.
* @return ciphertext - if the input was plaintext, plaintext - if the input was ciphertext
05.
*/
06.
public
static
String rot13(String text) {
07.
StringBuilder builder =
new
StringBuilder();
08.
for
(
int
i =
0
; i < text.length(); i++) {
09.
if
(text.charAt(i) <
'A'
|| text.charAt(i) >
'Z'
) {
10.
throw
new
IllegalArgumentException(
"Text must contain only uppercase english letters"
);
11.
}
12.
builder.append((
char
) (
'A'
+ ((text.charAt(i) -
'A'
+
13
) %
26
)));
13.
}
14.
return
builder.toString();
15.
}