Aim: Implementing Substitution Cipher
- Monoalphabetic Cipher
Theory: The mono-alphabetic substitution cipher is so called because each plain text letter is substituted by the same cipher text letter throughout the entire message, for example in the cipher table below, plaintext ‘r’ is always replaced by cipher text ‘H’.
Plain text alphabet – always in lower case
a | b | c | d | e | f | g | h | i | j | k | l | m | n | o | p | q | r | s | t | u | v | w | x | y | z |
X | D | G | S | Z | A | N | Y | O | B | T | M | J | C | E | V | F | H | K | W | P | L | Q | U | R | I |
Cipher text alphabet – always in upper case
Here is a short plain text message (top line) and the corresponding cipher text (bottom line), enciphered using the cipher table above, to show how the letters are substituted:
s | e | c | r | e | t | w | r | i | t | i | n | g | s | |
K | Z | G | H | Z | W | Q | H | O | W | O | C | N | K |
Source Code:
class MonoAlphabetic {
private final String ALPHABET = “abcdefghijklmnopqrstuvwxyz”;
private String newKey = “”;
private static int isGenerated = 0;
private void generateKey(String userKey)
{
// removing duplicate charaters from user key
userKey = userKey.toLowerCase();
for(int i=0;i<userKey.length();i++)
{
int flag = 0;
for(int j=0;j<this.newKey.length();j++)
{
if(userKey.charAt(i)==newKey.charAt(j))
{
flag = 1;
break;
}
}
if(flag==0)
this.newKey += userKey.charAt(i);
}
if(isGenerated==0){
isGenerated = 1;
this.generateKey(this.newKey+””+this.ALPHABET);
}
}
public String encrypt(String plainText, String userKey)
{
this.generateKey(userKey);
String cipherText = “”;
String tmpStr = plainText;
for(int i=0;i<plainText.length();i++)
{
char replaceVal = this.newKey.charAt(this.ALPHABET.indexOf(plainText.charAt(i)));
tmpStr = tmpStr.replace(tmpStr.charAt(i),replaceVal);
}
cipherText = tmpStr;
return cipherText;
}
public String decrypt(String cipherText, String userKey)
{
this.generateKey(userKey);
String plainText = “”;
String tmpStr = cipherText;
for(int i=0;i<cipherText.length();i++)
{
char replaceVal = this.ALPHABET.charAt(this.newKey.indexOf(cipherText.charAt(i)));
tmpStr = tmpStr.replace(tmpStr.charAt(i),replaceVal);
}
plainText = tmpStr;
return plainText;
}
}
class MonoAlphabeticDemo {
public static void main(String args[])
{
MonoAlphabetic ma = new MonoAlphabetic();
String en = ma.encrypt(“hiiiii”,”studentitzone”);
String de = ma.decrypt(en,”studentitzone”);
System.out.println(en + ” – ” + de);
}
}
Output:
New innovative Ideas are always welcome. feel free to post below: