我在网络上的某个地方找到了此代码以供参考,但这困扰着我。结果是正确的,但是在某种程度上该过程有问题。
import java.io.*;
import java.util.*;
import java.util.Scanner;
public class onetime{
public static void main(String[] args){
System.out.println("Type Message: " );
Scanner sc = new Scanner(System.in);
String text = sc.nextLine();
String key = RandomAlpha(text.length());
String enc = OTPEncryption(text,key);
System.out.println("Plaintext : " +text);
System.out.println("Key: "+key);
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){
String alphaU = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
String alphaL = "abcdefghijklmnopqrstuvwxyz";
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 = alphaU.indexOf(get);
int keydex = alphaU.indexOf(Character.toUpperCase(keyget));
int total = (index + keydex) % 26;
sb = sb+ alphaU.charAt(total);
}
else if(Character.isLowerCase(get)){
int index = alphaL.indexOf(get);
int keydex = alphaU.indexOf(Character.toLowerCase(keyget));
int total = (index + keydex) % 26;
sb = sb+ alphaL.charAt(total);
}
else{
sb = sb + get;
}
}
return sb;
}
public static String OTPDecryption(String text,String key){
String alphaU = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
String alphaL = "abcdefghijklmnopqrstuvwxyz";
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 = alphaU.indexOf(get);
int keydex = alphaU.indexOf(Character.toUpperCase(keyget));
int total = (index - keydex) % 26;
total = (total<0)? total + 26 : total;
sb = sb+ alphaU.charAt(total);
}
else if(Character.isLowerCase(get)){
int index = alphaL.indexOf(get);
int keydex = alphaU.indexOf(Character.toLowerCase(keyget));
int total = (index - keydex) % 26;
total = (total<0)? total + 26 : total;
sb = sb+ alphaL.charAt(total);
}
else{
sb = sb + get;
}
}
return sb;
}
}
输出
因此您可以在输出中找到键的第二个“ Q”,因为它应该是一个空格。如何删除? 非常感谢您的回答,谢谢:)