Copyright © infotec016 . Powered by Blogger.

Thursday, April 20, 2017

Cryptography : Vigenere Cipher


Vigenere Cipher

Sample java code for Vigenere Cipher

Encryption

//Vigenere cipher encryption
import java.util.*;
public class vigenere_encry{
public static void main(String args[]){
Scanner myscanner=new Scanner(System.in);
String alpha="abcdefghijklmnopqrstuvwxyz";
String keynew="",cipher="";
System.out.println("Enter the key");
String key=myscanner.nextLine().toLowerCase().replace(" ","");
System.out.println("Enter the plaintext");
String word=myscanner.nextLine().toLowerCase().replace(" ","");
int k=0;
while(k<word.length()/key.length()){
for(int i=0;i<key.length();i++){
keynew=keynew+key.charAt(i);
}
k++;
}

int q=0;
if(word.length()%key.length()!=0){
while(q<word.length()%key.length()){
keynew=keynew+key.charAt(q);
q++;
}
}
System.out.println("key       :"+keynew);
System.out.println("plaintext :"+word);

int numk=0,numw=0;
for(int i=0;i<word.length();i++){
char chark=keynew.charAt(i);
char charw=word.charAt(i);
for(int j=0;j<=25;j++){
if(chark==alpha.charAt(j)){
numk=j;
}
if(charw==alpha.charAt(j)){
numw=j;
}
}
cipher=cipher+alpha.charAt((numk+numw)%26);
}
System.out.println("ciphertext:"+cipher);
}
}



output of the above code


Decryption

import java.util.*;
public class vigenere_decry{
public static void main(String args[]){
Scanner myscanner=new Scanner(System.in);
String alpha="abcdefghijklmnopqrstuvwxyz";
String keynew="",plain="";
System.out.println("Enter the key");
String key=myscanner.nextLine().toLowerCase().replace(" ","");
System.out.println("Enter the ciphertext");
String word=myscanner.nextLine().toLowerCase().replace(" ","");
int k=0;
while(k<word.length()/key.length()){
for(int i=0;i<key.length();i++){
keynew=keynew+key.charAt(i);
}
k++;
}

int q=0;
if(word.length()%key.length()!=0){
while(q<word.length()%key.length()){
keynew=keynew+key.charAt(q);
q++;
}
}
System.out.println("ciphertext      :"+word);
System.out.println("key             :"+keynew);

int numk=0,numw=0;
for(int i=0;i<word.length();i++){
char chark=keynew.charAt(i);
char charw=word.charAt(i);
for(int j=0;j<=25;j++){
if(chark==alpha.charAt(j)){
numk=j;
}
if(charw==alpha.charAt(j)){
numw=j;
}
}
if(numw<numk){
plain=plain+alpha.charAt((26+numw)-numk);
}
else{
plain=plain+alpha.charAt(numw-numk);

}
}
System.out.println("original message:"+plain);
}
}

output of the above code


0 comments:

Post a Comment