具有自定义 HashAlgorithm 的 HMAC

HMAC with custom HashAlgorithm

内置了 HMAC(HMACSHA1 - HMACSHA512 ...)。 但是是否可以使用自定义 HashAlgorithm 创建 HMAC class?

我试过 HMAC.Create("location") 但那只是抛出了一个 NullReferenceException

会不会有像new HMAC(HashAlgorithm)这样的构造函数?

这是哈希算法(Fnv1 哈希)的代码:

public class Fnv1_32 : HashAlgorithm
{
    private const uint prime = 0x01000193;
    private const uint offsetbasis = 0x811C9DC5;
    private uint _Hash;

    public Fnv1_32()
    {
        this.Initialize();
        this.HashSizeValue = 32;
    }

    public override void Initialize()
    {
        this._Hash = offsetbasis;
    }

    protected override void HashCore(byte[] array, int ibStart, int cbSize)
    {
        for (var i = ibStart; i < cbSize; i++)
        {
            this._Hash *= prime;
            this._Hash ^= array[i];
        }
    }

    protected override byte[] HashFinal()
    {
        return BitConverter.GetBytes(this._Hash);
    }
}

在 .NET Framework 中,您可以通过

public class HMACFnv1_32 : HMAC
{
    private const string Fnv1CryptoConfigId = "Fnv1_32";

    static HMACFnv1_32()
    {
        CryptoConfig.AddAlgorithm(typeof(Fnv1_32), Fnv1CryptoConfigId);
    }

    public HMACFnv1_32(byte[] key)
    {
        HashName = Fnv1CryptoConfigId;
        HashSizeValue = 32;
        Key = key;
    }
}

在 .NET Core 上,HMAC 实现已被删除,所有内置 HMAC 类 调用系统密码库来执行 HMAC 计算。因此,您需要自己编写 HMAC 才能在 .NET Core 中使用自定义摘要。