【问题标题】:How to convert String to byte[] in java encryption decryption?java加密解密中如何将String转换为byte[]?
【发布时间】:2017-09-25 15:10:46
【问题描述】:

收到string 无法转换为byte[] 的错误:

String decrypted = new String(cipher.doFinal(msgin));

这是正确的加密方法,因为我收到的是加密形式的消息。

    try{
    String msgout = "";
    msgout = msg_text.getText().trim();
    aesKey = new SecretKeySpec(key.getBytes(), "AES");
        cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, aesKey);
        encrypted = cipher.doFinal(msgout.getBytes());
    String msgout1;
        msgout1 = String.valueOf(encrypted);
    dout.writeUTF(msgout1);
    msg_area.setText(msg_area.getText().trim()+"\nYou:\t"+msgout);
    }catch(Exception e){

    }

这是解密

的显示消息
    String msgin = "";
     try{
       ss = new ServerSocket(1201);
       s = ss.accept();
       din = new DataInputStream(s.getInputStream());
       dout = new DataOutputStream(s.getOutputStream());
       while(!msgin.equals("exit")){
           msgin = din.readUTF();
           cipher.init(Cipher.DECRYPT_MODE, aesKey);               
          String decrypted = new String(cipher.doFinal(msgin));\\here am receving error that string cannot be convert to byte[]
        msg_area.setText(msg_area.getText().trim()+"\nClient:\t"+decrypted);

       }
    }catch(Exception e){

    }

有什么解决办法吗?

【问题讨论】:

标签: java arrays string type-conversion byte


【解决方案1】:

对于字符串到字节[],您可以使用此代码。

    byte[] msginbyte = msgin.getBytes();
    System.out.println(Arrays.toString(valuesDefault));

使用 Arrays.toString 显示我们的字节数组。

    byte[] valuesAscii = letters.getBytes("US-ASCII");
    byte[] valuesAscii = letters.getBytes("UTF-8");

直接指定US-ASCII、UTF-8、UTF-16字符集

【讨论】:

    【解决方案2】:

    在调用 cipher.doFinal(msgin) 之前,使用 String.getBytes() 方法将 String 转换为字节数组。

    while(!msgin.equals("exit")){
        msgin = din.readUTF();
        cipher.init(Cipher.DECRYPT_MODE, aesKey);               
        String decrypted = new String(cipher.doFinal(msgin.getBytes()));
        msg_area.setText(msg_area.getText().trim()+"\nClient:\t"+decrypted);
    }
    

    【讨论】:

      猜你喜欢
      • 2014-09-13
      • 2012-01-02
      • 2021-09-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-06
      • 1970-01-01
      相关资源
      最近更新 更多