using System.Security.Cryptography;
using System.Text;

namespace NPin.Framework.Core.Crypt.BCrypt;

public static class BCrypt
{
    public static byte[] Generate(string password, string salt, int cost)
    {
        var passBytes = Encoding.UTF8.GetBytes(password);
        var saltBytes = Encoding.UTF8.GetBytes(salt);

        return Org.BouncyCastle.Crypto.Generators.BCrypt.Generate(passBytes, saltBytes, cost);
    }

    public static string GenerateSalt()
    {
        var buf = new byte[16];
        using var rand = RandomNumberGenerator.Create();
        rand.GetBytes(buf);

        return Convert.ToBase64String(buf);
    }

    /// <summary>
    /// 检查密码是否正确
    /// 通过再次生成一次密码匹配
    /// </summary>
    /// <param name="encrypt"></param>
    /// <param name="password"></param>
    /// <param name="salt"></param>
    /// <param name="cost"></param>
    /// <returns></returns>
    public static bool Check(string encrypt, string password, string salt, int cost)
    {
        var passStr = Generate(password, salt, cost).ToString();

        return string.Equals(encrypt, passStr);
    }
}