This Vernam cipher code written in Java takes a PlainText file and Key file as input and generates the CipherText file. To enjoy the in-depth taste of Vernam Cipher, encrypt a file and sent it your friend. Let your friend try to decrypt it. And if he says you, "The file is corrupted or couldn't view the file", send him the Key file and ask him to use the vernam cipher to decode and find what's in.
/**
*
* @Ananthi Ramaswamy
*/
import java.io.FileReader;
import java.io.FileWriter;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.Scanner;
import java.util.StringTokenizer;
public class XorCipher {
public static void main(String[] args)throws IOException {
FileReader plainText = null;
FileReader key=null;
FileWriter cipherText = null;
String fileName=null;
Scanner input;
try
{
System.out.println("Enter the Plain Text File Name with Location"+(char)52);
input=new Scanner(System.in);
String filePath=input.nextLine();
plainText = new FileReader(filePath);
System.out.println("Enter the Key File Name with Location");
input=new Scanner(System.in);
key = new FileReader(input.nextLine());
StringTokenizer tokens=new StringTokenizer(filePath,"\\");
while (tokens.hasMoreElements()) {
fileName=null;
fileName=(String) tokens.nextElement();
}
cipherText = new FileWriter("D:\\Crypto\\"+"Encrypted1_"+fileName);
int character,keey,cipherChar;
BufferedReader b=new BufferedReader(key);
b.mark(20);
while ((character = plainText.read()) != -1) {
if((keey=b.read())!=-1){
cipherChar=(character^keey)%128;
System.out.println((char)character +" ^ "+(char)keey +" = " +(char)cipherChar);
cipherText.write((char)cipherChar);}
else {
b.reset();
keey=b.read();
cipherChar=character^keey;
System.out.println((char)character +" ^ "+(char)keey +" = " +(char)cipherChar);
cipherText.write((char)cipherChar);
}
}
}
catch (IOException e)
{
System.out.println("Error message: " + e.getMessage());
}
finally
{
if (plainText != null)
plainText.close();
if (cipherText != null)
cipherText.close();
if(key != null)
key.close();
}
}
}
No comments:
Post a Comment