問題描述
我希望在不創建中間 String
的情況下將 Java char 數組轉換為字節數組,因為 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));
斷言總是失敗(而且,關鍵的是,當代碼在生產中使用時,密碼被拒絕),但打印語句打印出密碼三次.為什么 passwordBytes1AsString
和 passwordBytes2AsString
與 passwordAsString
不同,但看起來相同?我錯過了一個空終止符還是什么?我該怎么做才能使轉換和取消轉換工作?
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?
推薦答案
問題是你使用了 String(byte[])
構造函數,它使用平臺默認編碼.這幾乎是從不你應該做的——如果你傳入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.
這篇關于將 char 數組轉換為字節數組并再次返回的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!