Java PBEKeySpec未生成所需的输出密钥长度
我使用以下代码为提供的密码生成哈希:Java PBEKeySpec未生成所需的输出密钥长度,java,android,encryption,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; ch
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=
不应该再长一点吗 不,它的长度与您在
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
或
(注意:256bit=32字节)我想我今天睡得不够好。我的大脑决定忽略这些字节位
$ echo 'yo2NDJ96VYadiP2jpzL3p+LW0b4qkdWS++WqAm0W9d8=' | base64 --decode | wc
0 2 32