Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 3

KRITHIK CS 710720205023

EX.NO: 1A
Perform encryption, decryption using the following
DATE: substitution techniques : CAESAR CIPHER
AIM:

ALGORITHM:
1. Create a class named `CaesarCipher`.
2. Create a static method named `encode` that takes two parameters:
 `enc` (String): The plaintext message to be encoded.

 `offset` (int): The number of positions each letter should be shifted.

3. Inside the `encode` method:


 Create a `StringBuilder` named `encoded` to store the encoded message.

 Iterate over each character `i` in `enc`.

 If `i` is a letter, apply the Caesar cipher shift based on its case and append to `encoded`.

 If `i` is not a letter, append it unchanged to `encoded`.

 Return the `encoded` StringBuilder as a String.

4. Create a static method named `decode` that takes two parameters:


 `enc` (String): The ciphertext message to be decoded.

 `offset` (int): The number of positions each letter should be shifted back to decrypt the

message.
5. Inside the `decode` method:
 Call the `encode` method with the `enc` and the reverse of `offset` (i.e., 26 - offset) and

return the result.


6. In the `main` method:
 Create a string variable `msg` with the plaintext message.

 Print the input message `msg`.

 Encode the message using the `encode` method with an offset of 3 and print the

encrypted message.
 Decode the encrypted message using the `decode` method with the same offset of 3 and

print the decrypted message.

PROGRAM:
public class caesar{
public static String encode(String enc, int offset){
offset = offset % 26 + 26;
StringBuilder encoded = new StringBuilder();
for (char i : enc.toCharArray()){

IT8761 pg.no: Security Laboratory


KRITHIK CS 710720205023

if (Character.isLetter(i)){
if (Character.isUpperCase(i)){
encoded.append((char) ('A' + (i - 'A' + offset) % 26));}
else{
encoded.append((char) ('a' + (i - 'a' + offset) % 26));}}
else{
encoded.append(i);}}
return encoded.toString();}
public static String decode(String enc, int offset){
return encode(enc, 26 - offset);}
public static void main(String[] args)throws java.lang.Exception{
String msg = "Autonomous Institution";
System.out.println("------------| 20IT023 |------------");
System.out.println("Input : " + msg);
System.out.printf("Encrypted Message : ");
System.out.println(caesar.encode(msg, 2));
System.out.printf("Decrypted Message : ");
System.out.println(caesar.decode(caesar.encode(msg, 2), 2));}}

OUTPUT:

RESULT

IT8761 pg.no: Security Laboratory


KRITHIK CS 710720205023

IT8761 pg.no: Security Laboratory

You might also like