CRYPTOGRAPHY AND NETWORK SECURITY LAB
Lab assessment-1
Name:u.phani satya sai prasanth
Reg no:22BCT0060
Slot:L33+L34
Course code:BCSE309P
Program
CAESAR CIPHER
Aim:
To implement a Caesar Cipher algorithm in Java that can
encrypt and decrypt a given text based on a user-provided
key.
Concepts Applied:
Character Manipulation:
Using ASCII values to shift characters.Modular Arithmetic: Ensures
that character shifts wrap
around within the alphabet.
Conditional Statements: Differentiates between uppercase,
lowercase, and non-alphabetic characters.
Iterative Processing: Iterates through each character of the
input text.
Encapsulation: Encryption and decryption logic are
encapsulated in methods.
Input Handling: Accepts dynamic input (text and key) from
the user.
StringBuilder Usage: Efficiently constructs the
encrypted/decrypted string.
Case Sensitivity: Maintains the case of letters during
encryption/decryption.
Error Handling: Prevents invalid input from causing runtime
errors (e.g., modulo operations).
Reusability: The encryption logic is reused for decryption.
Algorithm for Caesar Cipher
Encryption:
1. Input:
○ A text string and an integer key.
2. Iterate:
○ Loop through each character of the string.
3. Check if Letter:
○ If the character is a letter:
■ Determine if it’s lowercase or uppercase.■ Calculate the shifted
position using
(original_position + key) % 26.
■ Convert the new position back to a character.
○ If not a letter, keep the character unchanged.
4. Build Encrypted Text:
○ Append each transformed character to the result.
5. Output:
○ Return the encrypted string.
Decryption:
1. Input:
○ The encrypted text string and the same integer
key.
2. Reverse Shift:
○ Use (26 - (key % 26)) as the new key.
3. Reuse Encryption:
○ Pass the encrypted text and the new key to the
encryption function.
4. Output:
○ Return the decrypted string.
CODE:
//NAME:u.phani satya sai prasanth
//REG NO:22BCT0060
import java.util.*;
public class CaesarCipher
{
// Method to encrypt the text
public static String encrypt(String text, int key)
{
StringBuilder encrypted = new StringBuilder();
for (char c : text.toCharArray())
{
if (Character.isLetter(c))
{
char base = Character.isLowerCase(c) ? 'a' : 'A';
encrypted.append((char) ((c - base + key) % 26 + base));
}
else
{
encrypted.append(c); // Keep non-alphabet characters unchanged
}
}
return encrypted.toString();
}
// Method to decrypt the text
public static String decrypt(String text, int key)
{
return encrypt(text, 26 - (key % 26)); // Decrypt by reversing the key
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter 1 for Encryption or 2 for Decryption:");
int choice = sc.nextInt();
sc.nextLine(); // Consume the newline
if (choice == 1)
{
System.out.println("Enter the text to encrypt:");
String text = sc.nextLine();
System.out.println("Enter the key value:");
int key = sc.nextInt();
String encryptedText = encrypt(text, key);
System.out.println("Encrypted Text: " + encryptedText);
}
else if (choice == 2)
{
System.out.println("Enter the text to decrypt:");
String text = sc.nextLine();
System.out.println("Enter the key value:");
int key = sc.nextInt();
String decryptedText = decrypt(text, key);
System.out.println("Decrypted Text: " + decryptedText);
}
else
{
System.out.println("Invalid choice. Please enter 1 or 2.");
}
}
}
OUTPUT:
Program2
Program 2
Playfair Cipher
Aim:
To implement a Playfair cipher substitution technique in Java.
Concepts Applied:
1. Introduction:
○ Invented by Charles Wheatstone in 1854,
promoted by Lord Playfair.
○ Encrypts pairs of letters (digraphs) instead of
single letters for added complexity.
2. Key Square Matrix (5×5):
○ A 5×5 grid of unique alphabets acts as the
encryption key.
○ "J" is replaced with "I" to fit 25 letters.○ The key starts with unique
letters of the given
keyword, followed by remaining alphabets in
order.
3. Plaintext Preparation:
○ Divide the plaintext into pairs of two letters
(digraphs).
○ If a pair has duplicate letters, insert a filler (e.g.,
"X").
○ Add a filler (e.g., "Z") if the plaintext has an odd
number of letters.
4. Encryption Rules:
○ Same Row: Replace each letter with the one to its
right (wrap around if at the end).
○ Same Column: Replace each letter with the one
below it (wrap around if at the bottom).
○ Rectangle Rule: Replace each letter with the one
at the opposite corner of the rectangle.
5. Features:
○ Simple to use and requires no special equipment.
○ Provides reasonable security by encrypting
digraphs, making it more complex to crack than
monoalphabetic ciphers.
Algorithm for Playfair Cipher:
1. Key Input and Key Table Creation:○ Accept a keyword from the
user and create a 5×5
grid (key table) of unique alphabets.
○ Replace "J" with "I" to fit the 25-letter grid. The
table starts with the keyword followed by
remaining letters in order.
2. Plaintext Input:
○ Read the plaintext from the user. Split it into pairs
of two letters (digraphs).
○ If a pair contains the same letter, insert a filler
(e.g., "Z") between them. For odd-length plaintext,
append a filler to the last letter.
3. Column Rule:
○ If both letters of a pair are in the same column,
replace each with the letter directly below it (wrap
around to the top if necessary).
4. Row Rule:
○ If both letters are in the same row, replace each
with the letter to its immediate right (wrap around
to the leftmost if necessary).
5. Rectangle Rule:
○ If the letters form a rectangle, replace them with
the letters at the horizontal opposite corners of the
rectangle.
Code:
//name:u.phani satya sai prasanth
//reg no:22BCT0060
package CNS;
import java.util.Scanner;
public class PlayfairCipher
{
public static void main(String[] args)
{
Scanner in=new Scanner(System.in);
System.out.print("Enter keyword: ");
String key=in.nextLine();
System.out.print("Enter message to encrypt: ");
String msg=in.nextLine();
PFEncryption pfEncryption=new PFEncryption();
pfEncryption.makeArray(key);
msg=pfEncryption.manageMessage(msg);
pfEncryption.doPlayFair(msg, "Encrypt");
String en=pfEncryption.getEncrypted();
System.out.println("Encrypting. .. \n\nThe encrypted text is: " + en);
System.out.println("=============================");
pfEncryption.doPlayFair(en, "Decrypt");
System.out.print("\nDecrypting... \n\nThe encrypted text is: "
+pfEncryption.getDecrypted());
}
}
class PFEncryption
private char [][] alphabets= new char[5][5];
private char[] uniqueChar= new char[26];
private String ch="ABCDEFGHIKLMNOPQRSTUVWXYZ";
private String encrypted="";
private String decrypted="";
void makeArray(String keyword)
{
keyword=keyword.toUpperCase().replace("J","I");
boolean present, terminate=false;
int val=0;
int uniqueLen;
for (int i=0; i<keyword.length(); i++)
{
present=false;
uniqueLen=0;
if (keyword.charAt(i)!= ' ')
{
for (int k=0; k<uniqueChar.length; k++)
{
if (Character.toString(uniqueChar[k])==null)
{
break;
}
uniqueLen++;
}
for (int j=0; j<uniqueChar.length; j++)
{
if (keyword.charAt(i)==uniqueChar[j])
{
present=true;
}
}
if (!present)
{
uniqueChar[val]=keyword.charAt(i); val++;
}
}
ch=ch.replaceAll(Character.toString(keyword.charAt(i)), "");
}
for (int i=0; i<ch.length(); i++)
{
uniqueChar[val]=ch.charAt(i);
val++;
}
val=0;
for (int i=0; i<5; i++)
{
for (int j=0; j<5; j++)
{
alphabets[i][j]=uniqueChar[val];
val++;
System.out.print(alphabets[i][j] + "\t");
}
System.out.println();
}
}
String manageMessage(String msg)
{
int val=0;
int len=msg.length()-2;
String newTxt="";
String intermediate="";
while (len>=0)
{
intermediate=msg.substring(val, val+2);
if (intermediate.charAt(0)==intermediate.charAt(1))
{
newTxt=intermediate.charAt(0) + "x" + intermediate.charAt(1);
msg=msg.replaceFirst(intermediate, newTxt);
len++;
}
len-=2;
val+=2;
}
if (msg.length()%2!=0)
{
msg=msg+'x';
}
return msg.toUpperCase().replaceAll("J","I").replaceAll(" ","");
}
void doPlayFair(String msg, String tag)
{
int val=0;
while (val<msg.length())
{
searchAndEncryptOrDecrypt(msg.substring(val,val+2),tag);
val+=2;
}
}
void searchAndEncryptOrDecrypt(String doubblyCh, String tag)
{
char ch1=doubblyCh.charAt(0);
char ch2=doubblyCh.charAt(1);
int row1=0, col1=0, row2=0, col2=0;
for (int i=0; i<5; i++)
{
for (int j=0; j<5; j++)
{
if (alphabets[i][j]==ch1)
{
row1=i;
col1=j;
}
else if (alphabets[i][j]==ch2)
{
row2=i;
col2=j;
}
}
}
if (tag =="Encrypt") encrypt(row1,
col1, row2, col2); else
if(tag=="Decrypt") decrypt(row1,
col1, row2, col2);
}
void encrypt(int row1, int col1, int row2, int col2)
{
if (row1==row2)
{
col1=col1+1;
col2=col2+1;
if (col1>4)
col1=0;
if (col2>4)
col2=0;
encrypted+=(Character.toString(alphabets[row1][col1])+
Character.toString(alphabets[row1][col2]));
}
else if(col1==col2)
{
row1=row1+1;
row2=row2+1;
if (row1>4)
row1=0;
if (row2>4)
row2=0;
encrypted+=(Character.toString(alphabets[row1][col1])+
Character.toString(alphabets[row2][col1]));
}
else
{
encrypted+=(Character.toString(alphabets[row1][col2])+
Character.toString(alphabets[row2][col1]));
}
}
void decrypt(int row1, int col1, int row2, int col2)
{
if (row1==row2)
{
col1=col1-1;
col2=col2-1;
if (col1<0)
col1=4;
if (col2<0)
col2=4;
decrypted+=(Character.toString(alphabets[row1][col1])+
Character.toString(alphabets[row1][col2]));
}
else if(col1==col2)
{
row1=row1-1;
row2=row2-1;
if (row1<0)
row1=4;
if (row2<0)
row2=4;
decrypted+=(Character.toString(alphabets[row1][col1])+
Character.toString(alphabets[row2][col1]));
}
else
{
decrypted+=(Character.toString(alphabets[row1][col2])+
Character.toString(alphabets[row2][col1]));
}
}
String getEncrypted( )
{
return encrypted;
}
String getDecrypted( )
{
return decrypted;
}
}
output: