Java加密等于不起作用

时间:2015-07-27 19:54:06

标签: java hash

好的,我有这个哈希方法:

public static String getEncodedHash(String password, String salt) throws UnsupportedEncodingException {
    // Returns only the last part of whole encoded password
    PKCS5S2ParametersGenerator gen = new PKCS5S2ParametersGenerator(new SHA256Digest());

    gen.init(password.getBytes(), salt.getBytes(), DEFAULT_ITERATIONS);
    byte[] dk = ((KeyParameter) gen.generateDerivedParameters(256)).getKey();

    return Base64.toBase64String(dk);
}

据我所知,它很好,当它返回一个字符串时,我将它与我所拥有的字符串进行比较,它们看起来完全相同,但.equals方法却没有。任何人都有任何想法因为我真的全力以赴

这是整个LoginHelper类:

import java.io.UnsupportedEncodingException;

import org.spongycastle.crypto.digests.SHA256Digest;
import org.spongycastle.crypto.generators.PKCS5S2ParametersGenerator;
import org.spongycastle.crypto.params.KeyParameter;
import org.spongycastle.util.encoders.Base64;

public class LoginHelper {
    public static final Integer DEFAULT_ITERATIONS = 20000;

    public static boolean passwordCorrect(String enteredPassword, String storedPassword) throws UnsupportedEncodingException {
        String[] parts = storedPassword.split("\\$");
        String salt = parts[2];
        String storedHash = parts[3];
        String calculatedHash = getEncodedHash(enteredPassword, salt);

        System.out.println(storedHash);
        System.out.println(calculatedHash);

        System.out.println(storedHash.length());
        System.out.println(calculatedHash.length());

        return storedPassword.equals(calculatedHash);
    }

    public static String getEncodedHash(String password, String salt) throws UnsupportedEncodingException {
        // Returns only the last part of whole encoded password
        PKCS5S2ParametersGenerator gen = new PKCS5S2ParametersGenerator(new SHA256Digest());

        gen.init(password.getBytes(), salt.getBytes(), DEFAULT_ITERATIONS);
        byte[] dk = ((KeyParameter) gen.generateDerivedParameters(256)).getKey();

        return Base64.toBase64String(dk);
    }
}

我致电:

System.out.println(LoginHelper.passwordCorrect("password","pbkdf2_sha256$20000$wlW7Po1nm1DW$nt9LYWbxwvHIXmyBGUQG7NyPDkrt/2fivN3ws//HzLnks="));

1 个答案:

答案 0 :(得分:2)

storedHashcalculatedHash进行比较。您正在比较storedPassword,它仍然具有前缀"pbkdf2_sha256$20000$"