PBEKeySpec不生成所需的输出密钥长度

时间:2014-05-04 09:47:03

标签: java android encryption

我正在使用以下代码,以便为提供的密码生成哈希:

 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:

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

输出类似于:

  

yo2NDJ96VYadiP2jpzL3p + LW0b4qkdWS ++ WqAm0W9d8 =

不应该更长吗?

1 个答案:

答案 0 :(得分: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

(NB:256bit = 32byte)