Java Caesar Cipher

This Java example uses the Caesar cipher algorithm to transform text. It shifts letters by a certain number of characters.
Caesar cipher. A cipher obscures text. In the Caesar cipher, letters are shifted by a specified number of places in the alphabet. We reverse this by shifting each letter back.
Strings are immutable. So we cannot change their letters directly—instead, we can convert them to a character array. And then, for each letter in it, we apply the shifting logic.
Caesar method. This accepts a String, and an int that indicates how many places each character is to be shifted. It handles out-of-range characters by subtracting, or adding, 26.

ToCharArray: We first convert the String to a char array. This is a mutable data structure: an element can be changed.

String: We return a String by converting the char array into one. We use the String constructor.

Java program that applies Caesar cipher public class Program { static String caesar(String value, int shift) { // Convert to char array. char[] buffer = value.toCharArray(); // Loop over characters. for (int i = 0; i < buffer.length; i++) { // Shift letter, moving back or forward 26 places if needed. char letter = buffer[i]; letter = (char) (letter + shift); if (letter > 'z') { letter = (char) (letter - 26); } else if (letter < 'a') { letter = (char) (letter + 26); } buffer[i] = letter; } // Return final string. return new String(buffer); } public static void main(String[] args) { // Test the cipher method. String a = "test"; System.out.println(a); System.out.println(); String b = caesar(a, 18); String c = caesar(b, -18); System.out.println(b); System.out.println(c); System.out.println(); String d = caesar(a, 1); String e = caesar(d, -1); System.out.println(d); System.out.println(e); System.out.println(); String f = "exxegoexsrgi"; String g = caesar(f, -4); System.out.println(f); System.out.println(g); } } Output test lwkl test uftu test exxegoexsrgi attackatonce
In testing, the caesar() method correctly converted the Strings. It converted the String "test" to "lwkl." And then it round-tripped the conversion.

So: For Strings with just ASCII letters, the method appears to be correct. Other values are not tested here.

ROT13. The Caesar cipher is nearly the same as ROT13, except with Caesar, we do not rotate just 13 characters. We must additionally know (or decipher) the "offset" or "shift" value.ROT13
Espionage is part of human civilization. Even in 40 BC, messages were being intercepted. The Caesar cipher, unlike modern systems, is easy to break—given the right knowledge.
© 2007-2019 Sam Allen. Every person is special and unique. Send bug reports to
Dot Net Perls