package bp;

import org.mindrot.jbcrypt.BCrypt;

/**
 * Class for testing password, it's has with another hash.
 *
 * @author František Flachs
 */
public class Password {

    /**
     *
     * @param password_plaintext
     * @param stored_hash
     * @return true if password and stored are
     */
    private static boolean passwordCheck(String password_plaintext, String stored_hash) {
        if (null != stored_hash || stored_hash.startsWith("$2a$")) {
            return BCrypt.checkpw(password_plaintext, stored_hash);
        }
        return false;
    }

    /**
     * Comparing password with his hash and another hash.
     *
     * @param test_passwd - testing password
     * @param test_hash - testing hash
     * @return true if the hash of testing password and testing hash are same
     */
    public static boolean testPassword(String test_passwd, String test_hash) {
        System.out.println("Test password: " + test_passwd);
        System.out.println("Test stored hash: " + test_hash.replaceFirst("2y", "2a"));

        String computed_hash = BCrypt.hashpw(test_passwd, BCrypt.gensalt(12));
        System.out.println("Test computed hash: " + computed_hash.replaceFirst("2y", "2a"));

        String compare_test;
        if (passwordCheck(test_passwd, test_hash.replaceFirst("2y", "2a"))) {
            compare_test = "Passwords match";
        } else {
            compare_test = "Passwords do not match";
        }
        System.out.println("Verify against stored hash:   " + compare_test);

        String compare_computed;
        if (passwordCheck(test_passwd, computed_hash)) {
            compare_computed = "Passwords match";
        } else {
            compare_computed = "Passwords do not match";
        }
        System.out.println("Verify against computed hash: " + compare_computed);

        return compare_test.equals("Passwords match") && compare_computed.equals("Passwords match");

    }
}
