问题描述
我在找一个Java char数组转换为字节数组的而不需要创建中间字符串
的,因为字符数组包含密码。我抬头一对夫妇的方法,但他们都忽视了:
I'm looking to convert a Java char array to a byte array without creating an intermediate String
, as the char array contains a password. I've looked up a couple of methods, but they all seem to fail:
char[] password = "password".toCharArray();
byte[] passwordBytes1 = new byte[password.length*2];
ByteBuffer.wrap(passwordBytes1).asCharBuffer().put(password);
byte[] passwordBytes2 = new byte[password.length*2];
for(int i=0; i<password.length; i++) {
passwordBytes2[2*i] = (byte) ((password[i]&0xFF00)>>8);
passwordBytes2[2*i+1] = (byte) (password[i]&0x00FF);
}
String passwordAsString = new String(password);
String passwordBytes1AsString = new String(passwordBytes1);
String passwordBytes2AsString = new String(passwordBytes2);
System.out.println(passwordAsString);
System.out.println(passwordBytes1AsString);
System.out.println(passwordBytes2AsString);
assertTrue(passwordAsString.equals(passwordBytes1) || passwordAsString.equals(passwordBytes2));
断言总是失败(以及非常重要,当code生产中使用,密码被拒绝),但在打印报表打印出密码三次。为什么 passwordBytes1AsString
和 passwordBytes2AsString
从 passwordAsString
不同,但出现相同?我错过了一个空结束的东西?我能做些什么来进行转换和unconversion工作?
The assertion always fails (and, critically, when the code is used in production, the password is rejected), yet the print statements print out password three times. Why are passwordBytes1AsString
and passwordBytes2AsString
different from passwordAsString
, yet appear identical? Am I missing out a null terminator or something? What can I do to make the conversion and unconversion work?
推荐答案
问题是您使用平台默认的字符串(字节[])
构造,使用编码。这几乎的从不的你应该做的事情 - 如果你在UTF-16作为传递的字符编码工作,你的测试可能都会通过。目前,我怀疑 passwordBytes1AsString
和 passwordBytes2AsString
是每行16个字符长,每隔一个字符的U + 0000。
The problem is your use of the String(byte[])
constructor, which uses the platform default encoding. That's almost never what you should be doing - if you pass in "UTF-16" as the character encoding to work, your tests will probably pass. Currently I suspect that passwordBytes1AsString
and passwordBytes2AsString
are each 16 characters long, with every other character being U+0000.
这篇关于转换字符数组转换成字节数组,然后再返回的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!