You are on page 1of 3

import java.util.

*;

class CaeserCipher

// Encrypts text using a shift by s

public static StringBuffer encrypt(String p, int s)

StringBuffer result= new StringBuffer();

for (int i=0; i<p.length(); i++)

if (Character.isUpperCase(p.charAt(i)))

char ch = (char)(((int)p.charAt(i) + s - 65) % 26 + 65);

result.append(ch);

else

char ch = (char)(((int)p.charAt(i) + s - 97) % 26 + 97);

result.append(ch);

return result;

// Decrypts text using a shift by s

public static StringBuffer decrypt(String C, int s)

StringBuffer result= new StringBuffer();

for (int i=0; i<C.length(); i++)

if (Character.isUpperCase(C.charAt(i)))
{

char ch = (char)(((int)C.charAt(i) - s - 65+26) % 26 + 65);

result.append(ch);

else

char ch = (char)(((int)C.charAt(i) - s - 97+26) % 26 + 97);

result.append(ch);

return result;

// Driver code

public static void main(String[] args)

Scanner sc = new Scanner(System.in);

//Creates a new object of type Scanner from the standard input of the program

System.out.print("Enter Plantext: ");

String plaintext= sc.nextLine(); //Reads Plaintext

// int k = 3;

System.out.println("Encryption Process, E(p,3) = (p+3) mod 26 :");

String Ciphertext = encrypt(plaintext, 3).toString();

System.out.println("Plaintext : "+plaintext);

System.out.println("Ciphertext : " + Ciphertext);

System.out.println("Decryption Process D(C,3) = (C-3) mod 26:");

plaintext = decrypt(Ciphertext, 3).toString();

System.out.println("Ciphertext : " + Ciphertext);

System.out.println("Plaintext : "+plaintext);
}

You might also like