Search code examples
c#.netcryptography.net-corehashalgorithm

Deriving from HashAlgorithm in .NET Core


In .NET Framework if we needed to create our own crypto algorithm we could create our own class like:

public class MyAlgorithm: System.Security.Cryptography.HashAlgorithm
{
}

But in .NET Core it seems very limited because of

public abstract class HashAlgorithm : IDisposable
    {     

    protected HashAlgorithm();    
    public virtual int HashSize { get; }    
    public byte[] ComputeHash(byte[] buffer);
    public byte[] ComputeHash(byte[] buffer, int offset, int count);
    public byte[] ComputeHash(Stream inputStream);
    public void Dispose();
    public abstract void Initialize();
    protected virtual void Dispose(bool disposing);
    protected abstract void HashCore(byte[] array, int ibStart, int cbSize);
    protected abstract byte[] HashFinal();
}

It doesn't have such things as HashSizeValue or State.

Should we still use HashAlgorithm as base class for own algorithms in .NET Core?


Solution

  • In your class, implement a

    public override int HashSize => 256;
    

    (or the value you have).

    If you are using HashSizeValue, change it to HashSize.

    If you are using State, readd it as a protected int State. In the "full" HashAlgorithm it is used by two public methods (TransformBlock and TransformFinalBlock). If you need it (and you are using TransformBlock and TransformFinalBlock) then copy it from a newer version of .NET Core HashAlgorithm (you can find it on github). If you were only checking it then you don't need it and you can comment it (because only two missing methods will be writing it).