How do I calculate the equivalent to SQL Server (hashbytes('SHA1',[ColumnName])) in C#?

前端 未结 3 1394
醉梦人生
醉梦人生 2020-12-03 18:50

In my database I have a computed column that contains a SHA1 hash of a column called URLString which holds URLs (e.g. \"http://xxxx.com/index.html\").

I often need t

3条回答
  •  心在旅途
    2020-12-03 19:25

    Below are two methods that do hashing of string and of bytes. The HashBytes method returns Base64 of the resulting bytes but you can return just the bytes if you prefer them

    public static string HashString(string cleartext)
    {
        byte[] clearBytes = Encoding.UTF8.GetBytes(cleartext);
        return HashBytes(clearBytes);
    }  
    
    public static string HashBytes(byte[] clearBytes)
    {
        SHA1 hasher = SHA1.Create();
        byte[] hashBytes =   hasher.ComputeHash(clearBytes);
        string hash = System.Convert.ToBase64String(hashBytes);
        hasher.Clear();
        return hash;
    }
    

提交回复
热议问题