问题描述
我有一个字节数组,我正在对其进行加密,然后将其转换为字符串以便进行传输.当我收到字符串时,我必须将字符串转换回字节数组,以便对其进行解密.我已经检查过接收的字符串是否与发送的字符串匹配(包括长度),但是当我使用 str.getBytes() 之类的东西将其转换为字节数组时,它与我的原始字节数组不匹配.
I have a byte array which I'm encrypting then converting to a string so it can be transmitted. When I receive the string I then have to convert the string back into a byte array so it can be decrypted. I have checked that the received string matches the sent string (including length) but when I use something like str.getBytes() to convert it to a byte array, it does not match my original byte array.
示例输出:
SENT: WzShnf/fOV3NZO2nqnOXZbM1lNwVpcq3qxmXiiv6M5xqC1A3
SENT STR: [B@3e4a9a7d
RECEIVED STR: [B@3e4a9a7d
RECEIVED: W0JAM2U0YTlhN2Q=
任何想法如何将接收到的字符串转换为与发送的字节数组匹配的字节数组?
any ideas how i can convert the received string to a byte array which matches the sent byte array?
谢谢
推荐答案
你使用了 array.toString()
,它是这样实现的:
You used array.toString()
, which is implemented like this:
return "[B@" + Integer.toString(this.hashCode(), 16);
(其实是继承了Object的定义,@
之前的部分就是getClass().getName()
的结果.)
(In fact it inherits the definition from Object, and the part before the @
simply is the result of getClass().getName()
.)
而且这里的 hashCode 不依赖于内容.
And the hashCode here does not depend on the content.
改为使用 new String(array, encoding).
Instead, use new String(array, encoding).
当然,这仅适用于真正可表示为 Java 字符串(然后包含可读字符)的字节数组,不适用于任意数组.最好像 Bozho 推荐的那样使用 base64(但一定要在通道的两侧使用它).
Of course, this only works for byte-arrays which are really representable as Java strings (which then contain readable characters), not for arbitrary arrays. There better use base64 like Bozho recommended (but make sure to use it on both sides of the channel).
这篇关于将Java字符串转换为字节数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!