Implement One Time Pad (OTP) Cipher.: Code
Implement One Time Pad (OTP) Cipher.: Code
Implement One Time Pad (OTP) Cipher.: Code
CODE –
import java.util.Scanner;
Page 1
if (len == 7)
{
for (j = 1; j <= len; j++)
{
bintemp[j - 1] = b1.binaryArrayAtPosition(j);
}
// XOR Operation
xorlen = b1.xorop(bintemp, randomBitPattern, len);
}
else
{
// System.out.println("\n less than 7 :"+len);
bintemp[0] = 0;
for (j = 1; j <= len; j++)
{
bintemp[j] = b1.binaryArrayAtPosition(j);
}
// XOR Operation
xorlen = b1.xorop(bintemp, randomBitPattern, len + 1);
}
int xor[] = new int[xorlen];
for (j = 0; j < xorlen; j++)
{
xor[j] = b1.xorinArrayAt(j);
cipherText = cipherText + xor[j];
}
cipherText += " ";
}
return (cipherText);
}
Page 2
public static String decryptionMessage(String s)
{
int i, j;
// char cipherChar[]=new char[(s.length()/2)];
char cipherChar[] = new char[(s.length())];
int cnt = -1;
for (i = 0; i < s.length(); i++)
{
// we receive only Ascii of it is allow 0 and 1, do not accept white
// space
// int ascii=(int)s.charAt(i);
if ((int) s.charAt(i) == 48 || (int) s.charAt(i) == 49
|| (int) s.charAt(i) == 32)
{
cnt++;
cipherChar[cnt] = s.charAt(i);
}
}
String s1 = new String(cipherChar);
String s2[] = s1.split(" ");
int data[] = new int[s2.length];
for (i = 0; i < s2.length; i++)
{
data[i] = Integer.parseInt(s2[i]);
}
char randomBitPattern[] = new char[7];
for (i = 0; i < 7; i++)
{
randomBitPattern[i] = (i % 2 == 0) ? '1' : '0';
Page 3
}
BasicOperation b1 = new BasicOperation();
String plain = new String("");
// do the XOR Operation
for (i = 0; i < s2.length; i++)
{
int xorlen = b1.xorop(s2[i], randomBitPattern);
int xor[] = new int[xorlen];
for (j = 0; j < xorlen; j++)
{
xor[j] = b1.xorinArrayAt(j);
plain += xor[j];
}
plain += " ";
}
String p[] = plain.split(" ");
BasicOperation ob = new BasicOperation();
int decryptedChar[] = new int[p.length];
char plainTextChar[] = new char[p.length];
for (i = 0; i < p.length; i++)
{
decryptedChar[i] = ob.binaryToDecimal(Integer.parseInt(p[i]));
plainTextChar[i] = (char) decryptedChar[i];
}
return (new String(plainTextChar));
}
Page 4
System.out.println("Enter the message: ");
String message = sc.next();
System.out.println("'" + message + "' in encrypted message : "
+ encryptionMessage(message));
System.out.println();
System.out.println("' in decrypted message : "
+ decryptionMessage(encryptionMessage(message)));
sc.close();
}
}
class BasicOperation
{
int bin[] = new int[100];
int xor[] = new int[100];
int temp1[] = new int[100];
int temp2[] = new int[100];
int len;
int xorlen;
Page 5
}
// Convert inputed number into decimal
no = myNum;
for (i = 0; i < n; i++)
{
int temp = no % 10;
dec = dec + temp * ((int) Math.pow(2, i));
no = no / 10;
}
return dec;
}
Page 6
}
return len;
}
Page 7
int i = -1;
for (i = 0; i < s.length(); i++)
{
xor[i] = (s.charAt(i) == c[i]) ? 0 : 1;
}
xorlen = i;
return xorlen;
}
Page 8