Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement