Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Friday, 9 May 2014

Java program for Hill Cipher

import javax.swing.JOptionPane;

/**
 *
 * @author dixit bhatta
 */

public class HillCipher {
    //the 3x3 key matrix for 3 characters at once
    public static int[][] keymat = new int[][]{
                { 1, 2, 1 },
                { 2, 3, 2 },
                { 2, 2, 1 },
            };
     public static int[][] invkeymat = new int[][]{
                { -1, 0, 1 },
                { 2, -1, 0 },
                { -2, 2, -1},
            };
    public static String key = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    public static void main(String[] args) {
        // TODO code application logic here
        String text,outtext ="";
        int ch, n;
        ch = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter 1 to Encrypt and 2 to Decrypt!"));
        text = JOptionPane.showInputDialog(null, "Enter plain/cipher text to encrypt?");
        text = text.toUpperCase();
        text = text.replaceAll("\\s",""); //removing spaces
        n = text.length() % 3;
        if(n!=0){
            for(int i = 1; i<= (3-n);i++){
                text+= 'X';
            }
        }
        System.out.println("Padded Text:" + text);
        char[] ptextchars = text.toCharArray();

Java program for Vigenere Cipher

import javax.swing.JOptionPane;

/**
 *
 * @author dixit bhatta
 */
public class Vigenere {
    public static String key = "ENIGMA"; //our key
    public static void main(String args[]){
        String text;
        int ch;
        ch = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter 1 to Encrypt and 2 to Decrypt!"));
        text = JOptionPane.showInputDialog(null, "Enter plain/cipher text to encrypt/decrypt?");
        text = text.toUpperCase();
        text = text.replaceAll("\\s",""); //removing spaces
        char[] ptextchars = text.toCharArray();
                switch(ch){
            case 1:
                    for(int i=0;i< text.length(); i++){
                        ptextchars[i] = encrypt(ptextchars[i],i);
                    }
                    break;
            case 2:
                    for(int i=0;i< text.length(); i++){
                        ptextchars[i] = decrypt(ptextchars[i],i);
                    }
                    break;
            default: System.out.println("Invalid Choice!");
        }
        System.out.println(ptextchars);
    }

    private static char encrypt(char c, int i) {
        int pos = (int)c % 65;
        pos = (((int)key.charAt(i%6))%65 + pos)%26;
        return (char)(pos+65);
    }

    private static char decrypt(char c, int i) {
        int pos = (int)c % 65;
        pos = (pos - (((int)key.charAt(i%6))%65))%26;
        if(pos+65 <65){ //adjustment for unstable indexes
            pos = pos + 26;
        }
        return (char)(pos+65);
    }

}

Java program for Playfair Cipher

import javax.swing.JOptionPane;

/**
 *
 * @author dixit bhatta
 */
public class PlayFair {
    //the key matrix
    public static char[][] keymat = new char[][]{
                { 'M', 'O', 'N', 'A', 'R' },
                { 'C', 'H', 'Y', 'B', 'D' },
                { 'E', 'F', 'G', 'I', 'K'},
                { 'L', 'P', 'Q', 'S', 'T'},
                { 'U', 'V', 'W', 'X', 'Z'}
            };
    public static String trans = "J"; //for translating J to I
    public static char filler = 'X'; //filler letter is X
    public static void main(String args[]){
        String text,outtext="";
        int ch;
        ch = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter 1 to Encrypt and 2 to Decrypt!"));
        text = JOptionPane.showInputDialog(null, "Enter plain/cipher text to encrypt/decrypt?");
        text = text.toUpperCase();
        text = text.replaceAll("\\s",""); //removing spaces
        text = text.replace(trans, "I"); //changing J with I
        text = text.replaceAll("([A-Z])\\1+","$1"+filler+"$1"); //handling repeated letters
        if(text.length() % 2 !=0)
            text+= filler;
        char[] ptextchars = text.toCharArray();
        System.out.println("Padded Text: "+text);
                switch(ch){
            case 1:
                    for(int i=0;i< text.length(); i+=2){
                        outtext += encrypt(ptextchars[i],ptextchars[i+1]);
                    }
                    break;
            case 2:
                    for(int i=0;i< text.length(); i+=2){
                        outtext += decrypt(ptextchars[i],ptextchars[i+1]);
                    }
                    break;
            default: System.out.println("Invalid Choice!");
        }
        System.out.println("Output: "+outtext);
    }

    private static String encrypt(char c1, char c2) {
        int[] posa = new int[2];
        int[] posb = new int[2];
        String frag = "";
        posa = search(c1);
        posb = search(c2);
        if(posa[0] == posb[0]){//same row
            c1 = keymat[posa[0]][(posa[1]+1)%5];
            c2 = keymat[posb[0]][(posb[1]+1)%5];
            frag = (""+c1+c2+"");
        }
        else if(posa[1] == posb[1]){ //same column
            c1 = keymat[(posa[0]+1)%5][posa[1]];
            c2 = keymat[(posb[0]+1)%5][posb[1]];
            frag = (""+c1+c2+"");
        }
        else{
            c1 = keymat[posb[0]][posa[1]];
            c2 = keymat[posa[0]][posb[1]];
            frag = (""+c1+c2+"");
        }
        return frag;
    }

    private static String decrypt(char c1, char c2) {
        int[] posa = new int[2];
        int[] posb = new int[2];
        String frag = "";
        posa = search(c1);
        posb = search(c2);
        if(posa[0] == posb[0]){//same row
            c1 = keymat[posa[0]][(posa[1]-1)%5];
            c2 = keymat[posb[0]][(posb[1]-1)%5];
            frag = (""+c1+c2+"");
        }
        else if(posa[1] == posb[1]){ //same column
            c1 = keymat[(posa[0]-1)%5][posa[1]];
            c2 = keymat[(posb[0]-1)%5][posb[1]];
            frag = (""+c1+c2+"");
        }
        else{
            c1 = keymat[posb[0]][posa[1]];
            c2 = keymat[posa[0]][posb[1]];
            frag = (""+c1+c2+"");
        }
        return frag;
    }

    private static int[] search(char c) {
        int i,j;
        int[] pos = new int[2];
        for (i = 0; i < 5; i++) {
            for (j = 0; j < 5; j++) {
                if (keymat[i][j] == c){
                    pos[0] = i;
                    pos[1] = j;
                    break;
                }
            }
        }
        return pos;
    }
   
   
}

Java program for Mono-alphabetic Substitution Cipher

import javax.swing.JOptionPane;

/**
 *
 * @author dixit bhatta
 */
public class Monoalphabetic {
    public static String key = "ISYVKJRUXEDZQMCTPLOFNBWGAH";
    public static void main(String[] args) {
        // TODO code application logic here
        String text;
        int ch;
        ch = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter 1 to Encrypt and 2 to Decrypt!"));
        text = JOptionPane.showInputDialog(null, "Enter plain/cipher text to encrypt?");
        text = text.toUpperCase();
        text = text.replaceAll("\\s",""); //removing spaces
        char[] ptextchars = text.toCharArray();
        switch(ch){
            case 1:
                    for(int i=0;i< text.length(); i++){
                        ptextchars[i] = encrypt(ptextchars[i]);
                    }
                    break;
            case 2:
                    for(int i=0;i< text.length(); i++){
                        ptextchars[i] = decrypt(ptextchars[i]);
                    }
                    break;
            default: System.out.println("Invalid Choice!");
        }
        System.out.println(ptextchars);
    }

        private static char encrypt(char a) {
            int pos = (int)a;
            pos = (pos % 91)- 65;
            a = key.charAt(pos);
            return a;
        }

        private static char decrypt(char a) {
            int ascii = 0;
            for(int i=0;i< key.length(); i++){
                if(key.charAt(i) == a)
                    ascii = i + 65;
            }
            return (char)ascii;
        }  
}

Java program for Caesar Cipher

import javax.swing.JOptionPane;

/**
 *
 * @author dixit bhatta
 */
public class Ceaser {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        String text;
        int ch, factor;
        ch = Integer.parseInt(JOptionPane.showInputDialog(null, "Enter 1 to Encrypt and 2 to Decrypt!"));
        text = JOptionPane.showInputDialog(null, "Enter plain/cipher text to encrypt?");
        factor = Integer.parseInt(JOptionPane.showInputDialog(null, "Shift characters by?"));
        text = text.toUpperCase();
        text = text.replaceAll("\\s",""); //removing spaces
        char[] ptextchars = text.toCharArray();
        switch(ch){
            case 1:
                    for(int i=0; i<text.length();i++){
                        ptextchars[i] = encrypt(text.charAt(i),i,factor);
                    }
                    break;
            case 2:
                    for(int i=0; i<text.length();i++){
                        ptextchars[i] = decrypt(text.charAt(i),i,factor);
                    }
                    break;
            default: System.out.println("Invalid Choice!");
        }
        System.out.println(ptextchars);
    }

    private static char encrypt(char a, int i, int f) {
        int ascii = (int)a;
        ascii = ((ascii + f ) % 90);
        if(ascii < 65){//adjustment for characters bigger than Z
            ascii = ascii + 65;
        }
            //moving using 3 characters
        a = (char) ascii;
        return a;
    }

    private static char decrypt(char a, int i, int f) {
        int ascii = (int)a;
        ascii = ((ascii - f ) % 90);
        if(ascii < 65){//adjustment for characters smaller than a
            ascii = ascii + 25;
        }          
        //moving using 3 characters
        a = (char) ascii;
        return a;
    }
}

Friday, 31 May 2013

Java program to simulate FIFO and LRU page replacement algorithms

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Scanner;

import javax.swing.JFileChooser;

/**
 * This class reads a user chosen file for the reference string
 * (there should be spaces between the values in the string)
 * and simulates the selected page replacement policy i.e.
 * FIFO or LRU. It displays the status of page frames at each
 * new value in the string and saves the paging report in a plain
 * text file.
 * @author Dixit Bhatta
 * **/
public class pgReplace {

public static void main(String[] args) throws IOException {
ArrayList<Integer> ref = new ArrayList<Integer>();//creating new HashSet

try {
Scanner filein = new Scanner(getInputFileNameFromUser()); //open file
while(filein.hasNext()) {
String frame = filein.next();
int frm = Integer.parseInt(frame);
ref.add(frm);// add the integers to HashSet.
}//end of while

filein.close();//close the file

} catch (FileNotFoundException e) {
System.err.println("FileNotFoundException: " + e.getMessage());
}

//display the size if it the set is not empty
if(!ref.isEmpty()){
int size = ref.size();
System.out.println("The length of the Reference String is: " + size);
}
//printing the read reference string using an iterator
Iterator<Integer> iter = ref.iterator();
while (iter.hasNext())
System.out.print(iter.next() +" ");

//converting the arraylist to an array
Integer frame[] = new Integer[ref.size()];
   frame = ref.toArray(frame);

   System.out.printf("\nSelect the Page Replacement Algorithm: ");
   System.out.printf("\n1.FIFO\n2.LRU\n? ");

   Scanner sc = new Scanner(System.in);
   while (!sc.hasNextInt()) {
       sc.next(); // discard next token, which isn't a valid int
   }
   int ch = sc.nextInt();

switch(ch){
   case 1: fifo(frame,ref.size());
    break;
   case 2: lru(frame,ref.size());
    break;
   default: System.out.printf("\nInvlaid Choice");
   }
 
}
/**Simulates LRU page replacement for given reference string
* @throws IOException **/
public static void lru(Integer[] page, int n) throws IOException {
int [] frame = new int[10];
int []used = new int[10];
int index = 0;
int i,j,k,temp;
int flag=0,pf=0;
BufferedWriter write = new BufferedWriter(new FileWriter("file.txt"));
PrintWriter out = new PrintWriter(write);
System.out.printf("\tLRU Page Replacement");
System.out.printf("\nEnter number of Frames: ");
Scanner sc = new Scanner(System.in);
   while (!sc.hasNextInt()) {
       sc.next(); // discard next token, which isn't a valid int
   }
   int nf = sc.nextInt();
for(i=0;i<nf;i++)
frame[i]= -1;

for(i=0;i<n;i++){
flag=0;
for(j=0;j<nf;j++){
if(frame[j]==page[i]){//no fault
System.out.printf("\n%d: ", page[i]);
out.printf("\n%d: ", page[i]);
flag=1;
break;
}
}
if(flag==0){//fault occurs
for(j=0;j<nf;j++)
used[j]=0;//all unused initially
//moving through pages and searching recently used pages
try{
for(j = 0,temp= i-1;j < nf-1;j++,temp--){
for(k = 0;k < nf;k++){
if(frame[k]==page[temp])
used[k]=1;
//mark the recently used pages
}
}
}
catch(ArrayIndexOutOfBoundsException e){
}
for(j=0;j<nf;j++)
if(used[j]==0)
index=j;
//replace the lru page with new page
frame[index]=page[i];
System.out.printf("\n%d: ", page[i]);
System.out.printf("--->F ");
out.printf("\n%d: ", page[i]);
out.printf("--->F ");
pf++;//no of page faults
}

for(k= nf-1;k>=0;k--)
if(frame[k] != -1){
System.out.printf(" %d",frame[k]);//print frames
out.printf(" %d",frame[k]);
}
}

System.out.printf("\nNumber of page faults is: %d ",pf);
out.printf("\nNumber of page faults is: %d ",pf);
out.close();
write.close();
}

/**Simulates FIFO page replacement for given reference string
* @throws IOException **/
public static void fifo(Integer[] pages, int pg) throws IOException {
int [] frame = new int[25];
int i,k,avail,count=0;
BufferedWriter write = new BufferedWriter(new FileWriter("file.txt"));
PrintWriter out = new PrintWriter(write);
System.out.printf("\tFIFO Page Replacement");
System.out.printf("\nEnter number of Frames: ");
Scanner sc = new Scanner(System.in);
   while (!sc.hasNextInt()) {
       sc.next(); // discard next token, which isn't a valid int
   }
   int nof = sc.nextInt();
for(i=0;i<nof;i++)
frame[i]= -1;

   int j=0;
   System.out.printf("\n");
   out.printf("\n");
for(i=0;i<pg;i++){
System.out.printf("%d\t",pages[i]);
out.printf("%d\t",pages[i]);
avail=0;
for(k=0;k<nof;k++)
if(frame[k]==pages[i])
avail=1;

  if (avail==0){
frame[j]=pages[i];
j=(j+1) % nof;
count++;

for(k=0;k<nof;k++)
if(frame[k]!=-1){
System.out.printf("%d",frame[k]);
out.printf("%d",frame[k]);
}
   
System.out.printf("-->F");
out.printf("-->F");
     }

     if(avail==1){
   for(k=0;k<nof;k++)
    if(frame[k]!=-1){
    System.out.printf("%d",frame[k]);
    out.printf("%d",frame[k]);
    }
     }
     System.out.printf("\n");
     out.printf("\n");
}
System.out.printf("\nNo of Faults: %d",count);
out.printf("\nNo of Faults: %d",count);
out.close();
write.close();
}
/**
* Lets the user select an input file using a standard file
* selection dialog box. If the user cancels the dialog
* without selecting a file, the return value is null.
*/
static File getInputFileNameFromUser() {
JFileChooser fileDialog = new JFileChooser();
fileDialog.setDialogTitle("Select File for Input");
int option = fileDialog.showOpenDialog(null);
if (option != JFileChooser.APPROVE_OPTION)
return null;
else
return fileDialog.getSelectedFile();
}//end of choosing file

}

©Dixit Bhatta 2013

Thursday, 30 May 2013

Java program to reverse the content of a text file

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.Scanner;

import javax.swing.JFileChooser;

/**
 * This class reads a user chosen file, reads its words
 * reverses the order in which the words are stored in
 * the file i.e. the last word becomes first and the first
 * word becomes last.
 * @author Dixit Bhatta
 * **/
public class revFile {

public static void main(String[] args) throws IOException{
ArrayList<String> rev = new ArrayList<String>();//creating new ArrayList
String absolutePath = null; //to store path of the file
try {
File file = getInputFileNameFromUser();
//store the path of file to modify it later
absolutePath = file.getAbsolutePath();
Scanner filein = new Scanner(file); //open file
while(filein.hasNext()) {
String frame = filein.next();
rev.add(frame);// add the strings i.e. words to the ArrayList.
}//end of while

filein.close();//close the file

} catch (FileNotFoundException e) {//handle exception in case of error
System.err.println("FileNotFoundException: " + e.getMessage());
}

//display the number of words if it the file is not empty
if(!rev.isEmpty()){
int size = rev.size();
System.out.println("The number of words in file is: " + size);
}
Collections.reverse(rev);//reverse the arraylist
//use buffered writer and print writer to write into the file
BufferedWriter write = new BufferedWriter(new FileWriter(absolutePath));
PrintWriter out = new PrintWriter(write);
//writing the strings in the file using an iterator
Iterator<String> iter = rev.iterator();
while (iter.hasNext())
out.write(iter.next() + " ");
out.close();
}

/**
* Lets the user select an input file using a standard file
* selection dialog box. If the user cancels the dialog
* without selecting a file, the return value is null.
*/
static File getInputFileNameFromUser() {
JFileChooser fileDialog = new JFileChooser();
fileDialog.setDialogTitle("Select File for Input");
int option = fileDialog.showOpenDialog(null);
if (option != JFileChooser.APPROVE_OPTION)
return null;
else
return fileDialog.getSelectedFile();
}//end of choosing file


}

©Dixit Bhatta 2013