Willcode4cash icon

Compute any hash for any object in C# (.Net Core 3.0)

Willcode4cash | PRO | 02/07/20 04:46:55 AM UTC | 0 ⭐ | 329 👁️ | Never ⏰ | []
C# |

1.47 KB

|

None

|

0 👍

/

0 👎

using System;
using System.IO;
using System.Runtime.Serialization;
using System.Security.Cryptography;
 
namespace HashExtension
{
    public static class ObjectExtensions
    {
        public static string GetHash<T>(this object instance) where T : HashAlgorithm, new()
        {
            T cryptoServiceProvider = new T();
            return computeHash(instance, cryptoServiceProvider);
        }
 
        public static string GetKeyedHash<T>(this object instance, byte[] key) where T : KeyedHashAlgorithm, new()
        {
            T cryptoServiceProvider = new T { Key = key };
            return computeHash(instance, cryptoServiceProvider);
        }
 
        public static string GetMD5Hash(this object instance)
        {
            return instance.GetHash<MD5CryptoServiceProvider>();
        }
 
        public static string GetSHA1Hash(this object instance)
        {
            return instance.GetHash<SHA1CryptoServiceProvider>();
        }
 
        private static string computeHash<T>(object instance, T cryptoServiceProvider) where T : HashAlgorithm, new()
        {
            DataContractSerializer serializer = new DataContractSerializer(instance.GetType());
            using MemoryStream memoryStream = new MemoryStream();
            serializer.WriteObject(memoryStream, instance);
            cryptoServiceProvider.ComputeHash(memoryStream.ToArray());
            return Convert.ToBase64String(cryptoServiceProvider.Hash);
        }
    }
}

Comments