A-7 B-10 C-19 D-23 E-0 F-22 G-6 H-25 I-9 J-1 K-15 L-4 M-21 N-20 O-16 P-8 Q-17 R-5 S-24 T-3 U-11 V-12 W-14 X-2 Y-13 Z-18
Plain text = COMPUTER
KEY = SOVIET
Encryption
FORMULA (cipher + key) % 26 C O M P U T E R S O V I E T S O ----------------------------------- (%26) 17 6 7 17 11 6 24 21 ----------------------------------- Q G A Q U G S M
Decryption
FORMULA = ((cipher + 26) - key) % 26 Q G A Q U G S M ------------------------------------ 17 6 7 17 11 6 24 21 (+26) 43 32 33 43 37 32 50 47 ------------------------------------ S O V I E T S O 24 16 12 9 0 3 24 16 (-KEY) 19 16 21 34 37 29 26 31 ------------------------------------ (%26) 19 16 21 8 11 3 0 5 ------------------------------------ C O M P U T E R
Change Snippet Background Color
/*
*/
import java.util.*;
public class OTPCipher2{
// 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
private static Integer[] list = {7,10,19,23,0,22,6,25,9,1,15,4,21,20,16,8,17,5,24,3,11,12,14,2,13,18};
private static String alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
public static void main(String[] args){
String text = "REPEAT ATTACK TONIGHT";
String key = "SOVIET";
String k = "";
int len = text.length();
if(key.length()<len){
int count = 0;
for(int x=0;x<len;x++){
if(count == key.length())
count = 0;
k = k+key.charAt(count);
count++;
}
key = k;
}
String enc = OTPEncryption(text,key);
System.out.println("Plaintext : "+text);
System.out.println("Encrypted : "+enc);
System.out.println("Decrypted : "+OTPDecryption(enc,key));
}
public static String RandomAlpha(int len){
Random r = new Random();
String key = "";
for(int x=0;x<len;x++)
key = key + (char) (r.nextInt(26) + 'A');
return key;
}
public static String OTPEncryption(String text,String key){
int len = text.length();
String sb= "";
for(int x=0;x<len;x++){
char get = text.charAt(x);
char keyget = key.charAt(x);
if(Character.isUpperCase(get)){
int index = list[alpha.indexOf(get)];
int keydex = list[alpha.indexOf(keyget)];
int total = (index + keydex) % 26;
sb = sb + alpha.charAt(Arrays.asList(list).indexOf(total));
}
else{
sb = sb + get;
}
}
return sb;
}
public static String OTPDecryption(String text,String key){
int len = text.length();
String sb = "";
for(int x=0;x<len;x++){
char get = text.charAt(x);
char keyget = key.charAt(x);
if(Character.isUpperCase(get)){
int index = list[alpha.indexOf(get)];
int keydex = list[alpha.indexOf(keyget)];
int total = (index + 26) - keydex;
total = total % 26;
sb = sb + alpha.charAt(Arrays.asList(list).indexOf(total));
}
else{
sb = sb + get;
}
}
return sb;
}
}
No comments:
Post a Comment