0

我在网上某处找到了这段代码以供参考,但这让我很困扰。结果是正确的,但不知何故,这个过程有问题。

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;
   }

}

输出

  • 纯文本:帮帮我
  • 关键字:QMMNQAB
  • 加密:gdko ld
  • 解密:帮帮我

所以你可以在输出中看到第二个“Q”键不应该在那里,因为它应该是一个空格。我怎样才能删除它?非常感谢您的回答谢谢:)

4

0 回答 0