Minggu, 27 November 2016

Caesar Chipper






  1. package com.sanfoundry.setandstring;
  2.  
  3. import java.util.Scanner;
  4.  
  5. public class CaesarCipher
  6. {
  7.     public static final String ALPHABET = "abcdefghijklmnopqrstuvwxyz";
  8.  
  9.     public static String encrypt(String plainText, int shiftKey)
  10.     {
  11.         plainText = plainText.toLowerCase();
  12.         String cipherText = "";
  13.         for (int i = 0; i < plainText.length(); i++)
  14.         {
  15.             int charPosition = ALPHABET.indexOf(plainText.charAt(i));
  16.             int keyVal = (shiftKey + charPosition) % 26;
  17.             char replaceVal = ALPHABET.charAt(keyVal);
  18.             cipherText += replaceVal;
  19.         }
  20.         return cipherText;
  21.     }
  22.  
  23.     public static String decrypt(String cipherText, int shiftKey)
  24.     {
  25.         cipherText = cipherText.toLowerCase();
  26.         String plainText = "";
  27.         for (int i = 0; i < cipherText.length(); i++)
  28.         {
  29.             int charPosition = ALPHABET.indexOf(cipherText.charAt(i));
  30.             int keyVal = (charPosition - shiftKey) % 26;
  31.             if (keyVal < 0)
  32.             {
  33.                 keyVal = ALPHABET.length() + keyVal;
  34.             }
  35.             char replaceVal = ALPHABET.charAt(keyVal);
  36.             plainText += replaceVal;
  37.         }
  38.         return plainText;
  39.     }
  40.  
  41.     public static void main(String[] args)
  42.     {
  43.         Scanner sc = new Scanner(System.in);
  44.         System.out.println("Enter the String for Encryption: ");
  45.         String message = new String();
  46.         message = sc.next();
  47.         System.out.println(encrypt(message, 3));
  48.         System.out.println(decrypt(encrypt(message, 3), 3));
  49.         sc.close();
  50.     }
  51. }

Tidak ada komentar:

Posting Komentar