SUBSTITUTION & TRANSPOSITION TECHNIQUES
CAESAR CIPHER
AIM
To write a program for encrypting a plain text and decrypting a cipher text using Caesar Cipher (shift cipher) substitution technique
ALGORITHM DESCRIPTION
· It is a type of substitution cipher in which each letter in the plaintext is replaced by a letter some fixed number of positions down the alphabet. For example, with a left shift of 3, D would be replaced by A, E would become B, and so on.
· The method is named after Julius Caesar, who used it in his private correspondence.
· The transformation can be represented by aligning two alphabets; the cipher alphabet is the plain alphabet rotated left or right by some number of positions.
· The encryption can also be represented using modular arithmetic by first transforming the letters into numbers, according to the scheme, A = 0, B = 1, Z = 25.
· Encryption of a letter x by a shift n can be described mathematically as,
En(x) = (x + n) mod26
· Decryption is performed similarly,
Dn (x)=(x - n) mod26
PROGRAM
import java.io.*;
importjava.util.Scanner;
public class CaeserCipher
{
public static void main(String[] args)
{
Scanner s=new Scanner(System.in);
System.out.println("Input Data to encypt:");
String str = s.nextLine();
System.out.println("Input the key");
int key =s.nextInt();
String encrypted = encrypt(str, key);
System.out.println("Encrypted Data :" + encrypted);
String decrypted = decrypt(encrypted, key);
System.out.println("Decrypted Data:" + decrypted);
}
public static String encrypt(String str, int key)
{
String encrypted = "";
for(int i = 0; i <str.length(); i++)
{
int c = str.charAt(i);
if (Character.isUpperCase(c))
{
c = c + (key % 26);
if (c > 'Z')
c = c - 26;
}
else if (Character.isLowerCase(c))
{
c = c + (key % 26);
if (c > 'z')
c = c - 26;
}
encrypted += (char) c;
}
return encrypted;
}
public static String decrypt(String str, int key)
{
String decrypted = "";
for(int i = 0; i <str.length(); i++)
{
int c = str.charAt(i);
if (Character.isUpperCase(c))
{
c = c - (key % 26);
if (c < 'A')
c = c + 26;
}
else if (Character.isLowerCase(c))
{
c = c - (key % 26);
if (c < 'a')
c = c + 26;
}
decrypted += (char) c;
}
return decrypted;
}
}
OUTPUT
Input Data to encrypt:
Hello How wre you
Input the key
3
Encrypted data: khoor krz zuh brx
Decrypted data : hello how wre you
No comments:
Post a Comment