user2739518
user2739518

Reputation: 217

Java encryption equals not working

Okay so I have this hash method:

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

It hashes fine as far as I can tell, and when it returns a string I compare it to the string I have and they look identical, but the .equals method says there not. Anybody got any ideas cause am literally all out

This is the entire LoginHelper class:

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

I call with:

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

Upvotes: 0

Views: 151

Answers (1)

erickson
erickson

Reputation: 269627

Compare storedHash to calculatedHash. You are comparing storedPassword, which still has the prefix "pbkdf2_sha256$20000$".

Upvotes: 2

Related Questions