Skip to content

Commit e38726d

Browse files
committed
Unify checksum helper methods
1 parent 73af92b commit e38726d

File tree

36 files changed

+337
-180
lines changed

36 files changed

+337
-180
lines changed

src/BizHawk.BizInvoke/WaterboxUtils.cs

Lines changed: 0 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
using System;
22
using System.IO;
3-
using System.Security.Cryptography;
43

54
namespace BizHawk.BizInvoke
65
{
@@ -22,18 +21,6 @@ public static void CopySome(Stream src, Stream dst, long len)
2221
}
2322
}
2423

25-
public static byte[] Hash(byte[] data)
26-
{
27-
using var h = SHA1.Create();
28-
return h.ComputeHash(data);
29-
}
30-
31-
public static byte[] Hash(Stream s)
32-
{
33-
using var h = SHA1.Create();
34-
return h.ComputeHash(s);
35-
}
36-
3724
public static unsafe void ZeroMemory(IntPtr mem, long length)
3825
{
3926
byte* p = (byte*)mem;

src/BizHawk.Client.Common/Api/Classes/MemoryApi.cs

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,8 @@
11
using System;
22
using System.Collections.Generic;
33
using System.Linq;
4-
using System.Security.Cryptography;
54

65
using BizHawk.Common;
7-
using BizHawk.Common.BufferExtensions;
86
using BizHawk.Emulation.Common;
97

108
namespace BizHawk.Client.Common
@@ -235,8 +233,7 @@ public string HashRegion(long addr, int count, string domain = null)
235233
}
236234
var data = new byte[count];
237235
for (var i = 0; i < count; i++) data[i] = d.PeekByte(addr + i);
238-
using var hasher = SHA256.Create();
239-
return hasher.ComputeHash(data).BytesToHexString();
236+
return SHA256Checksum.ComputeDigestHex(data);
240237
}
241238

242239
public uint ReadByte(long addr, string domain = null) => ReadUnsigned(addr, 1, domain);

src/BizHawk.Client.Common/RomLoader.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -233,7 +233,7 @@ private GameInfo MakeGameFromDisc(Disc disc, string ext, string name)
233233
var discType = new DiscIdentifier(disc).DetectDiscType();
234234
var discHasher = new DiscHasher(disc);
235235
var discHash = discType == DiscType.SonyPSX
236-
? discHasher.Calculate_PSX_BizIDHash().ToString("X8")
236+
? discHasher.Calculate_PSX_BizIDHash()
237237
: discHasher.OldHash();
238238

239239
var game = Database.CheckDatabase(discHash);

src/BizHawk.Client.Common/XmlGame.cs

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@
55
using System.Xml;
66

77
using BizHawk.Common;
8-
using BizHawk.Common.BufferExtensions;
98
using BizHawk.Common.IOExtensions;
109
using BizHawk.Emulation.Common;
1110

@@ -99,12 +98,11 @@ public static XmlGame Create(HawkFile f)
9998

10099
ret.Assets.Add(new KeyValuePair<string, byte[]>(filename, data));
101100
ret.AssetFullPaths.Add(fullPath);
102-
using var sha1 = System.Security.Cryptography.SHA1.Create();
103-
sha1.TransformFinalBlock(data, 0, data.Length);
104-
hashStream.Write(sha1.Hash, 0, sha1.Hash.Length);
101+
var sha1 = SHA1Checksum.Compute(data);
102+
hashStream.Write(sha1, 0, sha1.Length);
105103
}
106104

107-
ret.GI.Hash = hashStream.GetBuffer().HashSHA1(0, (int)hashStream.Length);
105+
ret.GI.Hash = SHA1Checksum.ComputeDigestHex(hashStream.GetBufferAsSpan());
108106
hashStream.Close();
109107
if (originalIndex != null)
110108
{

src/BizHawk.Client.Common/fwmanager/FirmwareManager.cs

Lines changed: 7 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,13 @@
11
#nullable enable
22

3-
using System;
43
using System.Collections.Generic;
54
using System.Diagnostics;
6-
using System.Security.Cryptography;
75
using System.IO;
86
using System.Linq;
97

10-
using BizHawk.Common.BufferExtensions;
8+
using BizHawk.Common;
119
using BizHawk.Common.CollectionExtensions;
10+
using BizHawk.Common.IOExtensions;
1211
using BizHawk.Emulation.Common;
1312

1413
namespace BizHawk.Client.Common
@@ -20,9 +19,7 @@ public sealed class FirmwareManager
2019
public static (byte[] Patched, string ActualHash) PerformPatchInMemory(byte[] @base, in FirmwarePatchOption patchOption)
2120
{
2221
var patched = patchOption.Patches.Aggregate(seed: @base, (a, fpd) => fpd.ApplyToMutating(a));
23-
using var sha1 = SHA1.Create();
24-
sha1.ComputeHash(patched);
25-
return (patched, sha1.Hash.BytesToHexString());
22+
return (patched, SHA1Checksum.ComputeDigestHex(patched));
2623
}
2724

2825
public static (string FilePath, int FileSize, FirmwareFile FF) PerformPatchOnDisk(string baseFilename, in FirmwarePatchOption patchOption, PathEntryCollection pathEntries)
@@ -95,26 +92,16 @@ public static (string FilePath, int FileSize, FirmwareFile FF) PerformPatchOnDis
9592
return resolved.FilePath;
9693
}
9794

98-
private sealed class RealFirmwareReader : IDisposable
95+
private sealed class RealFirmwareReader
9996
{
10097
private readonly Dictionary<string, RealFirmwareFile> _dict = new();
10198

102-
private SHA1? _sha1 = SHA1.Create();
103-
10499
public IReadOnlyDictionary<string, RealFirmwareFile> Dict => _dict;
105100

106-
public void Dispose()
107-
{
108-
_sha1?.Dispose();
109-
_sha1 = null;
110-
}
111-
112101
public RealFirmwareFile Read(FileInfo fi)
113102
{
114-
if (_sha1 == null) throw new ObjectDisposedException(nameof(RealFirmwareReader));
115103
using var fs = fi.OpenRead();
116-
_sha1!.ComputeHash(fs);
117-
var hash = _sha1.Hash.BytesToHexString();
104+
var hash = SHA1Checksum.ComputeDigestHex(fs.ReadAllBytes());
118105
return _dict![hash] = new RealFirmwareFile(fi, hash);
119106
}
120107
}
@@ -133,7 +120,7 @@ public bool CanFileBeImported(string f)
133120
if (!_firmwareSizes.Contains(fi.Length)) return false;
134121

135122
// check the hash
136-
using var reader = new RealFirmwareReader();
123+
var reader = new RealFirmwareReader();
137124
reader.Read(fi);
138125
var hash = reader.Dict.Values.First().Hash;
139126
return FirmwareDatabase.FirmwareFiles.Any(a => a.Hash == hash);
@@ -146,7 +133,7 @@ public bool CanFileBeImported(string f)
146133

147134
public void DoScanAndResolve(PathEntryCollection pathEntries, IDictionary<string, string> userSpecifications)
148135
{
149-
using var reader = new RealFirmwareReader();
136+
var reader = new RealFirmwareReader();
150137

151138
// build a list of files under the global firmwares path, and build a hash for each of them (as ResolutionInfo) while we're at it
152139
var todo = new Queue<DirectoryInfo>(new[] { new DirectoryInfo(pathEntries.AbsolutePathFor(pathEntries.FirmwaresPathFragment, null)) });

src/BizHawk.Client.EmuHawk/MainForm.Debug.cs

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,12 +5,11 @@
55
using System.IO;
66
using System.Linq;
77
using System.Reflection;
8-
using System.Security.Cryptography;
98
using System.Windows.Forms;
109

1110
using BizHawk.Client.Common;
1211
using BizHawk.Client.EmuHawk.Properties;
13-
using BizHawk.Common.BufferExtensions;
12+
using BizHawk.Common;
1413
using BizHawk.Emulation.Common;
1514
using BizHawk.Emulation.Cores;
1615
using BizHawk.Emulation.Cores.Nintendo.GBA;
@@ -88,9 +87,7 @@ public FirmwareAutopatchDebugToolForm()
8887
return;
8988
}
9089
// else something happened, figure out what it was
91-
using var sha1 = SHA1.Create();
92-
sha1.ComputeHash(@base);
93-
var baseHash = sha1.Hash.BytesToHexString();
90+
var baseHash = SHA1Checksum.ComputeDigestHex(@base);
9491
this.ModalMessageBox(baseHash == fpo.BaseHash
9592
? $"patchset declared with target\nSHA1:{fpo.TargetHash}\nbut produced\nSHA1:{actualHash}\n(is the patch wrong, or the hash?)"
9693
: $"patchset declared for base\nSHA1:{fpo.BaseHash}\nbut\nSHA1:{baseHash}\nwas provided");

src/BizHawk.Client.EmuHawk/MainForm.cs

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3822,8 +3822,9 @@ private bool LoadRomInternal(string path, LoadRomArgs args, out bool failureIsFr
38223822
else
38233823
{
38243824
xSw.WriteLine(xmlGame.Assets[xg].Key);
3825-
xSw.WriteLine($"SHA1:{xmlGame.Assets[xg].Value.HashSHA1()}");
3826-
xSw.WriteLine($"MD5:{xmlGame.Assets[xg].Value.HashMD5()}");
3825+
var data = xmlGame.Assets[xg].Value;
3826+
xSw.WriteLine(SHA1Checksum.ComputePrefixedHex(data));
3827+
xSw.WriteLine(MD5Checksum.ComputePrefixedHex(data));
38273828
xSw.WriteLine();
38283829
}
38293830
}
@@ -3857,7 +3858,7 @@ private bool LoadRomInternal(string path, LoadRomArgs args, out bool failureIsFr
38573858
var romDetails = Emulator.RomDetails();
38583859
if (string.IsNullOrWhiteSpace(romDetails) && loader.Rom != null)
38593860
{
3860-
_defaultRomDetails = $"{loader.Game.Name}\r\nSHA1:{loader.Rom.RomData.HashSHA1()}\r\nMD5:{loader.Rom.RomData.HashMD5()}\r\n";
3861+
_defaultRomDetails = $"{loader.Game.Name}\r\n{SHA1Checksum.ComputePrefixedHex(loader.Rom.RomData)}\r\n{MD5Checksum.ComputePrefixedHex(loader.Rom.RomData)}\r\n";
38613862
}
38623863
else if (string.IsNullOrWhiteSpace(romDetails) && loader.Rom == null)
38633864
{

src/BizHawk.Client.EmuHawk/tools/PCE/PCESoundDebugger.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
using System.Windows.Forms;
66

77
using BizHawk.Client.Common;
8-
using BizHawk.Common.BufferExtensions;
8+
using BizHawk.Common;
99
using BizHawk.Emulation.Cores.PCEngine;
1010
using BizHawk.Emulation.Common;
1111

@@ -103,7 +103,7 @@ protected override void UpdateAfter()
103103
}
104104

105105
bw.Flush();
106-
string md5 = _waveformTemp.HashMD5();
106+
var md5 = MD5Checksum.ComputeDigestHex(_waveformTemp);
107107

108108
if (!_psgEntryTable.TryGetValue(md5, out var entry))
109109
{

src/BizHawk.Common/Extensions/BufferExtensions.cs

Lines changed: 0 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
using System;
22
using System.IO;
33
using System.Text;
4-
using System.Security.Cryptography;
54

65
namespace BizHawk.Common.BufferExtensions
76
{
@@ -77,30 +76,6 @@ public static bool FindBytes(this byte[] array, byte[] pattern)
7776
return result >= pattern.Length - 1;
7877
}
7978

80-
public static string HashMD5(this byte[] data, int offset, int len)
81-
{
82-
using var md5 = MD5.Create();
83-
md5.ComputeHash(data, offset, len);
84-
return md5.Hash.BytesToHexString();
85-
}
86-
87-
public static string HashMD5(this byte[] data)
88-
{
89-
return HashMD5(data, 0, data.Length);
90-
}
91-
92-
public static string HashSHA1(this byte[] data, int offset, int len)
93-
{
94-
using var sha1 = SHA1.Create();
95-
sha1.ComputeHash(data, offset, len);
96-
return sha1.Hash.BytesToHexString();
97-
}
98-
99-
public static string HashSHA1(this byte[] data)
100-
{
101-
return HashSHA1(data, 0, data.Length);
102-
}
103-
10479
private static int Hex2Int(char c)
10580
{
10681
if (c <= '9')

src/BizHawk.Common/Extensions/IOExtensions.cs

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,14 @@
1-
using System.IO;
1+
using System;
2+
using System.IO;
23
using System.Text;
34

45
namespace BizHawk.Common.IOExtensions
56
{
67
public static class IOExtensions
78
{
9+
public static Span<byte> GetBufferAsSpan(this MemoryStream ms)
10+
=> ms.GetBuffer().AsSpan().Slice(start: 0, length: (int) ms.Length);
11+
812
public static byte[] ReadAllBytes(this Stream stream)
913
{
1014
const int BUFF_SIZE = 4096;

0 commit comments

Comments
 (0)