2022-01-25 19:13:37 +02:00
|
|
|
|
using System;
|
|
|
|
|
|
using System.Collections.Generic;
|
2022-01-26 20:20:18 +00:00
|
|
|
|
using System.Security.Cryptography;
|
2022-01-25 19:13:37 +02:00
|
|
|
|
|
2022-01-29 16:44:34 +02:00
|
|
|
|
namespace Framework.Cryptography
|
2022-01-25 19:13:37 +02:00
|
|
|
|
{
|
2022-01-26 20:20:18 +00:00
|
|
|
|
public enum HashAlgorithm
|
2022-01-25 19:13:37 +02:00
|
|
|
|
{
|
|
|
|
|
|
SHA1,
|
|
|
|
|
|
}
|
|
|
|
|
|
|
2022-01-26 20:20:18 +00:00
|
|
|
|
public static class HashHelper
|
2022-01-25 19:13:37 +02:00
|
|
|
|
{
|
|
|
|
|
|
private delegate byte[] HashFunction(params byte[][] data);
|
|
|
|
|
|
|
2022-01-26 20:20:18 +00:00
|
|
|
|
static Dictionary<HashAlgorithm, HashFunction> _hashFunctions;
|
2022-01-25 19:13:37 +02:00
|
|
|
|
|
|
|
|
|
|
static HashHelper()
|
|
|
|
|
|
{
|
2022-01-26 20:20:18 +00:00
|
|
|
|
_hashFunctions = new Dictionary<HashAlgorithm, HashFunction>
|
|
|
|
|
|
{
|
|
|
|
|
|
[HashAlgorithm.SHA1] = SHA1Func
|
|
|
|
|
|
};
|
|
|
|
|
|
}
|
2022-01-25 19:13:37 +02:00
|
|
|
|
|
2022-01-26 20:20:18 +00:00
|
|
|
|
/// <summary>
|
|
|
|
|
|
/// Hash based on <see cref="HashAlgorithm"/> and provided <see cref="byte[][]"/> data.
|
|
|
|
|
|
/// </summary>
|
|
|
|
|
|
public static byte[] Hash(this HashAlgorithm algorithm, params byte[][] data)
|
|
|
|
|
|
=> _hashFunctions[algorithm](data);
|
|
|
|
|
|
|
|
|
|
|
|
static byte[] SHA1Func(params byte[][] data)
|
|
|
|
|
|
{
|
|
|
|
|
|
using (SHA1 alg = SHA1.Create())
|
|
|
|
|
|
{
|
|
|
|
|
|
return alg.ComputeHash(Combine(data));
|
|
|
|
|
|
}
|
2022-01-25 19:13:37 +02:00
|
|
|
|
}
|
|
|
|
|
|
|
2022-01-26 20:20:18 +00:00
|
|
|
|
static byte[] Combine(byte[][] buffers)
|
2022-01-25 19:13:37 +02:00
|
|
|
|
{
|
|
|
|
|
|
int length = 0;
|
|
|
|
|
|
foreach (var buffer in buffers)
|
|
|
|
|
|
length += buffer.Length;
|
|
|
|
|
|
|
|
|
|
|
|
byte[] result = new byte[length];
|
|
|
|
|
|
|
|
|
|
|
|
int position = 0;
|
|
|
|
|
|
|
|
|
|
|
|
foreach (var buffer in buffers)
|
|
|
|
|
|
{
|
|
|
|
|
|
Buffer.BlockCopy(buffer, 0, result, position, buffer.Length);
|
|
|
|
|
|
position += buffer.Length;
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
return result;
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|
|
|
|
|
|
}
|