46 lines
1.2 KiB
C#
46 lines
1.2 KiB
C#
using System.Collections.Concurrent;
|
|
using System.Security;
|
|
|
|
namespace StellaOps.Scanner.Analyzers.Lang.Rust.Internal;
|
|
|
|
internal static class RustFileHashCache
|
|
{
|
|
private static readonly ConcurrentDictionary<RustFileCacheKey, string> Sha256Cache = new();
|
|
|
|
public static bool TryGetSha256(string path, out string? sha256)
|
|
{
|
|
sha256 = null;
|
|
|
|
if (!RustFileCacheKey.TryCreate(path, out var key))
|
|
{
|
|
return false;
|
|
}
|
|
|
|
try
|
|
{
|
|
sha256 = Sha256Cache.GetOrAdd(key, static (_, state) => ComputeSha256(state), path);
|
|
return !string.IsNullOrEmpty(sha256);
|
|
}
|
|
catch (IOException)
|
|
{
|
|
return false;
|
|
}
|
|
catch (UnauthorizedAccessException)
|
|
{
|
|
return false;
|
|
}
|
|
catch (SecurityException)
|
|
{
|
|
return false;
|
|
}
|
|
}
|
|
|
|
private static string ComputeSha256(string path)
|
|
{
|
|
using var stream = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.Read);
|
|
using var sha = System.Security.Cryptography.SHA256.Create();
|
|
var hash = sha.ComputeHash(stream);
|
|
return Convert.ToHexString(hash).ToLowerInvariant();
|
|
}
|
|
}
|