如何在java加密解密中将String转换为byte []?

时间:2017-04-27 17:24:12

标签: java arrays string type-conversion byte

接收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){

    }

任何解决方案?

2 个答案:

答案 0 :(得分:0)

在调用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);
}

答案 1 :(得分:0)

对于String to byte [],您可以使用此代码。

    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字符集