简体   繁体   English

密码加密方法永远不会为相同的参数返回相同的结果

[英]Password encryption method never returns the same result for the same parameters

I have found code leveraging java.security.* in order to encrypt passwords. 发现了利用java.security.*代码来加密密码。 But when I use it, It's not working. 但是当我使用它时,它不起作用。 Each time I call the encrypt method with the same parameters (which are displayed in the encrypt() method, and are really each time the same), I get a different result, which of course makes the code useless. 每次我使用相同的参数(在encrypt()方法中显示,并且实际上每次都相同)调用crypto方法时,都会得到不同的结果,这当然会使代码无用。 Here my code: 这是我的代码:

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;
}

I think I introduced an error in the original code at some point, but I can't see where. 我想我在某个时候在原始代码中引入了一个错误,但是我看不到哪里。 Any idea? 任何想法?

It's because System.out.println(truc); 这是因为System.out.println(truc); does not do what you think it does. 不按照您的想法去做。 If you tried: 如果您尝试:

System.out.println(Arrays.toString(truc));

you would print the actual content of the array, which should be the same every time you call the method with the same parameters. 您将打印数组的实际内容,每次使用相同参数调用该方法时,该内容都应该相同。

See for example: printing arrays 例如,参见: 打印数组

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM