Files
LightlessClient/LightlessSync/Utils/Crypto.cs
2025-11-25 07:14:59 +09:00

62 lines
2.5 KiB
C#

using System;
using System.Collections.Concurrent;
using System.IO;
using System.Security.Cryptography;
using System.Text;
namespace LightlessSync.Utils;
public static class Crypto
{
//This buffersize seems to be the best sweetpoint for Linux and Windows
private const int _bufferSize = 65536;
#pragma warning disable SYSLIB0021 // Type or member is obsolete
private static readonly ConcurrentDictionary<(string, ushort), string> _hashListPlayersSHA256 = new();
private static readonly ConcurrentDictionary<string, string> _hashListSHA256 = new(StringComparer.Ordinal);
private static readonly SHA256CryptoServiceProvider _sha256CryptoProvider = new();
public static string GetFileHash(this string filePath)
{
using SHA1 sha1 = SHA1.Create();
using FileStream stream = File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete);
return BitConverter.ToString(sha1.ComputeHash(stream)).Replace("-", "", StringComparison.Ordinal);
}
public static async Task<string> GetFileHashAsync(string filePath, CancellationToken cancellationToken = default)
{
var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete, bufferSize: _bufferSize, options: FileOptions.Asynchronous);
await using (stream.ConfigureAwait(false))
{
using var sha1 = SHA1.Create();
var buffer = new byte[8192];
int bytesRead;
while ((bytesRead = await stream.ReadAsync(buffer, cancellationToken).ConfigureAwait(false)) > 0)
{
sha1.TransformBlock(buffer, 0, bytesRead, outputBuffer: null, 0);
}
sha1.TransformFinalBlock([], 0, 0);
return Convert.ToHexString(sha1.Hash!);
}
}
public static string GetHash256(this (string, ushort) playerToHash)
{
return _hashListPlayersSHA256.GetOrAdd(playerToHash, key => ComputeHashSHA256(key.Item1 + key.Item2.ToString()));
}
public static string GetHash256(this string stringToHash)
{
return _hashListSHA256.GetOrAdd(stringToHash, ComputeHashSHA256);
}
private static string ComputeHashSHA256(string stringToCompute)
{
using var sha = SHA256.Create();
return BitConverter.ToString(sha.ComputeHash(Encoding.UTF8.GetBytes(stringToCompute))).Replace("-", "", StringComparison.Ordinal);
}
#pragma warning restore SYSLIB0021 // Type or member is obsolete
}