66 lines
1.8 KiB
C#
66 lines
1.8 KiB
C#
using System.Security.Cryptography;
|
|
|
|
namespace OmniNX.DesktopInstaller.Services;
|
|
|
|
public static class Sha256Sums
|
|
{
|
|
public static string? FindHash(string sumsText, string fileName)
|
|
{
|
|
foreach (var rawLine in sumsText.Split('\n'))
|
|
{
|
|
var line = rawLine.Trim();
|
|
if (line.Length == 0 || line[0] == '#')
|
|
continue;
|
|
|
|
var splitAt = line.IndexOf(' ');
|
|
if (splitAt <= 0)
|
|
continue;
|
|
|
|
var hash = line[..splitAt].Trim();
|
|
var name = line[(splitAt + 1)..].Trim();
|
|
if (name.StartsWith('*'))
|
|
name = name[1..];
|
|
|
|
if (!IsSha256Hex(hash))
|
|
continue;
|
|
|
|
if (name.Equals(fileName, StringComparison.OrdinalIgnoreCase))
|
|
return hash;
|
|
}
|
|
|
|
return null;
|
|
}
|
|
|
|
public static async Task<string> HashFileAsync(string path, CancellationToken cancellationToken = default)
|
|
{
|
|
await using var stream = new FileStream(
|
|
path,
|
|
FileMode.Open,
|
|
FileAccess.Read,
|
|
FileShare.Read,
|
|
bufferSize: 1024 * 1024,
|
|
FileOptions.Asynchronous | FileOptions.SequentialScan);
|
|
|
|
var hash = await SHA256.HashDataAsync(stream, cancellationToken);
|
|
return Convert.ToHexString(hash);
|
|
}
|
|
|
|
public static bool Matches(string actualHex, string expectedHex) =>
|
|
string.Equals(actualHex.Trim(), expectedHex.Trim(), StringComparison.OrdinalIgnoreCase);
|
|
|
|
private static bool IsSha256Hex(string value)
|
|
{
|
|
if (value.Length != 64)
|
|
return false;
|
|
|
|
foreach (var c in value)
|
|
{
|
|
var isHex = c is >= '0' and <= '9' or >= 'a' and <= 'f' or >= 'A' and <= 'F';
|
|
if (!isHex)
|
|
return false;
|
|
}
|
|
|
|
return true;
|
|
}
|
|
}
|