2014-05-04 66 views
-1

我使用下面的代碼,以生成用於提供密碼的哈希:PBEKeySpec不產生期望的輸出的密鑰長度

public static SecretKey generateKey(String passphraseOrPin) throws NoSuchAlgorithmException, InvalidKeySpecException { 
    final int iterations = 10000; 

    // Generate a 256-bit key 
    final int outputKeyLength = 256; 

    char[] chars = new char[passphraseOrPin.length()]; 
    passphraseOrPin.getChars(0, passphraseOrPin.length(), chars, 0); 
    byte[] salt = "thisSaltIsInClient".getBytes(); 

    SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); 
    KeySpec keySpec = new PBEKeySpec(chars, salt, iterations, outputKeyLength); 
    return secretKeyFactory.generateSecret(keySpec); 
} 

因此,當我得到從所生成的密碼字節,並將其轉換爲一字符串:

String passwordEncrypted = Base64.encodeToString(bytesPass, Base64.DEFAULT); 

的輸出是這樣的:

yo2NDJ96VYadiP2jpzL3p + LW0b4qkdWS ++ WqAm0W9d8 =

不應該更長嗎?

回答

1

不,它正是你在outputKeyLength指定的長度:

$ echo 'yo2NDJ96VYadiP2jpzL3p+LW0b4qkdWS++WqAm0W9d8=' | base64 --decode | hexdump -C 
00000000 ca 8d 8d 0c 9f 7a 55 86 9d 88 fd a3 a7 32 f7 a7 |.....zU......2..| 
00000010 e2 d6 d1 be 2a 91 d5 92 fb e5 aa 02 6d 16 f5 df |....*.......m...| 
00000020 

$ echo 'yo2NDJ96VYadiP2jpzL3p+LW0b4qkdWS++WqAm0W9d8=' | base64 --decode | wc 
0  2  32 

(注:256位= 32字節)

+0

我想我沒有睡不夠好今天。我的大腦決定忽略這些字節!=位 – Reinherd