package lc.mecha.crypto;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

/**
 * This class implements basic mechanics for processing passwords in a secure manner, including producing
 * hashes for long-term storage when there is a potential for data breach.
 *
 * @author Alex Leigh
 */
public class PasswordProcessor {
    SecureRandom rnd = new SecureRandom();

    /**
     * Generate a salt of sufficient size to be equal to the size of the hash provided by this class. Currently,
     * this implementation returns a 16 byte hash, although that specific length should not be depended on.
     */
    byte[] generateSalt() {
        byte[] salt = new byte[16];
        rnd.nextBytes(salt);
        return salt;
    }

    /**
     * Hash the provided password in the UTF-8 charset with the provided hash, and return the bytes to the caller.
     * Currently, this implemtnation uses the SHA-256 algorithm.
     */
    byte[] hashPassword(byte[] salt, String password) throws NoSuchAlgorithmException {
        MessageDigest md = MessageDigest.getInstance("SHA-256");
        md.update(salt);
        return md.digest(password.getBytes(StandardCharsets.UTF_8));
    }
}
