gpt4 book ai didi

Java UTF-8编码/解码仅显示第一个单词

转载 作者:行者123 更新时间:2023-12-02 03:56:02 25 4
gpt4 key购买 nike

我有一个简单的问题,希望能快速解决。

我目前有一个客户端/服务器程序,它从客户端获取输入,使用 UTF-8 将其编码为字节数组,使用 AES 加密该数组,将其发送到服务器,然后反转解密过程。

唯一的问题是,如果消息中包含用户发送的空格,则它只会将第一个空格之前的单词显示为解密的消息。

例如:

Input: Hello i am Tom

Output: Hello

But if my Input is all one word, it decrypts perfectly

Input: HelloIamTom

Output: HelloIamTom

我在任何地方都找不到这方面的信息!

如有任何帮助,我们将不胜感激,

客户端代码

 System.out.println("Please type a message to be encrypted:");
message = scanner.next();


//create iv array
byte[] iv = toByteArray("a11f001ed2dec0de6e6f6e73656e7365");

Cipher aesCipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
SecretKey key = new SecretKeySpec(decryptedKey, "AES");
IvParameterSpec ivParSpec = new IvParameterSpec(iv);
aesCipher.init(Cipher.ENCRYPT_MODE, key, ivParSpec);
byte[] encryptedMessage = aesCipher.doFinal(message.getBytes("UTF-8"));


dos.writeInt(encryptedMessage.length);
dos.write(encryptedMessage);

服务器代码

  int length = dis.readInt();//recieve length of byte array for incoming message
byte[] encryptedMessage = new byte[length];//create a byte array to the length recieved
dis.readFully(encryptedMessage);//fill the byte array with incoming data

//decrypt using AES

Cipher aesCipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");//create a cipher with correct parameters
IvParameterSpec ivParaSpec = new IvParameterSpec(iv);//create IvParameter spec using IV provided in assignment brief

aesCipher.init(Cipher.DECRYPT_MODE,key,ivParaSpec);//initialise the Cipher in DECRYPT mode
byte[] decryptedMessage = aesCipher.doFinal(encryptedMessage);//create decryptedMessage and put in byte array

String decMess = new String(decryptedMessage,"UTF-8");

System.out.println("User ID:");
System.out.println(uid);

System.out.println("Decrypted Message:");
System.out.println(decMess);

最佳答案

参见Scanner :

A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.

Scanner#next() :

Finds and returns the next complete token from this scanner. A complete token is preceded and followed by input that matches the delimiter pattern. This method may block while waiting for input to scan, even if a previous invocation of hasNext() returned true.

如果你想扫描孔线,你修改的客户端代码是:

System.out.println("Please type a message to be encrypted:");
message = scanner.nextLine();

关于Java UTF-8编码/解码仅显示第一个单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35443291/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com