如上所述,我在 Java 中遇到了 UTF-16LE 的问题。当我运行我的代码时,它通常会正确加密、解密和打印消息。有时它会丢失两个加密字符,有时它会打印出一个非英文字符,例如希腊语等。
这是一个班级,它确实难倒了我的教授,任何帮助将不胜感激。
/*This program was written by me for my professors class.
该程序的目的是使用 XOR 加密对消息进行加密,并以相同的方式对其进行解密,以便为这些方法生成一个密码本。*/
import java.security.*;
public class Crypto
{
public static void main(String[] args) throws Exception
{
Crypto c = new Crypto();
byte[]codebook = null;
String message = "";
System.out.println("Generating codebook");
codebook = c.makeCodebook(14);
System.out.println();
System.out.println("Now Encrypting");
System.out.println("This is the contents of the Encrypted Message: ");
message = c.crypt("1234567", codebook);
System.out.println();
System.out.println("Now Decrypting");
System.out.println("This is the contents of the Decrypted Message");
message = c.crypt(message, codebook);
System.out.println();
System.out.println("Your message is: ");
System.out.println(message);
}//publis static void main(String [] args)
//Encrypts or decrypts message against the codebook assuming the appropriate length
public String crypt (String message, byte [] codebook) throws Exception
{
//Take the message and put it into an array of bytes.
//This array of bytes is what will be XORed against the codebook
byte[] cryptedMessage = message.getBytes("UTF-16LE");
byte[] result = new byte[14];
message = "";
System.out.println(message.length());
System.out.println(cryptedMessage.length);
System.out.println(result.length);
//Let's see the contents of encryptedMessage
for(int i = 0; i< cryptedMessage.length; i++)
{
System.out.print(cryptedMessage[i]+" ");
}//for(int i = 0; i< encryptedMessage.length; i++)
System.out.println();
//XOR codebook and encryptedMessage
System.out.println("This is the message using XOR:");
for(int i = 0; i<result.length; i++)
{
//since XOR has return type of an int, we cast it to a byte
result[i] = (byte)(((byte)(codebook[i])) ^ ((byte)(cryptedMessage[i])));
System.out.print(result[i]+" ");
}//while(result[i]!=0)
//output
System.out.println();
//output
System.out.println(message.length());
System.out.println(cryptedMessage.length);
System.out.println(result.length);
return new String(result, "UTF-16LE");
}//public String crypt (String message, byte [] codebook) throws Exception
//Creates truly random numbers and makes a byte array using those truly random numbers
public byte [] makeCodebook (int length) throws Exception
{
SecureRandom SecureRandom = new SecureRandom();//instance of SecureRandom named random
byte[] codebook = null;
codebook = new byte[length];
SecureRandom.nextBytes(codebook);//generate bytes using the byte[]codebook
//output
System.out.println("This is the contents of the codebook: ");
for(int i = 0; i < codebook.length;i++)
{
System.out.print(codebook[i]+" ");
}//for(int i = 0; i < codebook[i];i++)
//output
System.out.println();
return codebook;
}//public byte [] MakeCodebook (int length) throws Exception
}//Public class Crypto