2013-04-26 70 views
0

如果我這樣做轉換散列字節數組轉換成String

int keyLength = 160; // because SHA1 generates 160-bit hashes 
int iterations = 20 * 1000; //standard is 2000 but let's be more secure here 

KeySpec spec = new PBEKeySpec(password.toCharArray(), generateSalt(), iterations, keyLength); 
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); 
byte[] hash = keyFactory.generateSecret(spec).getEncoded(); 

如何轉換這個散列成字符串,因此它可以被保存到數據庫?我想new String(hash, "UTF-8");但是,讓畸形的人物,如l��0\�w�c��Q�

回答

5

您需要將字節數組編碼爲Base64 string,然後在從數據庫中讀取時將其解碼回字節數組。請注意,編碼字符串將比原始字節數組大33%左右。

1

如果您在應用程序中始終將密鑰作爲byte[]使用,那麼最好將其作爲BLOB二進制對象本身保存在數據庫中。您將避免轉換錯誤。