Does anyone have any sources or references to a Caesar Cipher prgoram with a shift of 3 letters?
Printable View
Does anyone have any sources or references to a Caesar Cipher prgoram with a shift of 3 letters?
I have part of the code for my cypher to move down 3. But the only thing i am stuck on is how would i keep the spaces in the cyper. so they that i input "Michael Hall" and the output of that is "Encrypted sentence is: Plfkdho#Kdoo" with the # for the space. How would i keep an input with a space to keep the space in the output. along with a dash(-)Code:import java.io.*;
public class CaesarCypher {
public static void main(String args[])
{
final int MOVE_DOWN = 3;
String plainText = "Mr Spiegel";
char character;
System.out.print("Encrypted sentence is: " );
for (int iteration = 0; iteration < plainText.length(); iteration++)
{
character = plainText.charAt(iteration); //get the letters
character = (char) (character + MOVE_DOWN); //perform the move down shift +3
System.out.print(character);
}
System.out.println();
}
}
The caesar cypher is nothing more than a rotational shift of character value. I would find an ASCII table and include a range of all characters that I want included in the cypher including the space character. I'd find the size of this range, divide it in half and use this number to shift each char. In other words add the value to each char, then mod the resulting value by the top char so that the cypher shift wraps around. Then the cypher itself will automatically take care of spaces, capitals, lower case, everything.
For example, I'd set the START char of my cypher as the ' ' or space char and the END char as te end curly brace or '}' (because it works well), calculate the RANGE and the MID point of the RANGE and then create two static methods, shiftChar and shiftString, in pseudocode:
Code:shiftChar is public static, takes a char parameter, c, and returns a char result
int i is (c - START) // shift chars value so that the start char is at 0
add MID to i // MID is RANGE / 2, and this shifts all our characters over -- this is the cypher
mod i by RANGE // RANGE is nothing but END - START + 1, this will ensure that any chars shifted beyond the range will wrap back into the range
add START back to i // shift char back
return i cast as a char
end method
shiftString is public static, takes a String parameter and returns a String result
create StringBuilder
for each char in the parameter String, call shiftChar and place in StringBuilder
return the toString result of the StringBuilder.
end method