gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 06:46:07 30 4
gpt4 key购买 nike

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

}

有什么解决办法吗?

最佳答案

对于 String 到 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字符集

关于java - java加密解密中如何将String转换为byte[]?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43664282/

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