Wednesday, 6 January 2016

simple caesar cipher code in java

simple Caesar cipher code in java(encryption,decryption)

import java.io.*;
class cipher
{
 public static void main(String a[])
 {

  String s1,s2,cipher,alpha;
  int count=0;
  alpha="abcdefghijklmnopqrstuvwxyz";
  Console c=System.console();


  System.out.println("-----cipher----");
  s1=c.readLine("Enter the plain text :");
  s2=c.readLine("Enter the key(in number) :");
  System.out.println("---decryption---");
  int key=Integer.parseInt(s2);
  cipher="";

  for(int i=0;i<s1.length();i++)
      {
   for(int j=0;j<26;j++)
   {
     if(s1.charAt(i)==alpha.charAt(j))
      {
       cipher=""+alpha.charAt(j+key);
    System.out.print(cipher);
    }
   }

   }
   System.out.println("");
System.out.println("");
System.out.print(cipher);
System.out.println("");
System.out.println("");

   System.out.println("---decryption---");
 
   for(int i=0;i<cipher.length();i++)
      {
    for(int j=0;j<26;j++)
   {
     if(cipher.charAt(i)==alpha.charAt(j))
      {
       cipher=""+alpha.charAt(j-key);
    System.out.print(cipher);
    }
   }
   }
}
}

2 comments:

  1. the code has bugs and does not appear to have been tested.

    ReplyDelete
    Replies
    1. encryption error is removed. decryption still need to be fixed.

      Delete