【问题标题】:Java UTF-8 Encoding/decoding is only displaying the first wordJava UTF-8 编码/解码只显示第一个单词
【发布时间】:2016-02-16 21:25:01
【问题描述】:

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

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

唯一的问题是,如果消息中有来自用户的空格,它将只显示第一个空格之前的单词作为解密消息。

例如:

输入:你好,我是汤姆

输出:你好

但如果我的输入都是一个单词,它会完美解密

输入:HelloIamTom

输出: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);

【问题讨论】:

  • 代替message = scanner.next();试试...message = scanner.nextLine();

标签: java encryption encoding utf-8 aes


【解决方案1】:

Scanner:

扫描器使用分隔符模式将其输入分解为标记,默认情况下匹配空格。

Scanner#next():

从这个扫描器中查找并返回下一个完整的令牌。一个完整的标记前后是匹配分隔符模式的输入。此方法在等待输入扫描时可能会阻塞,即使之前对 hasNext() 的调用返回了 true

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

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

【讨论】:

    【解决方案2】:

    你正在做message = scanner.next();。取而代之的是,您应该使用message = scanner.nextLine(); 将整行作为输入。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-07
      • 1970-01-01
      • 2011-09-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多