95 lines
2.1 KiB
C#
95 lines
2.1 KiB
C#
using System;
|
|
using System.IO;
|
|
using System.Security.Cryptography;
|
|
using System.Threading;
|
|
using CommunityToolkit.HighPerformance;
|
|
using Org.BouncyCastle.Crypto.Digests;
|
|
|
|
namespace FrostFS.SDK.Cryptography;
|
|
|
|
public static class Extentions
|
|
{
|
|
private static readonly SHA256 _sha256 = SHA256.Create();
|
|
private static SpinLock _spinlockSha256;
|
|
|
|
private static readonly SHA512 _sha512 = SHA512.Create();
|
|
private static SpinLock _spinlockSha512;
|
|
|
|
internal static byte[] RIPEMD160(this byte[] value)
|
|
{
|
|
var hash = new byte[20];
|
|
|
|
var digest = new RipeMD160Digest();
|
|
digest.BlockUpdate(value, 0, value.Length);
|
|
digest.DoFinal(hash, 0);
|
|
return hash;
|
|
}
|
|
|
|
public static byte[] Sha256(this byte[] value)
|
|
{
|
|
bool lockTaken = false;
|
|
try
|
|
{
|
|
_spinlockSha256.Enter(ref lockTaken);
|
|
|
|
return _sha256.ComputeHash(value);
|
|
}
|
|
finally
|
|
{
|
|
if (lockTaken)
|
|
{
|
|
_spinlockSha256.Exit(false);
|
|
}
|
|
}
|
|
}
|
|
|
|
public static byte[] Sha256(this ReadOnlyMemory<byte> value)
|
|
{
|
|
bool lockTaken = false;
|
|
try
|
|
{
|
|
_spinlockSha256.Enter(ref lockTaken);
|
|
|
|
return _sha256.ComputeHash(value.AsStream());
|
|
}
|
|
finally
|
|
{
|
|
if (lockTaken)
|
|
{
|
|
_spinlockSha256.Exit(false);
|
|
}
|
|
}
|
|
}
|
|
|
|
public static byte[] Sha512(this ReadOnlyMemory<byte> value)
|
|
{
|
|
bool lockTaken = false;
|
|
try
|
|
{
|
|
_spinlockSha512.Enter(ref lockTaken);
|
|
|
|
return _sha512.ComputeHash(value.AsStream());
|
|
}
|
|
finally
|
|
{
|
|
if (lockTaken)
|
|
_spinlockSha512.Exit(false);
|
|
}
|
|
}
|
|
|
|
public static byte[] Sha512(this Stream stream)
|
|
{
|
|
bool lockTaken = false;
|
|
try
|
|
{
|
|
_spinlockSha512.Enter(ref lockTaken);
|
|
|
|
return _sha512.ComputeHash(stream);
|
|
}
|
|
finally
|
|
{
|
|
if (lockTaken)
|
|
_spinlockSha512.Exit(false);
|
|
}
|
|
}
|
|
}
|