Implementation of Caesar ciphar in java - Pratik Ghelani

Pratik Ghelani

Breaking

Sunday, May 10, 2020

Implementation of Caesar ciphar in java

Input:-

import java.util.Scanner;
public class main {
public static void main(String[] args) {
int i,key = 0;
char pt[] = new char[50];
char ct[] = new char[50];
Scanner s = new Scanner(System.in);
System.out.print("Enter the Plain text:");
String str = s.next();
pt = str.toCharArray();
System.out.print("Enter the key:");
key = s.nextInt();
System.out.println("---Encryption---");
System.out.print("Ciphertext:");
for(i = 0 ; i<str.length() ; i++)
{
if(pt[i]>=65 && pt[i]<=90){
ct[i] = (char)(pt[i] + key);
if(ct[i]<65){
ct[i] = (char)(ct[i] + 26);
}
if(ct[i]>90){
ct[i] = (char)(ct[i] - 26);
}
}
else
{
ct[i] = (char)(pt[i] + key);
if(ct[i]<97){
ct[i] = (char)(ct[i] + 26);
}
if(ct[i]>122){
ct[i] = (char)(ct[i] - 26);
}
}
System.out.print(ct[i]);
}
System.out.println();
System.out.println("---Decryption---");
System.out.print("Original Plaintext:");
for(i = 0 ; i<str.length() ; i++)

{
if(ct[i]>=65 && ct[i]<=90){
pt[i] = (char)(ct[i] - key);
if(pt[i]<65){
pt[i] = (char)(pt[i] + 26);
}
if(pt[i]>90){
pt[i] = (char)(pt[i] - 26);
}
}
else
{
pt[i] = (char)(ct[i] - key);
if(pt[i]<97){
pt[i] = (char)(pt[i] + 26);
}
if(pt[i]>122){
pt[i] = (char)(pt[i] - 26);
}
}
System.out.print(pt[i]);
}
System.out.println();
}
}


Output:-



No comments:

Post a Comment