Sei sulla pagina 1di 3

Sample Java Code to Encrypt and Decrypt using Caesar Cipher

Prepared by: Dr. Natarajan Meghanathan Any questions and/or feedback, email: natarajan.meghanathan@jsums.edu
The encryption code takes a text file as input, reads the file until a line break is seen and encrypts the contents, character-by-character, using Caesar Cipher. The output could be printed on the terminal or redirected to a text file to store the ciphertext. The decryption code reads the ciphertext file and decrypts the contents, character-by-character, and prints them on to the terminal screen. The integer key to be used for encryption and decryption is the other (second) input to the encryption and decryption programs. Note that Caesar Cipher is a symmetric key algorithm. Encryption Code
import java.io.*; class encryptCaesar{ public static void main(String[] args){ try{ FileReader fr = new FileReader(args[0]); BufferedReader br = new BufferedReader(fr); String plaintext = br.readLine(); plaintext = plaintext.toUpperCase(); int shiftKey = Integer.parseInt(args[1]); shiftKey = shiftKey % 26; String cipherText = ""; for (int i=0; i<plaintext.length(); i++){ int asciiValue = (int) plaintext.charAt(i); if (asciiValue < 65 || asciiValue > 90){ cipherText += plaintext.charAt(i); continue; } int basicValue = asciiValue - 65; int newAsciiValue = 65 + ((basicValue + shiftKey) % 26) cipherText += (char) newAsciiValue; } System.out.print(cipherText); } catch(Exception e){e.printStackTrace();} } }

Decryption Code
import java.io.*; class decryptCaesar{ public static void main(String[] args){ try{ FileReader fr = new FileReader(args[0]); BufferedReader br = new BufferedReader(fr); String ciphertext = br.readLine(); ciphertext = ciphertext.toUpperCase(); int shiftKey = Integer.parseInt(args[1]); shiftKey = shiftKey % 26; String plainText = ""; for (int i=0; i<ciphertext.length(); i++){ int asciiValue = (int) ciphertext.charAt(i); if (asciiValue < 65 || asciiValue > 90){ plainText += ciphertext.charAt(i); continue; } int basicValue = asciiValue - 65; int newAsciiValue = -1000; if (basicValue - shiftKey < 0){ newAsciiValue = 90 - (shiftKey - basicValue) + 1; } else{ newAsciiValue = 65 + (basicValue - shiftKey); } plainText += (char) newAsciiValue; }

System.out.print(plainText);

} catch(Exception e){e.printStackTrace();} } }

Plaintext File

Sample Output

Potrebbero piacerti anche