Sunday, March 16, 2014

Affine Cipher Encryption Decryption Source code in Java

Written by Pranshu Bajpai |  | LinkedIn

Encryption

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package DICAss;
import java.io.*;
/**
 *
 * @author Pranshu
 */
public class DICAss19_AffineCipherEnc {
    public static void main(String[] args) {
        String Msg;
        String CTxt = "";
        
        int a = 5;
        int b = 8;
        int m = 26;
        
        BufferedReader ObjIn = new BufferedReader(
                new InputStreamReader(System.in));
        try{
            System.out.println("Enter your Message(in Caps and without spaces):");
            Msg = ObjIn.readLine();
        
            //ENCRYPTION...
            for (int i = 0 ; i < Msg.length() ; i++){
                CTxt = CTxt + (char)(((a * Msg.charAt(i) + b) % m) + 65);                
            }
            
            System.out.println("Cipher Text :"+ CTxt);
            
            //ENTERING CIPHER TEXT INTO A FILE...
            DICAss0_FileHandling ObjFilHand = new DICAss0_FileHandling();
            ObjFilHand.FileWriteFunc("BealeCipher_CTxt.txt", CTxt);
        }
        catch(Exception err){
            System.err.print("Error: " + err);
        }
    }         
}

Decryption

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package DICAss;

/**
 *
 * @author Pranshu
 */
public class DICAss20_AffineCipherDec {
    public static void main(String[] args) {
        String Msg = "";
        String CTxt;
        
        int a = 5;
        int b = 8;
        int m = 26;
        int a_inv = 0;
        int flag = 0 ;

        //Finding a_inverse...
        for (int i = 0 ; i < 26 ; i++){
            flag = (a * i) % 26;
            if (flag == 1){
                a_inv = i;
            }
        }
        
        try{
            DICAss0_FileHandling ObjFileHand = new DICAss0_FileHandling();
            CTxt = ObjFileHand.FileReadFunc("BealeCipher_CTxt.txt");
            System.out.println("CIPHER TEXT IS :"+ CTxt);
            
        
            //DECRYPTION...
            for (int i = 0 ; i < CTxt.length() ; i++){
                Msg = Msg + (char)(((a_inv * (CTxt.charAt(i) - b)) % 26) + 65);
            }
            
            System.out.println("Original Message :"+ Msg);
        }
        catch(Exception err){
            System.err.print("Error: " + err);
        }
    }         
}

4 comments:

  1. Hello there!
    This seems to be a very useful blog, I would only like to ask if it is possible to copy some parts of the codes because I couldn't figure it out.
    It helped me a lot, thanks Pranshu :)

    ReplyDelete
  2. i m not able to copy this code due to ur restrictions...

    ReplyDelete
    Replies
    1. thanks for sharing,
      I tried to make the user to enter the value of a and b
      but it does not work! why?

      Delete