You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
69 lines
1.7 KiB
69 lines
1.7 KiB
using System; |
|
using System.IO; |
|
using System.Text; |
|
using System.Reflection; |
|
using System.Runtime.CompilerServices; |
|
using System.Security.Cryptography; |
|
|
|
public static class HashAlgorithm<THashAlgorithm> |
|
where THashAlgorithm : HashAlgorithm |
|
{ |
|
/// <summary> |
|
/// 线程静态变量:即该变量在每个线程中唯一目的是为了避开多线程问题 |
|
/// </summary> |
|
[ThreadStatic] |
|
private static THashAlgorithm instance; |
|
|
|
/// <summary> |
|
/// 哈希算法单例。 |
|
/// </summary> |
|
public static THashAlgorithm Instance => instance ?? Create(); |
|
|
|
public static string ComputeHash(Stream input) |
|
{ |
|
var instance = Instance; |
|
|
|
var bytes = instance.ComputeHash(input); |
|
|
|
var result = Convert.ToBase64String(bytes); |
|
|
|
return result; |
|
} |
|
|
|
public static string ComputeHash(byte[] input) |
|
{ |
|
var instance = Instance; |
|
|
|
var bytes = instance.ComputeHash(input); |
|
|
|
var result = Convert.ToBase64String(bytes); |
|
|
|
return result; |
|
} |
|
|
|
public static string ComputeHash(string input) |
|
{ |
|
var bytes = Encoding.UTF8.GetBytes(input); |
|
|
|
return ComputeHash(bytes); |
|
} |
|
|
|
[MethodImpl(MethodImplOptions.NoInlining)] |
|
private static THashAlgorithm Create() |
|
{ |
|
var createMethod = typeof(THashAlgorithm).GetMethod( |
|
nameof(HashAlgorithm.Create), |
|
BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly, |
|
Type.DefaultBinder, |
|
Type.EmptyTypes, |
|
null); |
|
|
|
if (createMethod != null) |
|
instance = (THashAlgorithm)createMethod.Invoke(null, new object[] { }); |
|
else |
|
instance = Activator.CreateInstance<THashAlgorithm>(); |
|
|
|
return instance; |
|
} |
|
} |
|
|
|
|