5 using System.Collections.Generic;
6 using System.Security.Cryptography;
8 using System.Text.RegularExpressions;
16 private static string RemoveWhitespace(
string s)
18 StringBuilder sb =
new StringBuilder(s.Length / 2);
20 for (
int i = 0; i < s.Length; i++)
22 if (
char.IsWhiteSpace(s[i])) {
continue; }
29 private static readonly Regex stringHashRegex =
new Regex(
@"^[0-9a-fA-F]{7,32}$", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);
35 private static void CalculateHash(
byte[] bytes, out
string stringRepresentation, out
byte[] byteRepresentation)
37 using (MD5 md5 = MD5.Create())
39 byte[] byteHash = md5.ComputeHash(bytes);
41 byteRepresentation = byteHash;
42 stringRepresentation = ByteRepresentationToStringRepresentation(byteHash);
46 private static string ByteRepresentationToStringRepresentation(
byte[] byteHash)
47 => ToolBoxCore.ByteArrayToHexString(byteHash);
49 private static byte[] StringRepresentationToByteRepresentation(
string strHash)
50 => ToolBoxCore.HexStringToByteArray(strHash);
54 return fullHash.Length < 7 ? fullHash : fullHash.Substring(0, 7);
65 private Md5Hash(
byte[] bytes,
bool calculate)
82 if (!stringHashRegex.IsMatch(hash)) {
throw new ArgumentException($
"{hash} is not a valid hash"); }
88 using IncrementalHash incrementalHash = IncrementalHash.CreateHash(HashAlgorithmName.MD5);
89 foreach (var hash
in hashes)
91 incrementalHash.AppendData(hash.ByteRepresentation);
93 return BytesAsHash(incrementalHash.GetHashAndReset());
98 return new Md5Hash(bytes, calculate:
true);
103 return new Md5Hash(bytes, calculate:
false);
111 IgnoreWhitespace = 0x2
118 string str = File.ReadAllText(path, Encoding.UTF8);
123 byte[] bytes = File.ReadAllBytes(path);
132 str = str.ToLowerInvariant();
136 str = RemoveWhitespace(str);
138 byte[] bytes = Encoding.UTF8.GetBytes(str);
157 return selfStr.Equals(otherStr, StringComparison.OrdinalIgnoreCase);
static Md5Hash MergeHashes(IEnumerable< Md5Hash > hashes)
static Md5Hash BytesAsHash(byte[] bytes)
static bool operator==(Md5Hash? a, Md5Hash? b)
static bool operator!=(Md5Hash? a, Md5Hash? b)
static Md5Hash CalculateForFile(string path, StringHashOptions options)
static Md5Hash StringAsHash(string hash)
override bool Equals(object? obj)
override string ToString()
static Md5Hash CalculateForBytes(byte[] bytes)
override int GetHashCode()
readonly string StringRepresentation
readonly byte[] ByteRepresentation
readonly string ShortRepresentation
static Md5Hash CalculateForString(string str, StringHashOptions options)
static readonly Md5Hash Blank
static string GetShortHash(string fullHash)