Advertisement
Willcode4cash

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

Feb 6th, 2020
140
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.47 KB | None | 0 0
  1. using System;
  2. using System.IO;
  3. using System.Runtime.Serialization;
  4. using System.Security.Cryptography;
  5.  
  6. namespace HashExtension
  7. {
  8.     public static class ObjectExtensions
  9.     {
  10.         public static string GetHash<T>(this object instance) where T : HashAlgorithm, new()
  11.         {
  12.             T cryptoServiceProvider = new T();
  13.             return computeHash(instance, cryptoServiceProvider);
  14.         }
  15.  
  16.         public static string GetKeyedHash<T>(this object instance, byte[] key) where T : KeyedHashAlgorithm, new()
  17.         {
  18.             T cryptoServiceProvider = new T { Key = key };
  19.             return computeHash(instance, cryptoServiceProvider);
  20.         }
  21.  
  22.         public static string GetMD5Hash(this object instance)
  23.         {
  24.             return instance.GetHash<MD5CryptoServiceProvider>();
  25.         }
  26.  
  27.         public static string GetSHA1Hash(this object instance)
  28.         {
  29.             return instance.GetHash<SHA1CryptoServiceProvider>();
  30.         }
  31.  
  32.         private static string computeHash<T>(object instance, T cryptoServiceProvider) where T : HashAlgorithm, new()
  33.         {
  34.             DataContractSerializer serializer = new DataContractSerializer(instance.GetType());
  35.             using MemoryStream memoryStream = new MemoryStream();
  36.             serializer.WriteObject(memoryStream, instance);
  37.             cryptoServiceProvider.ComputeHash(memoryStream.ToArray());
  38.             return Convert.ToBase64String(cryptoServiceProvider.Hash);
  39.         }
  40.     }
  41. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement