Tuesday, 9 August 2016

A Java Program to perform encryption and decryption using Ceaser Cipher.

import java.util.Scanner;

public class myCaeserCipher {
public char p[] = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};

         int key = 3;

         public String doEncryption (String s){
          String s1 = new String(s);
          s1 = "";
          int t;
          for (int i=0; i<s.length();i++){
          for(int j=0; j<26;j++){
          if(s.charAt(i)==' '){
          s1 = s1+" ";
          break;
          }
          if(p[j]==s.charAt(i)){
          t=(j-key+26)%26;
          s1=s1+p[t];
          break;
          }
          }
          }
          return(s1);
         }

         public String doDecrypt(String s){
          String s1 = new String(s);
          s1="";
          int t;
          for(int i=0; i<s.length();i++){
          for(int j=0;j<26; j++)
                  {
          if(s.charAt(i)==' '){
          s1=s1+" ";
          break;
          }
          if(p[j]==s.charAt(i)){
          t=(j+key+26)%26;
          s1=s1+p[t];
          break;
          }
          }
          }
          return(s1);
          }        
     
         public static void main (String args[]){
            Scanner sc = new Scanner(System.in);
            System.out.println("Ente a string: \n");

          String msg = sc.nextLine();
          String emsg,nmsg;

          myCaeserCipher c1 = new myCaeserCipher();
          emsg = c1.doEncryption(msg);
          System.out.println("\nafter encryption: "+ emsg);

          nmsg = c1.doDecrypt(emsg);
          System.out.println("\nafter decryption : " + nmsg);

         }

}
 /* The End Of Our Program Code */
Copy the above code and paste it in your editor, 
-> save the file as myCaeserCipher.java, 
->compile it using javac myCaeserCipher.java
->then run it using java myCaeserCipher

if all done well, the following out put is expected
-------------------------------------------------------------------------------------------------------------------

No comments:

Post a Comment