SecurityUtils.java

/*
 * Copyright © 2024-2025 The CTAN Team and individual authors
 *
 * This file is distributed under the 3-clause BSD license.
 * See file LICENSE for details.
 */

package org.ctan.site.services.util;

import at.favre.lib.crypto.bcrypt.BCrypt;
import at.favre.lib.crypto.bcrypt.BCrypt.Hasher;
import at.favre.lib.crypto.bcrypt.BCrypt.Verifyer;

/**
 * The class <code>SecurityUtils</code> contains utility methods in the area of
 * security.
 */
public class SecurityUtils {

    /**
     * The field <code>HASHER</code> contains the hasher.
     */
    private static final Hasher HASHER = BCrypt.withDefaults();

    /**
     * The field <code>VERIFIER</code> contains the verifier.
     */
    private static final Verifyer VERIFIER = BCrypt.verifyer();

    /**
     * The method <code>generateHash</code> provides means to compute the hash
     * value for an input password.
     *
     * @param password the password
     * @return the generated hash
     */
    public static String generateHash(String password) {

        return HASHER.hashToString(BCrypt.MIN_COST, password.toCharArray());
    }

    /**
     * The method <code>verify</code> provides means to check that the hash fits
     * to the password.
     *
     * @param passwd the password
     * @param hash the hash value
     * @return {@code true} iff the validation succeeds
     */
    public static boolean verify(String passwd, String hash) {

        return hash != null
            && VERIFIER.verify(passwd.toCharArray(), hash).verified;
    }

    /**
     * This is the constructor for <code>SecurityUtils</code>.
     */
    private SecurityUtils() {

    }
}