我发现利用代码java.security.*
来加密密码。但是当我使用它时,它不起作用。每次调用 encrypt 方法的参数都一样(encrypt()
方法中显示的,而且每次都一样),得到的结果都不一样,这当然让代码没用了。这是我的代码:
public byte[] encrypt(String clearPassword, byte[] salt) throws NoSuchAlgorithmException, InvalidKeySpecException {
System.out.println(clearPassword+" ********** "+salt);
String algorithm = "PBKDF2WithHmacSHA1";
int derivedKeyLength = 1600;
int iterations = 20000;
KeySpec spec = new PBEKeySpec(clearPassword.toCharArray(), salt, iterations, derivedKeyLength);
SecretKeyFactory f = SecretKeyFactory.getInstance(algorithm);
byte [] truc = f.generateSecret(spec).getEncoded();
System.out.println(truc);
return truc;
}
public byte[] generateSalt() throws NoSuchAlgorithmException {
SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
byte[] salt = new byte[8];
random.nextBytes(salt);
return salt;
}
我想我在某些时候在原始代码中引入了一个错误,但我看不到在哪里。任何想法?