Advertisement
makasun

CaesarCipher

Jul 7th, 2015
221
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.62 KB | None | 0 0
  1. class CaesarCipher {
  2.     private final String ALPHABET = "abcdefghijklmnopqrstuvwxyz";
  3.     public static void main(String args[])
  4.     {
  5.         String plainText = "ScannerWillBeBetter";
  6.         int shiftKey=4;
  7.  
  8.         CaesarCipher cc = new CaesarCipher();
  9.  
  10.         String cipherText = cc.encrypt(plainText,shiftKey);
  11.         System.out.println("Your Plain  Text :" + plainText);
  12.         System.out.println("Your Cipher Text :" + cipherText);
  13.  
  14.         String cPlainText = cc.decrypt(cipherText,shiftKey);
  15.         System.out.println("Your Plain Text  :" + cPlainText);
  16.     }
  17.  
  18.     public String encrypt(String plainText,int shiftKey)
  19.     {
  20.         plainText = plainText.toLowerCase();
  21.         String cipherText="";
  22.         for(int i=0;i<plainText.length();i++)
  23.         {
  24.             int charPosition = ALPHABET.indexOf(plainText.charAt(i));
  25.             int keyVal = (shiftKey+charPosition)%26;
  26.             char replaceVal = this.ALPHABET.charAt(keyVal);
  27.             cipherText += replaceVal;
  28.         }
  29.         return cipherText;
  30.     }
  31.     public String decrypt(String cipherText, int shiftKey)
  32.     {
  33.         cipherText = cipherText.toLowerCase();
  34.         String plainText="";
  35.         for(int i=0;i<cipherText.length();i++)
  36.         {
  37.             int charPosition = this.ALPHABET.indexOf(cipherText.charAt(i));
  38.             int keyVal = (charPosition-shiftKey)%26;
  39.             if(keyVal<0)
  40.             {
  41.                 keyVal = this.ALPHABET.length() + keyVal;
  42.             }
  43.             char replaceVal = this.ALPHABET.charAt(keyVal);
  44.             plainText += replaceVal;
  45.         }
  46.         return plainText;
  47.     }
  48. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement