188 Commits
1.2.3 ... main

Author SHA1 Message Date
Matt Nadareski
a334ffc25a Slightly more cleanup and clarification 2026-01-27 09:13:30 -05:00
Matt Nadareski
3211f1a218 Use new null checking syntax 2026-01-25 17:12:44 -05:00
Matt Nadareski
3c451b8570 Add editorconfig, fix issues 2026-01-25 17:11:44 -05:00
Matt Nadareski
ecd52b1a0e Add issue templates 2026-01-11 09:25:38 -05:00
Matt Nadareski
0075b9b1ad Add CRC-32/DVD-ROM-EDC (fixes #4) 2026-01-11 09:20:15 -05:00
Matt Nadareski
214b449e5e Format GHA definitions 2025-11-17 08:38:13 -05:00
Matt Nadareski
0bb3e541be Fix one property group 2025-11-13 20:38:04 -05:00
Matt Nadareski
d91220a2e4 Bump version 2025-11-13 07:25:14 -05:00
Matt Nadareski
e60a1fbe3c These can be static 2025-11-12 21:41:40 -05:00
Matt Nadareski
978a3847de Add support for .NET 10 2025-11-12 20:00:11 -05:00
Matt Nadareski
48da4cd88e Update rolling tag 2025-10-26 20:21:42 -04:00
Matt Nadareski
458499eea4 Bump version 2025-10-07 09:06:58 -04:00
Matt Nadareski
47cb600f3f Fix accidental cutoff 2025-10-07 09:02:11 -04:00
Matt Nadareski
d42af9b95d Consistency matching cleanup 2025-10-07 09:01:12 -04:00
Matt Nadareski
8672fea581 Used mixed features and inputs 2025-10-06 11:31:54 -04:00
Matt Nadareski
a5b36a8329 Update readme to match help text 2025-10-06 09:12:58 -04:00
Matt Nadareski
b83cafebf1 Reorganize based on lessons from other implementations 2025-10-06 09:12:48 -04:00
Matt Nadareski
2b7f09f06f Update CommandLine to 1.3.2 2025-10-06 07:29:48 -04:00
Matt Nadareski
2a37f8c03a Set text formatting in readme 2025-10-05 22:08:02 -04:00
Matt Nadareski
51c3ecec4b Fully use CommandLine modelling 2025-10-05 20:31:15 -04:00
Matt Nadareski
97a1338cab Update CommandLine to 1.3.1 2025-10-05 20:11:35 -04:00
Matt Nadareski
a808c9ba3c Use CommandLine library for executable 2025-10-05 19:47:02 -04:00
Matt Nadareski
53e28df7f8 Make MekaCrc official 2025-09-25 07:51:44 -04:00
Matt Nadareski
bdde3bad16 Use BitConverter instead of Convert 2025-09-25 07:39:57 -04:00
Matt Nadareski
32491ccaae Add "mekacrc", not hooked up or validated 2025-09-24 23:20:30 -04:00
Matt Nadareski
ae3fc9ef56 Fix typo introduced by cleanup 2025-09-24 22:38:38 -04:00
Matt Nadareski
8d52187a03 Minor typing cleanup 2025-09-24 22:36:45 -04:00
Matt Nadareski
720a3a4c2b Slightly improve HasCommonSubstring 2025-09-24 22:35:40 -04:00
Matt Nadareski
0872d8c927 Slight reorganization 2025-09-24 22:20:31 -04:00
Matt Nadareski
1619046d11 Rewrite comparison code to fit C# better, add tests 2025-09-24 22:18:02 -04:00
Matt Nadareski
4fda55d4d1 Move static method higher in the class 2025-09-24 21:58:12 -04:00
Matt Nadareski
349a414ff3 Slight cleanup based on preferred style and naming 2025-09-24 21:55:20 -04:00
Matt Nadareski
05617c5c7e Slight test cleanup 2025-09-24 21:41:26 -04:00
HeroponRikiBestest
cce8a18b03 Add SpamSum fuzzy compare (#3)
* Pre-cleaned drop in fuzzycompare

* Finish cleaning up code.

* Figure out why i can't debug my unit tests

* Fix stupid mistake

* First round of changes

* Extra tests

* Revert TestHelper.cs

* Roll back TestHelper.cs correctly.

* Roll back Options.cs and Program.cs
2025-09-24 21:32:11 -04:00
Matt Nadareski
cbaa79b284 Minor tweaks 2025-09-23 14:18:50 -04:00
Matt Nadareski
32cd0e73ed Add hashing tool implementation, for fun 2025-09-23 14:15:27 -04:00
Matt Nadareski
95589df904 There 2025-09-10 21:52:28 -04:00
Matt Nadareski
fd612f939a Bump version 2025-07-24 08:44:08 -04:00
Matt Nadareski
8e3a0f77e9 Be consistent about end-of-file newlines 2025-07-24 08:41:37 -04:00
Matt Nadareski
40cfa78be4 Add .NET Standard 2.0 and 2.1 2025-07-24 08:36:34 -04:00
Matt Nadareski
4d92c7cd23 Update nuget packages 2025-07-24 08:34:59 -04:00
Matt Nadareski
acf1e3ec71 Reduce target frameworks for test project 2025-02-25 21:28:49 -05:00
Matt Nadareski
10027f78e3 Fix how conditions are used for references 2025-02-25 21:24:38 -05:00
Matt Nadareski
187932b091 Bump version 2025-01-06 09:58:33 -05:00
Matt Nadareski
89dbe0460f Simplify apparent usings in wrapper class 2025-01-06 00:53:27 -05:00
Matt Nadareski
365ee9019f Use expression bodies for properties 2025-01-06 00:46:12 -05:00
Matt Nadareski
e117892f37 Fix modern .NET builds 2025-01-06 00:40:11 -05:00
Matt Nadareski
1e11e9abb8 Reduce complexity of CurrentHash properties 2025-01-06 00:38:37 -05:00
Matt Nadareski
1d2985023d Remove now-obsolete remark 2025-01-06 00:29:40 -05:00
Matt Nadareski
cfddb3dab4 Maintain consistency between supported structures 2025-01-06 00:15:11 -05:00
Matt Nadareski
08512abc59 Maintain consistency between supported structures 2025-01-06 00:12:32 -05:00
Matt Nadareski
71a330cf68 Better HashTool documentation 2025-01-06 00:00:30 -05:00
Matt Nadareski
ad8d119905 Fix stream hash and size signatures 2025-01-05 23:56:05 -05:00
Matt Nadareski
c82a6dc39b Add stream GetStandardHashes variant 2025-01-05 23:39:00 -05:00
Matt Nadareski
414759cbd2 Without size variants are all thin wrappers 2025-01-05 23:33:29 -05:00
Matt Nadareski
142ca6f327 Replace FileInfo calls 2025-01-05 23:28:50 -05:00
Matt Nadareski
8dee2e2501 Add tests around length additions 2025-01-05 23:10:50 -05:00
Matt Nadareski
240098dd03 Create calculate-length-on-read HashTool helpers 2025-01-05 23:04:41 -05:00
Matt Nadareski
15a022eca5 Reduce unnecessary complexity 2025-01-02 22:43:41 -05:00
Matt Nadareski
0ede92a5d9 Fix SSDEEP URL 2025-01-02 22:25:17 -05:00
Matt Nadareski
0c3815e17c Replace SpamSum implementation with more complete one 2025-01-02 22:21:26 -05:00
Matt Nadareski
8f5bff0375 Add extremely basic SpamSum implementation 2025-01-02 20:02:08 -05:00
Matt Nadareski
dc3cb0be5d Simplify namespace usage 2025-01-02 16:00:56 -05:00
Matt Nadareski
f7346b20e1 Simplify namespace usage 2025-01-02 15:53:51 -05:00
Matt Nadareski
f971fcf5c8 Add HashSize property for all implementations 2025-01-02 15:37:20 -05:00
Matt Nadareski
4e0da77cb4 Message digests are cryptographic hashes 2025-01-02 15:29:06 -05:00
Matt Nadareski
7776112ec6 xxHash are non-cryptographic hashes 2025-01-02 15:23:13 -05:00
Matt Nadareski
c65184689d FNV are non-cryptographic hashes 2025-01-02 15:15:53 -05:00
Matt Nadareski
704e08b5ed Make xxHash 32/64 implement HashAlgorithm 2025-01-02 15:08:32 -05:00
Matt Nadareski
99f770ce81 Make checksums implement HashAlgorithm 2025-01-02 15:03:33 -05:00
Matt Nadareski
e5fea69815 Rename checksum methods based on HashAlgorithm 2025-01-02 14:35:40 -05:00
Matt Nadareski
80448302e8 Make message digests implement HashAlgorithm 2025-01-02 13:58:36 -05:00
Matt Nadareski
434a10d3db Update copyright 2024-12-30 21:22:58 -05:00
Matt Nadareski
4ea5f95b5e Remove unnecessary action step 2024-12-30 21:22:45 -05:00
Matt Nadareski
381dffccf9 Ensure .NET versions are installed for testing 2024-12-19 10:51:03 -05:00
Matt Nadareski
d4885d389d Ensure .NET versions are installed for testing 2024-12-19 10:48:52 -05:00
Matt Nadareski
f0adc62394 Bump version 2024-12-16 14:03:53 -05:00
Matt Nadareski
d7790ac4e1 Allow symbols to be packed 2024-12-16 14:01:58 -05:00
Matt Nadareski
70b145c633 Use publish script and update README 2024-12-06 11:06:58 -05:00
Matt Nadareski
4e9d7fc927 Framework only matters for executable 2024-11-15 20:49:38 -05:00
Matt Nadareski
ba7a1cd8b7 Bump version 2024-11-13 02:00:32 -05:00
Matt Nadareski
165bbdfd72 Add .NET 9 to target frameworks 2024-11-13 02:00:18 -05:00
Matt Nadareski
4a9fc1a144 Bump version 2024-11-12 12:15:51 -05:00
Matt Nadareski
563d293f4b Add overarching CRC region 2024-11-11 21:36:04 -05:00
Matt Nadareski
39c2451354 Reduce FNV code for simplicity 2024-11-11 20:51:37 -05:00
Matt Nadareski
b8ec4ac9c4 Make FnvBase public 2024-11-11 04:04:02 -05:00
Matt Nadareski
adc918ea8a Make FNV public 2024-11-11 04:00:56 -05:00
Matt Nadareski
186f8a1ece Add FNV variants 2024-11-11 04:00:46 -05:00
Matt Nadareski
d8cb2e2955 Turn some things into auto-fields for clarity 2024-11-11 02:29:35 -05:00
Matt Nadareski
83f008919c Generalize Fletcher base class for all checksums 2024-11-11 01:57:08 -05:00
Matt Nadareski
72a98e3e03 No-reflect CRC-32 made more efficient 2024-11-11 01:32:57 -05:00
Matt Nadareski
32fe421af4 CRC below 64 can be optimized more 2024-11-11 01:09:23 -05:00
Matt Nadareski
3382c20217 Add MD4 efficient implementation 2024-11-10 23:32:33 -05:00
Matt Nadareski
6700f603f2 Fix efficient MD2 2024-11-10 22:43:38 -05:00
Matt Nadareski
e1c1c8322d Fix missing method from Framework 2024-11-10 22:29:17 -05:00
Matt Nadareski
7b9580c991 Add MD2 to the readme 2024-11-10 22:24:10 -05:00
Matt Nadareski
75e536df4f Create more efficient MD2 implementation 2024-11-10 22:23:46 -05:00
Matt Nadareski
3e18ddce9f Create inefficient MD2 implementation 2024-11-10 21:36:38 -05:00
Matt Nadareski
f4d5e88f0a Fix issue with non-length streams 2024-11-10 20:43:11 -05:00
Matt Nadareski
a5f7e7d91d Shortcut on 0-byte inputs 2024-11-10 20:38:39 -05:00
Matt Nadareski
2e3e16e8ae Add zero byte hash byte arrays 2024-11-10 20:36:30 -05:00
Matt Nadareski
8fa100eb89 Add zero byte hash strings 2024-11-10 19:57:37 -05:00
Matt Nadareski
bf1cfa0e1f Add performance note 2024-11-09 23:45:59 -05:00
Matt Nadareski
4e86e0ef86 Remove now-unused Aaru.Checksums pieces 2024-11-09 23:18:45 -05:00
Matt Nadareski
d57396612f Add Fletcher family checksums 2024-11-09 23:14:31 -05:00
Matt Nadareski
1b06751c68 Move helper to main utility class 2024-11-09 22:06:46 -05:00
Matt Nadareski
89582a56ac Move things to Checksum namespace 2024-11-09 22:03:32 -05:00
Matt Nadareski
ac1cacc247 Add Adler-32 implementation 2024-11-09 22:01:07 -05:00
Matt Nadareski
27276ce05d Fix CRC note 2024-11-09 21:34:41 -05:00
Matt Nadareski
841f5708a3 Update README 2024-11-09 21:32:13 -05:00
Matt Nadareski
6df184fa4e Add Tiger2 variants (0x80 pad start) 2024-11-09 21:32:02 -05:00
Matt Nadareski
d9cf9fd3b2 Use new message digest base class 2024-11-09 21:12:02 -05:00
Matt Nadareski
21b49921ac Create message digest base class 2024-11-09 20:54:58 -05:00
Matt Nadareski
d1b60f7951 Move message digests to new namespace 2024-11-09 20:51:38 -05:00
Matt Nadareski
bb9d4155d2 Add Tiger family hashes 2024-11-09 20:46:05 -05:00
Matt Nadareski
5b66eaf253 Make RIPEMD implementations public 2024-11-09 03:11:35 -05:00
Matt Nadareski
7c4d6a6862 Create and use new HashOperations helper class 2024-11-09 03:11:01 -05:00
Matt Nadareski
79c10cf2fb Add RIPEMD-256 implementation 2024-11-09 02:59:17 -05:00
Matt Nadareski
ffc6bc045d Add RIPEMD-320 implementation 2024-11-09 02:54:04 -05:00
Matt Nadareski
7a43f6c0de Add region in HashType enum for RIPEMD 2024-11-09 02:35:50 -05:00
Matt Nadareski
d096cbf07e Add RIPEMD-128 implementation 2024-11-09 02:33:51 -05:00
Matt Nadareski
bb67c3e2f3 Migrate to internal RIPEMD-160 implementation 2024-11-09 01:18:52 -05:00
Matt Nadareski
f2e5033bb4 Simplify the hash assembly 2024-11-09 01:15:10 -05:00
Matt Nadareski
0f7d373751 Fix RIPEMD-160 hashing 2024-11-09 01:13:46 -05:00
Matt Nadareski
8231ab18a6 Fix order of operations 2024-11-09 01:03:40 -05:00
Matt Nadareski
bd8055b7d5 Rename vars for easier debugging 2024-11-09 00:36:42 -05:00
Matt Nadareski
bd0f76ef08 Consolidate the hash pieces into an array 2024-11-09 00:32:25 -05:00
Matt Nadareski
70e79a68eb Fix little-endian read, again 2024-11-09 00:26:41 -05:00
Matt Nadareski
a087abf3d3 Fix a logic bug (nw) 2024-11-08 23:24:50 -05:00
Matt Nadareski
bd363ca1ec Rename some things to make easier debugging 2024-11-08 23:13:19 -05:00
Matt Nadareski
e4a53f3d62 Minor cleanup (nw) 2024-11-08 21:48:30 -05:00
Matt Nadareski
1401775c15 Unroll main loop 2024-11-08 21:19:33 -05:00
Matt Nadareski
a3ba52adee Split RoundOperation to prepare for flattening 2024-11-08 20:43:49 -05:00
Matt Nadareski
544d6f1cc8 Fix infinite loop bug 2024-11-08 20:31:52 -05:00
Matt Nadareski
62da665c07 Preemptively wire up support for RIPEMD-160 2024-11-08 20:13:14 -05:00
Matt Nadareski
8480ec8d92 Add majority of RIPEMD-160 implementation 2024-11-08 20:10:45 -05:00
Matt Nadareski
c763d402d9 Add RIPEMD constants 2024-11-08 16:11:03 -05:00
Matt Nadareski
7c090b76c0 Make XXH32 and XXH64 implementations public 2024-11-08 15:53:36 -05:00
Matt Nadareski
2be7850b9e Update states to be more like XXH32/64 2024-11-08 14:33:34 -05:00
Matt Nadareski
611a0934ae Add more XXH3 utilities 2024-11-08 14:08:16 -05:00
Matt Nadareski
16826f4c8b Add more XXH3 utilities 2024-11-08 13:47:03 -05:00
Matt Nadareski
4732de1268 Add XXH3 utilities 2024-11-08 13:27:05 -05:00
Matt Nadareski
f74c9ddffd Use internal implementation for XXH64 2024-11-08 13:11:58 -05:00
Matt Nadareski
58f2475099 Fix LE64 bug 2024-11-08 13:09:32 -05:00
Matt Nadareski
1d1fe196cf Minor cleanup (nw) 2024-11-08 12:57:58 -05:00
Matt Nadareski
2af987bb1d Prep the hash wrapper for new XXH64 2024-11-08 12:48:05 -05:00
Matt Nadareski
effb2f9db6 Clean up XXH64 2024-11-08 12:46:31 -05:00
Matt Nadareski
b728aa77c7 Use internal implementation for XXH32 2024-11-08 12:33:43 -05:00
Matt Nadareski
fefdcd72a3 Fix endian reads 2024-11-08 12:30:22 -05:00
Matt Nadareski
5d25a017eb Use Array.Clear instead of a loop 2024-11-08 11:14:00 -05:00
Matt Nadareski
c0643e3bca Just make this a bool 2024-11-08 10:35:27 -05:00
Matt Nadareski
65a57f6c60 Slight tweaks to XXH32 (nw) 2024-11-08 01:05:22 -05:00
Matt Nadareski
9c27523612 xxHash aren't reversed 2024-11-08 00:54:22 -05:00
Matt Nadareski
5ed7ad7802 Rename accumulator so I don't keep losing track 2024-11-08 00:28:51 -05:00
Matt Nadareski
41be02c57d Fix issue in XXH32 updating 2024-11-08 00:23:09 -05:00
Matt Nadareski
0ec9c1f91d Preemptively add wiring in HashWrapper for xxHash 2024-11-07 23:44:06 -05:00
Matt Nadareski
de8e510f71 Reserved isn't used, so remove it 2024-11-07 23:34:42 -05:00
Matt Nadareski
82f051354f Start cleaning up XXH32 code 2024-11-07 23:29:25 -05:00
Matt Nadareski
7559ba2edc Add CRC-1 (parity bit) 2024-11-07 22:25:48 -05:00
Matt Nadareski
4a408ded7e Add xxHash32 hasher class (nw) 2024-11-07 22:15:25 -05:00
Matt Nadareski
3469d424af Rename TransformBlock to Update 2024-11-07 22:00:29 -05:00
Matt Nadareski
3fa04bba65 Add most XXH64 code 2024-11-07 21:53:07 -05:00
Matt Nadareski
f135693c7e Add most XXH32 code 2024-11-07 21:18:13 -05:00
Matt Nadareski
0d6806cf59 Add 128-bit hash struct 2024-11-07 20:04:37 -05:00
Matt Nadareski
4dde900195 Split XXH3State 2024-11-07 20:02:59 -05:00
Matt Nadareski
a383bb39a6 Add skeletons and TODOs to states 2024-11-07 17:06:57 -05:00
Matt Nadareski
92554705cc Add xxHash state classes 2024-11-07 16:40:33 -05:00
Matt Nadareski
c5e4cb1495 Add xxHash constants and enums 2024-11-07 16:20:43 -05:00
Matt Nadareski
9bb8a07c32 Public CrcRunner and related 2024-11-07 15:26:10 -05:00
Matt Nadareski
7878591107 Add CRC-3/4/5/6/7 implementations 2024-11-07 15:18:18 -05:00
Matt Nadareski
6f536b8e2a Add CRC-8 implementations 2024-11-07 14:54:44 -05:00
Matt Nadareski
dee69d1d88 Enable optimization for all reflected checksums 2024-11-07 14:30:12 -05:00
Matt Nadareski
0e8694cc90 Add CRC-10/11/12/13/14/15 implementations 2024-11-07 14:28:08 -05:00
Matt Nadareski
a7f8e0664a Fix reflecting initial value 2024-11-07 13:56:56 -05:00
Matt Nadareski
b1e4546697 Slight tweaks to table generation 2024-11-07 13:28:56 -05:00
Matt Nadareski
51d1a81e08 Add CRC-24 reflected to optimized list 2024-11-07 12:56:18 -05:00
Matt Nadareski
1a941b44fc Fix and reenable CRC-17 2024-11-07 12:49:33 -05:00
Matt Nadareski
ea601eed8d Fix CRC-17 definition 2024-11-07 12:35:13 -05:00
Matt Nadareski
c1a9e007c5 Make test more maintainable 2024-11-07 12:24:12 -05:00
Matt Nadareski
fb83427c91 Add CRC-17 and CRC-21 implementations 2024-11-07 03:36:34 -05:00
Matt Nadareski
57f9aa9133 Add CRC-30 and CRC-31 implementations 2024-11-07 03:13:05 -05:00
Matt Nadareski
dbcb654f8a Add name field for CRC definitions 2024-11-07 03:05:06 -05:00
Matt Nadareski
16d3472fc6 Consolidate cases in fast transform 2024-11-07 02:29:51 -05:00
Matt Nadareski
aced21c9f0 16/32/64 reflect all can share optimization 2024-11-07 02:15:07 -05:00
Matt Nadareski
2a81a65f99 Add CRC-64 reflect 4-byte optimized 2024-11-07 02:01:02 -05:00
Matt Nadareski
9819a5975a Extend no-reflect to 8-bytes 2024-11-07 01:44:03 -05:00
Matt Nadareski
e36cd9bf3c Add fast no-reflect transform implementation 2024-11-07 01:40:05 -05:00
Matt Nadareski
4eec52241e Region up HashType for readability 2024-11-06 22:01:27 -05:00
104 changed files with 12630 additions and 5103 deletions

167
.editorconfig Normal file
View File

@@ -0,0 +1,167 @@
# top-most EditorConfig file
root = true
# C# files
[*.cs]
# Indentation and spacing
charset = utf-8
indent_size = 4
indent_style = space
tab_width = 4
trim_trailing_whitespace = true
# New line preferences
end_of_line = lf
insert_final_newline = true
max_line_length = unset
# using directive preferences
csharp_using_directive_placement = outside_namespace
dotnet_diagnostic.IDE0005.severity = error
# Code-block preferences
csharp_style_namespace_declarations = block_scoped
csharp_style_prefer_method_group_conversion = true
csharp_style_prefer_top_level_statements = false
# Expression-level preferences
csharp_prefer_simple_default_expression = true
csharp_style_inlined_variable_declaration = true
csharp_style_unused_value_assignment_preference = discard_variable
csharp_style_unused_value_expression_statement_preference = discard_variable
dotnet_diagnostic.IDE0001.severity = warning
dotnet_diagnostic.IDE0002.severity = warning
dotnet_diagnostic.IDE0004.severity = warning
dotnet_diagnostic.IDE0010.severity = error
dotnet_diagnostic.IDE0051.severity = warning
dotnet_diagnostic.IDE0052.severity = warning
dotnet_diagnostic.IDE0072.severity = warning
dotnet_diagnostic.IDE0080.severity = warning
dotnet_diagnostic.IDE0100.severity = error
dotnet_diagnostic.IDE0110.severity = error
dotnet_diagnostic.IDE0120.severity = warning
dotnet_diagnostic.IDE0121.severity = warning
dotnet_diagnostic.IDE0240.severity = error
dotnet_diagnostic.IDE0241.severity = error
dotnet_style_coalesce_expression = true
dotnet_style_namespace_match_folder = false
dotnet_style_null_propagation = true
dotnet_style_prefer_auto_properties = true
dotnet_style_prefer_collection_expression = when_types_loosely_match
dotnet_style_prefer_is_null_check_over_reference_equality_method = true
dotnet_style_prefer_compound_assignment = true
csharp_style_prefer_simple_property_accessors = true
dotnet_style_prefer_simplified_interpolation = true
dotnet_style_prefer_simplified_boolean_expressions = true
csharp_style_prefer_unbound_generic_type_in_nameof = true
# Field preferences
dotnet_diagnostic.IDE0044.severity = warning
dotnet_style_readonly_field = true
# Language keyword vs. framework types preferences
dotnet_diagnostic.IDE0049.severity = error
dotnet_style_predefined_type_for_locals_parameters_members = true
dotnet_style_predefined_type_for_member_access = true
# Modifier preferences
csharp_prefer_static_local_function = true
csharp_style_prefer_readonly_struct = true
dotnet_diagnostic.IDE0036.severity = warning
dotnet_diagnostic.IDE0040.severity = error
dotnet_diagnostic.IDE0380.severity = error
dotnet_style_require_accessibility_modifiers = always
# New-line preferences
dotnet_diagnostic.IDE2000.severity = warning
dotnet_diagnostic.IDE2002.severity = warning
dotnet_diagnostic.IDE2003.severity = warning
dotnet_diagnostic.IDE2004.severity = warning
dotnet_diagnostic.IDE2005.severity = warning
dotnet_diagnostic.IDE2006.severity = warning
csharp_style_allow_blank_line_after_colon_in_constructor_initializer_experimental = false
csharp_style_allow_blank_line_after_token_in_arrow_expression_clause_experimental = false
csharp_style_allow_blank_line_after_token_in_conditional_expression_experimental = false
csharp_style_allow_blank_lines_between_consecutive_braces_experimental = false
dotnet_style_allow_multiple_blank_lines_experimental = false
dotnet_style_allow_statement_immediately_after_block_experimental = false
# Null-checking preferences
csharp_style_conditional_delegate_call = true
# Parameter preferences
dotnet_code_quality_unused_parameters = all
dotnet_diagnostic.IDE0280.severity = error
# Parentheses preferences
dotnet_diagnostic.IDE0047.severity = warning
dotnet_diagnostic.IDE0048.severity = warning
dotnet_style_parentheses_in_arithmetic_binary_operators = always_for_clarity
dotnet_style_parentheses_in_other_binary_operators = always_for_clarity
dotnet_style_parentheses_in_other_operators = always_for_clarity
dotnet_style_parentheses_in_relational_binary_operators = always_for_clarity
# Pattern-matching preferences
dotnet_diagnostic.IDE0019.severity = warning
dotnet_diagnostic.IDE0020.severity = warning
dotnet_diagnostic.IDE0038.severity = warning
dotnet_diagnostic.IDE0066.severity = none
dotnet_diagnostic.IDE0083.severity = warning
dotnet_diagnostic.IDE0260.severity = warning
csharp_style_pattern_matching_over_as_with_null_check = true
csharp_style_pattern_matching_over_is_with_cast_check = true
csharp_style_prefer_not_pattern = true
csharp_style_prefer_pattern_matching = true
# this. and Me. preferences
dotnet_style_qualification_for_event = false
dotnet_style_qualification_for_field = false
dotnet_style_qualification_for_method = false
dotnet_style_qualification_for_property = false
# var preferences
csharp_style_var_for_built_in_types = false
csharp_style_var_when_type_is_apparent = true
# .NET formatting options
dotnet_separate_import_directive_groups = false
dotnet_sort_system_directives_first = true
# C# formatting options
csharp_indent_block_contents = true
csharp_indent_braces = false
csharp_indent_case_contents = true
csharp_indent_case_contents_when_block = false
csharp_indent_labels = one_less_than_current
csharp_indent_switch_labels = true
csharp_new_line_before_catch = true
csharp_new_line_before_else = true
csharp_new_line_before_finally = true
csharp_new_line_before_members_in_anonymous_types = true
csharp_new_line_before_members_in_object_initializers = true
csharp_new_line_before_open_brace = all
csharp_new_line_between_query_expression_clauses = true
csharp_preserve_single_line_blocks = true
csharp_preserve_single_line_statements = true
csharp_space_after_cast = false
csharp_space_after_colon_in_inheritance_clause = true
csharp_space_after_comma = true
csharp_space_after_dot = false
csharp_space_after_keywords_in_control_flow_statements = true
csharp_space_after_semicolon_in_for_statement = true
csharp_space_around_binary_operators = before_and_after
csharp_space_around_declaration_statements = false
csharp_space_before_colon_in_inheritance_clause = true
csharp_space_before_comma = false
csharp_space_before_dot = false
csharp_space_before_open_square_brackets = false
csharp_space_before_semicolon_in_for_statement = false
csharp_space_between_empty_square_brackets = false
csharp_space_between_method_call_empty_parameter_list_parentheses = false
csharp_space_between_method_call_name_and_opening_parenthesis = false
csharp_space_between_method_call_parameter_list_parentheses = false
csharp_space_between_method_declaration_empty_parameter_list_parentheses = false
csharp_space_between_method_declaration_parameter_list_parentheses = false
csharp_space_between_parentheses = false
csharp_space_between_square_brackets = false

View File

@@ -0,0 +1,27 @@
---
name: Feature Request
about: For when you know better than me what you want
title: "[Request]"
labels: enhancement
assignees: mnadareski
---
**Before You Submit**
- Remember to try the [latest WIP build](https://github.com/SabreTools/SabreTools.Hashing/releases/tag/rolling) to see if the feature already exists.
- Check [previous issues](https://github.com/SabreTools/SabreTools.Hashing/issues) to see if any of those are related to what you're about to ask for.
If none of those apply, then continue...
**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
**Describe the solution you'd like**
A clear and concise description of what you want to happen.
**Describe alternatives you've considered**
A clear and concise description of any alternative solutions or features you've considered.
**Additional context**
Add any other context or screenshots about the feature request here.

21
.github/ISSUE_TEMPLATE/informational.md vendored Normal file
View File

@@ -0,0 +1,21 @@
---
name: Info
about: Something you need to tell me
title: "[Info]"
labels: question
assignees: mnadareski
---
**Before You Submit**
- Remember to try the [latest WIP build](https://github.com/SabreTools/SabreTools.Hashing/releases/tag/rolling) to see if the feature already exists.
- Check [previous issues](https://github.com/SabreTools/SabreTools.Hashing/issues) to see if any of those are related to what you're about to ask for.
If none of those apply, then continue...
**Is your information related to one of the checksums/hashes supported or something that isn't a bug in the code? Please describe.**
A clear and concise description of what the information is. Ex. With the latest build of Hasher, it [...]
**Additional context**
Add any other context or screenshots about the information here.

45
.github/ISSUE_TEMPLATE/issue-report.md vendored Normal file
View File

@@ -0,0 +1,45 @@
---
name: Issue Report
about: Tell me what's wrong, seriously
title: "[Problem]"
labels: bug
assignees: mnadareski
---
**Before You Submit**
- Remember to try the [latest WIP build](https://github.com/SabreTools/SabreTools.Hashing/releases/tag/rolling) to see if the issue has already been addressed.
- Check multiple inputs to help narrow down the issue
If all of those fail, then continue...
**Version**
What version are you using?
- [ ] Stable release (version here)
- [ ] WIP release (version here)
**Build**
What runtime version are you using?
- [ ] .NET 10 running on (Operating System)
**Describe the issue**
A clear and concise description of what the bug is.
**To Reproduce**
Steps to reproduce the behavior:
1. Create the '...' hasher
2. Run the hasher with '....'
3. See error
**Expected behavior**
A clear and concise description of what you expected to happen.
**Screenshots**
If applicable, add screenshots to help explain your problem.
**Additional context**
Add any other context about the problem here.

48
.github/workflows/build_and_test.yml vendored Normal file
View File

@@ -0,0 +1,48 @@
name: Build and Test
on:
push:
branches: ["main"]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v5
with:
fetch-depth: 0
- name: Setup .NET
uses: actions/setup-dotnet@v5
with:
dotnet-version: |
8.0.x
9.0.x
10.0.x
- name: Run tests
run: dotnet test
- name: Run publish script
run: ./publish-nix.sh -d
- name: Update rolling tag
run: |
git config user.name "github-actions[bot]"
git config user.email "github-actions[bot]@users.noreply.github.com"
git tag -f rolling
git push origin :refs/tags/rolling || true
git push origin rolling --force
- name: Upload to rolling
uses: ncipollo/release-action@v1.20.0
with:
allowUpdates: True
artifacts: "*.nupkg,*.snupkg,*.zip"
body: "Last built commit: ${{ github.sha }}"
name: "Rolling Release"
prerelease: True
replacesArtifacts: True
tag: "rolling"
updateOnlyUnreleased: True

View File

@@ -1,49 +0,0 @@
name: Nuget Pack
on:
push:
branches: [ "main" ]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
submodules: recursive
- name: Setup .NET
uses: actions/setup-dotnet@v4
with:
dotnet-version: 8.0.x
- name: Restore dependencies
run: dotnet restore
- name: Build library
run: dotnet build
- name: Run tests
run: dotnet test
- name: Pack
run: dotnet pack
- name: Upload build
uses: actions/upload-artifact@v4
with:
name: 'Nuget Package'
path: 'SabreTools.Hashing/bin/Release/*.nupkg'
- name: Upload to rolling
uses: ncipollo/release-action@v1.14.0
with:
allowUpdates: True
artifacts: 'SabreTools.Hashing/bin/Release/*.nupkg'
body: 'Last built commit: ${{ github.sha }}'
name: 'Rolling Release'
prerelease: True
replacesArtifacts: True
tag: "rolling"
updateOnlyUnreleased: True

View File

@@ -3,18 +3,21 @@ name: Build PR
on: [pull_request]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Setup .NET
uses: actions/setup-dotnet@v4
with:
dotnet-version: 8.0.x
- name: Build
run: dotnet build
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v5
- name: Run tests
run: dotnet test
- name: Setup .NET
uses: actions/setup-dotnet@v5
with:
dotnet-version: |
8.0.x
9.0.x
10.0.x
- name: Build
run: dotnet build
- name: Run tests
run: dotnet test

28
.vscode/launch.json vendored Normal file
View File

@@ -0,0 +1,28 @@
{
// Use IntelliSense to find out which attributes exist for C# debugging
// Use hover for the description of the existing attributes
// For further information visit https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md
"version": "0.2.0",
"configurations": [
{
"name": ".NET Core Launch",
"type": "coreclr",
"request": "launch",
"preLaunchTask": "build",
// If you have changed target frameworks, make sure to update the program path.
"program": "${workspaceFolder}/Hasher/bin/Debug/net10.0/Hasher.dll",
"args": [],
"cwd": "${workspaceFolder}",
// For more information about the 'console' field, see https://aka.ms/VSCode-CS-LaunchJson-Console
"console": "internalConsole",
"stopAtEntry": false,
"justMyCode": false
},
{
"name": ".NET Core Attach",
"type": "coreclr",
"request": "attach",
"processId": "${command:pickProcess}"
}
]
}

View File

@@ -0,0 +1,52 @@
using System;
using SabreTools.CommandLine;
using SabreTools.Hashing;
namespace Hasher.Features
{
internal sealed class ListFeature : Feature
{
#region Feature Definition
public const string DisplayName = "list";
private static readonly string[] _flags = ["--list"];
private const string _description = "List all available hashes and quit";
#endregion
public ListFeature()
: base(DisplayName, _flags, _description)
{
RequiresInputs = false;
}
/// <inheritdoc/>
/// TODO: Print all supported variants of names?
public override bool Execute()
{
Console.WriteLine("Hash Name Parameter Name ");
Console.WriteLine("--------------------------------------------------------------");
var hashTypes = (HashType[])Enum.GetValues(typeof(HashType));
foreach (var hashType in hashTypes)
{
// Derive the parameter name
string paramName = $"{hashType}";
paramName = paramName.Replace("-", string.Empty);
paramName = paramName.Replace(" ", string.Empty);
paramName = paramName.Replace("/", "_");
paramName = paramName.Replace("\\", "_");
paramName = paramName.ToLowerInvariant();
Console.WriteLine($"{hashType.GetHashName()?.PadRight(39, ' ')} {paramName}");
}
return true;
}
/// <inheritdoc/>
public override bool VerifyInputs() => true;
}
}

View File

@@ -0,0 +1,170 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using SabreTools.CommandLine;
using SabreTools.CommandLine.Inputs;
using SabreTools.Hashing;
namespace Hasher.Features
{
internal sealed class MainFeature : Feature
{
#region Feature Definition
public const string DisplayName = "main";
/// <remarks>Flags are unused</remarks>
private static readonly string[] _flags = [];
/// <remarks>Description is unused</remarks>
private const string _description = "";
#endregion
#region Inputs
private const string _debugName = "debug";
internal readonly FlagInput DebugInput = new(_debugName, ["-d", "--debug"], "Enable debug mode");
private const string _typeName = "type";
internal readonly StringListInput TypeInput = new(_typeName, ["-t", "--type"], "Select included hashes");
#endregion
public MainFeature()
: base(DisplayName, _flags, _description)
{
RequiresInputs = true;
Add(DebugInput);
Add(TypeInput);
}
/// <inheritdoc/>
public override bool Execute()
{
// Get the required variables
bool debug = GetBoolean(_debugName);
List<HashType> hashTypes = GetHashTypes(GetStringList(_typeName));
// Loop through all of the input files
for (int i = 0; i < Inputs.Count; i++)
{
string arg = Inputs[i];
PrintPathHashes(arg, hashTypes, debug);
}
return true;
}
/// <inheritdoc/>
public override bool VerifyInputs() => true;
/// <summary>
/// Derive a list of hash types from a list of strings
/// </summary>
private static List<HashType> GetHashTypes(List<string> types)
{
List<HashType> hashTypes = [];
if (types.Count == 0)
{
hashTypes.Add(HashType.CRC32);
hashTypes.Add(HashType.MD5);
hashTypes.Add(HashType.SHA1);
hashTypes.Add(HashType.SHA256);
}
else if (types.Contains("all"))
{
hashTypes = [.. (HashType[])Enum.GetValues(typeof(HashType))];
}
else
{
foreach (string typeString in types)
{
HashType? hashType = typeString.GetHashType();
if (hashType is not null && !hashTypes.Contains(hashType.Value))
hashTypes.Add(item: hashType.Value);
}
}
return hashTypes;
}
/// <summary>
/// Wrapper to print hashes for a single path
/// </summary>
/// <param name="path">File or directory path</param>
/// <param name="hashTypes">Set of hashes to retrieve</param>
/// <param name="debug">Enable debug output</param>
private static void PrintPathHashes(string path, List<HashType> hashTypes, bool debug)
{
Console.WriteLine($"Checking possible path: {path}");
// Check if the file or directory exists
if (File.Exists(path))
{
PrintFileHashes(path, hashTypes, debug);
}
else if (Directory.Exists(path))
{
foreach (string file in Directory.GetFiles(path, "*", SearchOption.AllDirectories))
{
PrintFileHashes(file, hashTypes, debug);
}
}
else
{
Console.WriteLine($"{path} does not exist, skipping...");
}
}
/// <summary>
/// Print information for a single file, if possible
/// </summary>
/// <param name="file">File path</param>
/// <param name="hashTypes">Set of hashes to retrieve</param>
/// <param name="debug">Enable debug output</param>
private static void PrintFileHashes(string file, List<HashType> hashTypes, bool debug)
{
Console.WriteLine($"Attempting to hash {file}, this may take a while...");
Console.WriteLine();
// If the file doesn't exist
if (!File.Exists(file))
{
Console.WriteLine($"{file} does not exist, skipping...");
return;
}
try
{
// Get all file hashes for flexibility
var hashes = HashTool.GetFileHashes(file);
if (hashes is null)
{
if (debug) Console.WriteLine($"Hashes for {file} could not be retrieved");
return;
}
// Output subset of available hashes
var builder = new StringBuilder();
foreach (HashType hashType in hashTypes)
{
// TODO: Make helper to pretty-print hash type names
if (hashes.TryGetValue(hashType, out string? hash) && hash is not null)
builder.AppendLine($"{hashType}: {hash}");
}
// Create and print the output data
string hashData = builder.ToString();
Console.WriteLine(hashData);
}
catch (Exception ex)
{
Console.WriteLine(debug ? ex : "[Exception opening file, please try again]");
return;
}
}
}
}

37
Hasher/Hasher.csproj Normal file
View File

@@ -0,0 +1,37 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>net20;net35;net40;net452;net462;net472;net48;netcoreapp3.1;net5.0;net6.0;net7.0;net8.0;net9.0;net10.0</TargetFrameworks>
<OutputType>Exe</OutputType>
<CheckEolTargetFramework>false</CheckEolTargetFramework>
<IncludeNativeLibrariesForSelfExtract>true</IncludeNativeLibrariesForSelfExtract>
<IncludeSourceRevisionInInformationalVersion>false</IncludeSourceRevisionInInformationalVersion>
<LangVersion>latest</LangVersion>
<Nullable>enable</Nullable>
<SuppressTfmSupportBuildWarnings>true</SuppressTfmSupportBuildWarnings>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<Version>1.6.0</Version>
</PropertyGroup>
<!-- Support All Frameworks -->
<PropertyGroup Condition="$(TargetFramework.StartsWith(`net2`)) OR $(TargetFramework.StartsWith(`net3`)) OR $(TargetFramework.StartsWith(`net4`))">
<RuntimeIdentifiers>win-x86;win-x64</RuntimeIdentifiers>
</PropertyGroup>
<PropertyGroup Condition="$(TargetFramework.StartsWith(`netcoreapp`)) OR $(TargetFramework.StartsWith(`net5`))">
<RuntimeIdentifiers>win-x86;win-x64;win-arm64;linux-x64;linux-arm64;osx-x64</RuntimeIdentifiers>
</PropertyGroup>
<PropertyGroup Condition="$(TargetFramework.StartsWith(`net6`)) OR $(TargetFramework.StartsWith(`net7`)) OR $(TargetFramework.StartsWith(`net8`)) OR $(TargetFramework.StartsWith(`net9`)) OR $(TargetFramework.StartsWith(`net10`))">
<RuntimeIdentifiers>win-x86;win-x64;win-arm64;linux-x64;linux-arm64;osx-x64;osx-arm64</RuntimeIdentifiers>
</PropertyGroup>
<PropertyGroup Condition="$(RuntimeIdentifier.StartsWith(`osx-arm`))">
<TargetFrameworks>net6.0;net7.0;net8.0;net9.0;net10.0</TargetFrameworks>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\SabreTools.Hashing\SabreTools.Hashing.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="SabreTools.CommandLine" Version="[1.4.0]" />
</ItemGroup>
</Project>

87
Hasher/Program.cs Normal file
View File

@@ -0,0 +1,87 @@
using System;
using System.Collections.Generic;
using Hasher.Features;
using SabreTools.CommandLine;
using SabreTools.CommandLine.Features;
namespace Hasher
{
public static class Program
{
public static void Main(string[] args)
{
// Create the command set
var mainFeature = new MainFeature();
var commandSet = CreateCommands(mainFeature);
// If we have no args, show the help and quit
if (args is null || args.Length == 0)
{
commandSet.OutputAllHelp();
return;
}
// Cache the first argument and starting index
string featureName = args[0];
// Try processing the standalone arguments
var topLevel = commandSet.GetTopLevel(featureName);
switch (topLevel)
{
// Standalone Options
case Help help: help.ProcessArgs(args, 0, commandSet); return;
case ListFeature lf: lf.Execute(); return;
// Default Behavior
default:
if (!mainFeature.ProcessArgs(args, 0))
{
commandSet.OutputAllHelp();
return;
}
else if (!mainFeature.VerifyInputs())
{
Console.Error.WriteLine("At least one input is required");
commandSet.OutputAllHelp();
return;
}
mainFeature.Execute();
break;
}
}
/// <summary>
/// Create the command set for the program
/// </summary>
private static CommandSet CreateCommands(MainFeature mainFeature)
{
List<string> header = [
"File Hashing Program",
string.Empty,
"Hasher <options> file|directory ...",
string.Empty,
];
List<string> footer = [
string.Empty,
"If no hash types are provided, this tool will default to",
"outputting CRC-32, MD5, SHA-1, and SHA-256.",
"Optionally, all supported hashes can be output by",
"specifying a value of 'all'.",
];
var commandSet = new CommandSet(header, footer);
// Standalone Options
commandSet.Add(new Help(["-?", "-h", "--help"]));
commandSet.Add(new ListFeature());
// Hasher Options
commandSet.Add(mainFeature.DebugInput);
commandSet.Add(mainFeature.TypeInput);
return commandSet;
}
}
}

7
LICENSE Normal file
View File

@@ -0,0 +1,7 @@
Copyright (c) 2018-2025 Matt Nadareski
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice (including the next paragraph) shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@@ -1,12 +1,60 @@
# SabreTools.Hashing
This library comprises of methods and helpers to simplify the process of getting checksums and hashes from both files and streams. See the following table for information about where each of the various components comes from:
[![Build and Test](https://github.com/SabreTools/SabreTools.Hashing/actions/workflows/build_and_test.yml/badge.svg)](https://github.com/SabreTools/SabreTools.Hashing/actions/workflows/build_and_test.yml)
This library comprises of methods and helpers to simplify the process of getting checksums and hashes from both files and streams.
Find the link to the Nuget package [here](https://www.nuget.org/packages/SabreTools.Hashing).
## Releases
For the most recent stable build, download the latest release here: [Releases Page](https://github.com/SabreTools/SabreTools.Hashing/releases)
For the latest WIP build here: [Rolling Release](https://github.com/SabreTools/SabreTools.Hashing/releases/rolling)
## Hasher
**Hasher** is a reference implementation for hashing and checksumming features of the library, packaged as a standalone executable for all supported platforms. It will attempt to select the correct hashing types based on input and then print the calculated values to standard output.
```text
Hasher <options> file|directory ...
Available options:
-?, -h, --help Show this help
--list List all available hashes and quit
-d, --debug Enable debug mode
-t=, --type= Select included hashes
If no hash types are provided, this tool will default to
outputting CRC-32, MD5, SHA-1, and SHA-256.
Optionally, all supported hashes can be output by
specifying a value of 'all'.
```
## Internal Implementations
All hash and checksum types here have been written to ensure compatibility across all .NET versions. Some may have been adapted to ensure this compatibility. These can be treated as reference implementations, not always optimized.
| Hash / Checksum Type | Notes |
| --- | --- |
| Adler-32 | Based on the [zlib source code](https://github.com/madler/zlib/blob/v1.2.11/adler32.c) |
| CRC | All CRC values documented [here](https://reveng.sourceforge.io/crc-catalogue/all.htm) except for CRC-82 due to bit-length restrictions |
| Fletcher | 16-, 32-, and 64-bit variants |
| FNV | 32-, and 64-bit variants; 0, 1, and 1a algorithms |
| Message Digest | MD2 and MD4 only |
| RIPEMD | 128-, 160-, 256-, and 320-bit variants |
| SpamSum | Based on the [SSDEEP source code](https://github.com/ssdeep-project/ssdeep/blob/master/fuzzy.c) |
| Tiger | 128-, 160-, and 192-bit variants; 3- and 4-pass; `0x01` and `0x80` (Tiger2) pad-initialized |
| xxHash | xxHash-32 and xxHash-64 only |
## External Implementations
External implementations of hash and checksum types may not be compatible with all .NET versions. Please see the table below for more information about support.
| Source | Hash / Checksum Types | Notes |
| --- | --- | --- |
| [Aaru.Checksums](https://github.com/aaru-dps/Aaru.Checksums) | Adler-32, Fletcher-16, Fletcher-32, SpamSum | Some code tweaks made to support older .NET versions |
| [Blake3.NET](https://github.com/xoofx/Blake3.NET) | BLAKE3 | Used in `net7.0` and above |
| [System.IO.Hashing](https://www.nuget.org/packages/System.IO.Hashing) | xxHash32, xxHash64, XXH3, XXH128 | Used in `net462` and above |
| [System.Security.Cryptography](https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography) | MD5, RIPEMD160 (.NET Framework only), SHA-1, SHA-256, SHA-384, SHA-512, SHA3-256, SHA3-384, SHA3-512, SHAKE128, SHAKE256 | Built-in library; SHA3-256, SHA3-384, SHA3-512, SHAKE128, and SHAKE256 are `net8.0` and above only for [supported platforms](https://learn.microsoft.com/en-us/dotnet/standard/security/cross-platform-cryptography) |
| [System.IO.Hashing](https://www.nuget.org/packages/System.IO.Hashing) | XXH3, XXH128 | Used in `net462` and above |
| [System.Security.Cryptography](https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography) | MD5, SHA-1, SHA-256, SHA-384, SHA-512, SHA3-256, SHA3-384, SHA3-512, SHAKE128, SHAKE256 | Built-in library; SHA3-256, SHA3-384, SHA3-512, SHAKE128, and SHAKE256 are `net8.0` and above only for [supported platforms](https://learn.microsoft.com/en-us/dotnet/standard/security/cross-platform-cryptography) |
Find the link to the Nuget package [here](https://www.nuget.org/packages/SabreTools.Hashing).
**Note:** If all you care about is performance, I encourage you to forego this library and use the ones listed above directly instead.

View File

@@ -29,7 +29,8 @@ namespace SabreTools.Hashing.Test
public void GetSingleGzipStreamHashesTest()
{
var gzipStream = new GZipStream(File.OpenRead(_singleGzipFilePath), CompressionMode.Decompress);
var hashDict = HashTool.GetStreamHashes(gzipStream);
var hashDict = HashTool.GetStreamHashesAndSize(gzipStream, out long actualSize);
TestHelper.ValidateSize(actualSize);
TestHelper.ValidateHashes(hashDict);
}
@@ -38,7 +39,8 @@ namespace SabreTools.Hashing.Test
{
var zipFile = ZipFile.OpenRead(_singleZipFilePath);
var fileStream = zipFile.Entries[0].Open();
var hashDict = HashTool.GetStreamHashes(fileStream);
var hashDict = HashTool.GetStreamHashesAndSize(fileStream, out long actualSize);
TestHelper.ValidateSize(actualSize);
TestHelper.ValidateHashes(hashDict);
}
@@ -50,9 +52,10 @@ namespace SabreTools.Hashing.Test
for (int i = 0; i < zipFile.Entries.Count; i++)
{
var fileStream = zipFile.Entries[i].Open();
var hashDict = HashTool.GetStreamHashes(fileStream);
var hashDict = HashTool.GetStreamHashesAndSize(fileStream, out long actualSize);
TestHelper.ValidateSize(actualSize);
TestHelper.ValidateHashes(hashDict);
}
}
}
}
}

View File

@@ -12,39 +12,82 @@ namespace SabreTools.Hashing.Test
private static readonly string _hashFilePath
= Path.Combine(Environment.CurrentDirectory, "TestData", "file-to-hash.bin");
#region Known File Information
/// <summary>
/// Get an array of all hash types
/// </summary>
public static TheoryData<HashType> AllHashTypes
{
get
{
var values = Enum.GetValues<HashType>();
var set = new TheoryData<HashType>();
foreach (var value in values)
{
set.Add(value);
}
private const long _hashFileSize = 125;
private const string _crc32 = "ba02a660";
private const string _md5 = "b722871eaa950016296184d026c5dec9";
private const string _sha1 = "eea1ee2d801d830c4bdad4df3c8da6f9f52d1a9f";
#endregion
return set;
}
}
[Fact]
public void GetStandardHashesTest()
public void GetStandardHashesFileTest()
{
bool gotHashes = HashTool.GetStandardHashes(_hashFilePath, out long actualSize, out string? crc32, out string? md5, out string? sha1);
Assert.True(gotHashes);
Assert.Equal(_hashFileSize, actualSize);
Assert.Equal(_crc32, crc32);
Assert.Equal(_md5, md5);
Assert.Equal(_sha1, sha1);
TestHelper.ValidateSize(actualSize);
TestHelper.ValidateHash(HashType.CRC32, crc32);
TestHelper.ValidateHash(HashType.MD5, md5);
TestHelper.ValidateHash(HashType.SHA1, sha1);
}
[Fact]
public void GetFileHashesTest()
public void GetStandardHashesArrayTest()
{
byte[] fileBytes = File.ReadAllBytes(_hashFilePath);
bool gotHashes = HashTool.GetStandardHashes(fileBytes, out long actualSize, out string? crc32, out string? md5, out string? sha1);
Assert.True(gotHashes);
TestHelper.ValidateSize(actualSize);
TestHelper.ValidateHash(HashType.CRC32, crc32);
TestHelper.ValidateHash(HashType.MD5, md5);
TestHelper.ValidateHash(HashType.SHA1, sha1);
}
[Fact]
public void GetStandardHashesStreamTest()
{
var fileStream = File.OpenRead(_hashFilePath);
bool gotHashes = HashTool.GetStandardHashes(fileStream, out long actualSize, out string? crc32, out string? md5, out string? sha1);
Assert.True(gotHashes);
TestHelper.ValidateSize(actualSize);
TestHelper.ValidateHash(HashType.CRC32, crc32);
TestHelper.ValidateHash(HashType.MD5, md5);
TestHelper.ValidateHash(HashType.SHA1, sha1);
}
[Fact]
public void GetFileHashesParallelTest()
{
var hashDict = HashTool.GetFileHashes(_hashFilePath);
TestHelper.ValidateHashes(hashDict);
}
[Theory]
[MemberData(nameof(AllHashTypes))]
public void GetFileHashesSerialTest(HashType hashType)
{
var hashValue = HashTool.GetFileHash(_hashFilePath, hashType);
TestHelper.ValidateHash(hashType, hashValue);
}
[Fact]
public void GetFileHashesAndSizeTest()
{
var hashDict = HashTool.GetFileHashesAndSize(_hashFilePath, out long actualSize);
Assert.Equal(_hashFileSize, actualSize);
TestHelper.ValidateSize(actualSize);
TestHelper.ValidateHashes(hashDict);
}
@@ -56,6 +99,15 @@ namespace SabreTools.Hashing.Test
TestHelper.ValidateHashes(hashDict);
}
[Fact]
public void GetByteArrayHashesAndSizeTest()
{
byte[] fileBytes = File.ReadAllBytes(_hashFilePath);
var hashDict = HashTool.GetByteArrayHashesAndSize(fileBytes, out long actualSize);
TestHelper.ValidateSize(actualSize);
TestHelper.ValidateHashes(hashDict);
}
[Fact]
public void GetStreamHashesTest()
{
@@ -63,5 +115,14 @@ namespace SabreTools.Hashing.Test
var hashDict = HashTool.GetStreamHashes(fileStream);
TestHelper.ValidateHashes(hashDict);
}
[Fact]
public void GetStreamHashesAndSizeTest()
{
var fileStream = File.OpenRead(_hashFilePath);
var hashDict = HashTool.GetStreamHashesAndSize(fileStream, out long actualSize);
TestHelper.ValidateSize(actualSize);
TestHelper.ValidateHashes(hashDict);
}
}
}
}

View File

@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>net462;net472;net48;net6.0;net7.0;net8.0</TargetFrameworks>
<TargetFrameworks>net8.0;net9.0;net10.0</TargetFrameworks>
<CheckEolTargetFramework>false</CheckEolTargetFramework>
<IsPackable>false</IsPackable>
<LangVersion>latest</LangVersion>
@@ -20,14 +20,13 @@
</ItemGroup>
<ItemGroup>
<PackageReference Include="coverlet.collector" Version="6.0.2">
<PackageReference Include="coverlet.collector" Version="6.0.4">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.11.1" />
<PackageReference Include="System.IO.Compression" Version="4.3.0" />
<PackageReference Include="xunit" Version="2.9.2" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.8.2">
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="18.0.1" />
<PackageReference Include="xunit" Version="2.9.3" />
<PackageReference Include="xunit.runner.visualstudio" Version="3.1.5">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>

View File

@@ -0,0 +1,45 @@
using Xunit;
namespace SabreTools.Hashing.Test
{
public class SpamSumTests
{
[Theory]
// Invalid inputs
[InlineData(null, null, -1)]
[InlineData(null, "3:hMCPQCE6AFQxWyENFACBE+rW6Tj7SMQmKozr9MVERkL:hZRdxZENFs+rPSromekL", -1)]
[InlineData("3:hMCPQCE6AFQxWyENFACBE+rW6Tj7SMQmKozr9MVERkL:hZRdxZENFs+rPSromekL", null, -1)]
[InlineData("", "", -1)]
[InlineData("3:hMCPQCE6AFQxWyENFACBE+rW6Tj7SMQmKozr9MVERkL:hZRdxZENFs+rPSromekL", "", -1)]
[InlineData("", "3:hMCPQCE6AFQxWyENFACBE+rW6Tj7SMQmKozr9MVERkL:hZRdxZENFs+rPSromekL", -1)]
// Small data
[InlineData("6:l+lq/MtlM8pJ0gt6lXWogE61UlT1Uqj1akMD5n:l+l6Mtl/n0gtOXmEuUl5UqpakM9n", "6:mTj3qJskr+V+1o21+n0rtD2noPWKlAyjllZmMt6120EK+wlsS6T1oLwXuk4tk7:m/bk/1oQrJL3jTu20EK+wlsp5oO4tk7", 0)]
[InlineData("6:mTj3qJskr+V+1o21+n0rtD2noPWKlAyjllZmMt6120EK+wlsS6T1oLwXuk4tk7:m/bk/1oQrJL3jTu20EK+wlsp5oO4tk7", "6:l+lq/MtlM8pJ0gt6lXWogE61UlT1Uqj1akMD5n:l+l6Mtl/n0gtOXmEuUl5UqpakM9n", 0)]
[InlineData("3:hMCPQCE6AFQxWyENFACBE+rW6Tj7SMQmKozr9MVERkL:hZRdxZENFs+rPSromekL", "3:hMCERJAFQxWyENFACBE+rW6Tj7SMQmKozr9MVERkL:huRJdxZENFs+rPSromekL", 41)]
[InlineData("3:hMCERJAFQxWyENFACBE+rW6Tj7SMQmKozr9MVERkL:huRJdxZENFs+rPSromekL", "3:hMCPQCE6AFQxWyENFACBE+rW6Tj7SMQmKozr9MVERkL:hZRdxZENFs+rPSromekL", 41)]
[InlineData("12:Y+VH/3Ckg3xqMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMn:xHqVwMMMMMMMMMMMMMMMMMMMMMMMMMM0", "12:Oqkg3xqMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMu:OqVwMMMMMMMMMMMMMMMMMMMMMMMMMMMd", 44)]
[InlineData("12:Oqkg3xqMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMu:OqVwMMMMMMMMMMMMMMMMMMMMMMMMMMMd", "12:Y+VH/3Ckg3xqMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMn:xHqVwMMMMMMMMMMMMMMMMMMMMMMMMMM0", 44)]
// Large data
[InlineData("196608:Gbxf3F4OQK3IuUGM8Ylv1kqCLuDKeo5cRld6iZL6HAGpX7g08WCWDc4NNgs4NEv:qcgxU+UxR2gl5qAGpXjHDcCNgs4N", "196608:EqKRzGWxtDOadbDCbZStQxNy+fox3UgOYorlhjolL0K1WJj5lYA:EbNf76db9xNVox3MRlh+sf", 0)]
[InlineData("196608:EqKRzGWxtDOadbDCbZStQxNy+fox3UgOYorlhjolL0K1WJj5lYA:EbNf76db9xNVox3MRlh+sf", "196608:Gbxf3F4OQK3IuUGM8Ylv1kqCLuDKeo5cRld6iZL6HAGpX7g08WCWDc4NNgs4NEv:qcgxU+UxR2gl5qAGpXjHDcCNgs4N", 0)]
[InlineData("24576:p+QxhkAcV6cUdRxczoy3NmO0ne3HFVjSeQ229SVjeONr+v:YQ/q6baz5Nqe3H2eQzStBa", "24576:fCQxhkAcV6cUdRxczoyVQQFDSVRNihk24vXDj20sq:6Q/q6bazwMgRNihk24jtsq", 54)]
[InlineData("24576:fCQxhkAcV6cUdRxczoyVQQFDSVRNihk24vXDj20sq:6Q/q6bazwMgRNihk24jtsq", "24576:p+QxhkAcV6cUdRxczoy3NmO0ne3HFVjSeQ229SVjeONr+v:YQ/q6baz5Nqe3H2eQzStBa", 54)]
// Duplicate sequence truncation
[InlineData("500:AAAAAAAAAAAAAAAAAAAAAAAAyENFACBE+rW6Tj7SMQmK:4", "500:AAAyENFACBE+rW6Tj7SMQmK:4", 100)]
// Trailing data ignored
[InlineData("6:l+lq/MtlM8pJ0gt6lXWogE61UlT1Uqj1akMD5n:l+l6Mtl/n0gtOXmEuUl5UqpakM9n,ANYTHING", "6:mTj3qJskr+V+1o21+n0rtD2noPWKlAyjllZmMt6120EK+wlsS6T1oLwXuk4tk7:m/bk/1oQrJL3jTu20EK+wlsp5oO4tk7,NOTHING", 0)]
[InlineData("6:mTj3qJskr+V+1o21+n0rtD2noPWKlAyjllZmMt6120EK+wlsS6T1oLwXuk4tk7:m/bk/1oQrJL3jTu20EK+wlsp5oO4tk7,NOTHING", "6:l+lq/MtlM8pJ0gt6lXWogE61UlT1Uqj1akMD5n:l+l6Mtl/n0gtOXmEuUl5UqpakM9n,ANYTHING", 0)]
// Rolling window - larger than 7
[InlineData("500:7SMQmKa:3", "500:7SMQmKr:3", 0)]
// Rolling window - smaller than 7
[InlineData("500:7QmKa:3", "500:7QmKr:3", 0)]
// Blocksize differences
[InlineData("9287:hMCPQCE6AFQxWyENFACBE+rW6Tj7SMQmKozr9MVERkL:hZRdxZENFs+rPSromekL", "5893:hMCPQCE6AFQxWyENFACBE+rW6Tj7SMQmKozr9MVERkL:hZRdxZENFs+rPSromekL", 0)]
[InlineData("3:hMCPQCE6AFQxWyENFACBE+rW6Tj7SMQmKozr9MVERkL:hZRdxZENFs+rPSromekL", "3:hMCPQCE6AFQxWyENFACBE+rW6Tj7SMQmKozr9MVERkL:hZRdxZENFs+rPSromekL", 100)]
public void FuzzyCompareTest(string? stringOne, string? stringTwo, int expected)
{
var result = SpamSum.SpamSum.FuzzyCompare(stringOne, stringTwo);
Assert.Equal(expected, result);
}
}
}

View File

@@ -6,102 +6,218 @@ namespace SabreTools.Hashing.Test
/// <summary>
/// Helper class for tests
/// </summary>
/// CRC values confirmed with <see href="https://emn178.github.io/online-tools/crc/"/>
/// CRC values confirmed with <see href="https://emn178.github.io/online-tools/crc/"/>
internal static class TestHelper
{
#region Known File Information
private const long _hashFileSize = 125;
private const string _adler32 = "08562d95";
private static readonly Dictionary<HashType, string> _knownHashes = new()
{
{HashType.Adler32, "08562d95"},
#if NET7_0_OR_GREATER
private const string _blake3 = "d4bd7ca6f1ebea9580d9381106b248eb5b6069170d0bfd00b17d659fcd10dcdc";
{HashType.BLAKE3, "d4bd7ca6f1ebea9580d9381106b248eb5b6069170d0bfd00b17d659fcd10dcdc"},
#endif
private const string _crc16 = "7573";
private const string _crc16_arc = "7573";
private const string _crc16_cdma2000 = "8b5f";
private const string _crc16_cms = "1a37";
private const string _crc16_dds110 = "241d";
private const string _crc16_dectr = "7390";
private const string _crc16_dectx = "7391";
private const string _crc16_dnp = "4bbb";
private const string _crc16_en13757 = "e28b";
private const string _crc16_genibus = "b65d";
private const string _crc16_gsm = "482d";
private const string _crc16_ibm3740 = "49a2";
private const string _crc16_ibmsdlc = "4f52";
private const string _crc16_isoiec144433a = "85cd";
private const string _crc16_kermit = "bed2";
private const string _crc16_lj1200 = "3533";
private const string _crc16_m17 = "5223";
private const string _crc16_maximdow = "8a8c";
private const string _crc16_mcrf4xx = "b0ad";
private const string _crc16_modbus = "9e54";
private const string _crc16_nrsc5 = "4857";
private const string _crc16_opensafetya = "abcd";
private const string _crc16_opensafetyb = "76f4";
private const string _crc16_profibus = "3099";
private const string _crc16_riello = "23e0";
private const string _crc16_spifujitsu = "f98b";
private const string _crc16_t10dif = "2642";
private const string _crc16_teledisk = "7e05";
private const string _crc16_tms37157 = "dba0";
private const string _crc16_umts = "fee0";
private const string _crc16_usb = "61ab";
private const string _crc16_xmodem = "b7d2";
private const string _crc24_ble = "2969f2";
private const string _crc24_flexraya = "ce9dc7";
private const string _crc24_flexrayb = "0f49d7";
private const string _crc24_interlaken = "fb4725";
private const string _crc24_ltea = "675e55";
private const string _crc24_lteb = "c91203";
private const string _crc24_openpgp = "0c6012";
private const string _crc24_os9 = "610e21";
private const string _crc32 = "ba02a660";
private const string _crc32_aixm = "6174a75a";
private const string _crc32_autosar = "c050428e";
private const string _crc32_base91d = "e741ba25";
private const string _crc32_bzip2 = "18aa4603";
private const string _crc32_cdromedc = "b8ced467";
private const string _crc32_cksum = "f27b3c27";
private const string _crc32_iscsi = "544d37db";
private const string _crc32_isohdlc = "ba02a660";
private const string _crc32_jamcrc = "45fd599f";
private const string _crc32_mef = "d9d98444";
private const string _crc32_mpeg2 = "e755b9fc";
private const string _crc32_xfer = "55bdf222";
private const string _crc40_gsm = "c9843306eb";
private const string _crc64 = "8d33b5189c00e0a0";
private const string _crc64_ecma182 = "8d33b5189c00e0a0";
private const string _crc64_goiso = "6c3bf747ccfa1e3b";
private const string _crc64_ms = "799edc0db430d7be";
private const string _crc64_nvme = "9242023bbcf6bbf9";
private const string _crc64_redis = "408dab12b9f45dad";
private const string _crc64_we = "91812be748f941c4";
private const string _crc64_xz = "fb49044e8331f6e5";
private const string _fletcher16 = "46c1";
private const string _fletcher32 = "073f2d94";
private const string _md5 = "b722871eaa950016296184d026c5dec9";
#if NETFRAMEWORK
private const string _ripemd160 = "346361e1d7fdb836650cecdb842b0dbe660eed66";
#endif
private const string _sha1 = "eea1ee2d801d830c4bdad4df3c8da6f9f52d1a9f";
private const string _sha256 = "fdb02dee8c319c52087382c45f099c90d0b6cc824850aff28c1bfb2884b7b855";
private const string _sha384 = "e276c49618fff25bc1fe2e0659cd0ef0e7c1186563b063e07c52323b9899f3ce9b091be04d6208444b3ef1265e879074";
private const string _sha512 = "15d69514eb628c2403e945a7cafd1d27e557f6e336c69b63ea17e7ed9d256cc374ee662f09305836d6de37fdae59d83883b982aa8446e4ff26346b6b6b50b240";
{HashType.CRC1_ZERO, "0"},
{HashType.CRC1_ONE, "1"},
{HashType.CRC3_GSM, "4"},
{HashType.CRC3_ROHC, "3"},
{HashType.CRC4_G704, "6"},
{HashType.CRC4_INTERLAKEN, "0"},
{HashType.CRC5_EPCC1G2, "1f"},
{HashType.CRC5_G704, "06"},
{HashType.CRC5_USB, "0a"},
{HashType.CRC6_CDMA2000A, "3c"},
{HashType.CRC6_CDMA2000B, "12"},
{HashType.CRC6_DARC, "0f"},
{HashType.CRC6_G704, "09"},
{HashType.CRC6_GSM, "21"},
{HashType.CRC7_MMC, "2f"},
{HashType.CRC7_ROHC, "68"},
{HashType.CRC7_UMTS, "66"},
{HashType.CRC8, "fc"},
{HashType.CRC8_AUTOSAR, "ca"},
{HashType.CRC8_BLUETOOTH, "00"},
{HashType.CRC8_CDMA2000, "2d"},
{HashType.CRC8_DARC, "35"},
{HashType.CRC8_DVBS2, "5c"},
{HashType.CRC8_GSMA, "d8"},
{HashType.CRC8_GSMB, "f3"},
{HashType.CRC8_HITAG, "aa"},
{HashType.CRC8_I4321, "a9"},
{HashType.CRC8_ICODE, "61"},
{HashType.CRC8_LTE, "d7"},
{HashType.CRC8_MAXIMDOW, "bd"},
{HashType.CRC8_MIFAREMAD, "9b"},
{HashType.CRC8_NRSC5, "e2"},
{HashType.CRC8_OPENSAFETY, "fc"},
{HashType.CRC8_ROHC, "17"},
{HashType.CRC8_SAEJ1850, "55"},
{HashType.CRC8_SMBUS, "fc"},
{HashType.CRC8_TECH3250, "7d"},
{HashType.CRC8_WCDMA, "c6"},
{HashType.CRC10_ATM, "26b"},
{HashType.CRC10_CDMA2000, "14f"},
{HashType.CRC10_GSM, "0e7"},
{HashType.CRC11_FLEXRAY, "18b"},
{HashType.CRC11_UMTS, "347"},
{HashType.CRC12_CDMA2000, "f9c"},
{HashType.CRC12_DECT, "d62"},
{HashType.CRC12_GSM, "975"},
{HashType.CRC12_UMTS, "46b"},
{HashType.CRC13_BBC, "074f"},
{HashType.CRC14_DARC, "0add"},
{HashType.CRC14_GSM, "0c7d"},
{HashType.CRC15_CAN, "66c3"},
{HashType.CRC15_MPT1327, "013b"},
{HashType.CRC16, "7573"},
{HashType.CRC16_ARC, "7573"},
{HashType.CRC16_CDMA2000, "8b5f"},
{HashType.CRC16_CMS, "1a37"},
{HashType.CRC16_DDS110, "241d"},
{HashType.CRC16_DECTR, "7390"},
{HashType.CRC16_DECTX, "7391"},
{HashType.CRC16_DNP, "4bbb"},
{HashType.CRC16_EN13757, "e28b"},
{HashType.CRC16_GENIBUS, "b65d"},
{HashType.CRC16_GSM, "482d"},
{HashType.CRC16_IBM3740, "49a2"},
{HashType.CRC16_IBMSDLC, "4f52"},
{HashType.CRC16_ISOIEC144433A, "85cd"},
{HashType.CRC16_KERMIT, "bed2"},
{HashType.CRC16_LJ1200, "3533"},
{HashType.CRC16_M17, "5223"},
{HashType.CRC16_MAXIMDOW, "8a8c"},
{HashType.CRC16_MCRF4XX, "b0ad"},
{HashType.CRC16_MODBUS, "9e54"},
{HashType.CRC16_NRSC5, "4857"},
{HashType.CRC16_OPENSAFETYA, "abcd"},
{HashType.CRC16_OPENSAFETYB, "76f4"},
{HashType.CRC16_PROFIBUS, "3099"},
{HashType.CRC16_RIELLO, "23e0"},
{HashType.CRC16_SPIFUJITSU, "f98b"},
{HashType.CRC16_T10DIF, "2642"},
{HashType.CRC16_TELEDISK, "7e05"},
{HashType.CRC16_TMS37157, "dba0"},
{HashType.CRC16_UMTS, "fee0"},
{HashType.CRC16_USB, "61ab"},
{HashType.CRC16_XMODEM, "b7d2"},
{HashType.CRC17_CANFD, "0706d"},
{HashType.CRC21_CANFD, "117d4b"},
{HashType.CRC24_BLE, "2969f2"},
{HashType.CRC24_FLEXRAYA, "ce9dc7"},
{HashType.CRC24_FLEXRAYB, "0f49d7"},
{HashType.CRC24_INTERLAKEN, "fb4725"},
{HashType.CRC24_LTEA, "675e55"},
{HashType.CRC24_LTEB, "c91203"},
{HashType.CRC24_OPENPGP, "0c6012"},
{HashType.CRC24_OS9, "610e21"},
{HashType.CRC30_CDMA, "2ce682b2"},
{HashType.CRC31_PHILIPS, "247c3cbe"},
{HashType.CRC32, "ba02a660"},
{HashType.CRC32_AIXM, "6174a75a"},
{HashType.CRC32_AUTOSAR, "c050428e"},
{HashType.CRC32_BASE91D, "e741ba25"},
{HashType.CRC32_BZIP2, "18aa4603"},
{HashType.CRC32_CDROMEDC, "b8ced467"},
{HashType.CRC32_CKSUM, "f27b3c27"},
{HashType.CRC32_DVDROMEDC, "b538afc0"},
{HashType.CRC32_ISCSI, "544d37db"},
{HashType.CRC32_ISOHDLC, "ba02a660"},
{HashType.CRC32_JAMCRC, "45fd599f"},
{HashType.CRC32_MEF, "d9d98444"},
{HashType.CRC32_MPEG2, "e755b9fc"},
{HashType.CRC32_XFER, "55bdf222"},
{HashType.CRC40_GSM, "c9843306eb"},
{HashType.CRC64, "8d33b5189c00e0a0"},
{HashType.CRC64_ECMA182, "8d33b5189c00e0a0"},
{HashType.CRC64_GOISO, "6c3bf747ccfa1e3b"},
{HashType.CRC64_MS, "799edc0db430d7be"},
{HashType.CRC64_NVME, "9242023bbcf6bbf9"},
{HashType.CRC64_REDIS, "408dab12b9f45dad"},
{HashType.CRC64_WE, "91812be748f941c4"},
{HashType.CRC64_XZ, "fb49044e8331f6e5"},
{HashType.Fletcher16, "46c1"},
{HashType.Fletcher32, "073f2d94"},
{HashType.Fletcher64, "000b073400002d94"},
{HashType.FNV0_32, "33d28b00"},
{HashType.FNV0_64, "778e818addd23280"},
{HashType.FNV1_32, "ac09cbeb"},
{HashType.FNV1_64, "23229308c1f9252b"},
{HashType.FNV1a_32, "9086769b"},
{HashType.FNV1a_64, "399dd1cd965b73db"},
{HashType.MekaCrc, "0a0a0b1174052f22"},
{HashType.MD2, "362e1a6931668e6a9de5c159c52c71b5"},
{HashType.MD4, "61bef59d7a754874fccbd67b4ec2fb10"},
{HashType.MD5, "b722871eaa950016296184d026c5dec9"},
{HashType.RIPEMD128, "6356cc18225245de3ca9afcb4fa22ce6"},
{HashType.RIPEMD160, "346361e1d7fdb836650cecdb842b0dbe660eed66"},
{HashType.RIPEMD256, "c2fe11922529651bc615be3d8a296820b6681ecaed5ce051439c86bf3d942276"},
{HashType.RIPEMD320, "a523bec87b0738f89d8ae5cf0edd3ee9c7b9811f1051e32893e32e820db33841b9d5042e738d20c9"},
{HashType.SHA1, "eea1ee2d801d830c4bdad4df3c8da6f9f52d1a9f"},
{HashType.SHA256, "fdb02dee8c319c52087382c45f099c90d0b6cc824850aff28c1bfb2884b7b855"},
{HashType.SHA384, "e276c49618fff25bc1fe2e0659cd0ef0e7c1186563b063e07c52323b9899f3ce9b091be04d6208444b3ef1265e879074"},
{HashType.SHA512, "15d69514eb628c2403e945a7cafd1d27e557f6e336c69b63ea17e7ed9d256cc374ee662f09305836d6de37fdae59d83883b982aa8446e4ff26346b6b6b50b240"},
#if NET8_0_OR_GREATER
private const string _sha3_256 = "1d76459e68c865b5911ada5104067cc604c5c60b345c4e81b3905e916a43c868";
private const string _sha3_384 = "1bcbed87b73f25c0adf486c3afbf0ea3105763c387af3f8b2bd79b0a1964d42832b1d7c6a2225f9153ead26f442e8b67";
private const string _sha3_512 = "89852144df37c58d01f5912124f1942dd00bac0346eb3971943416699c3094cff087fb42c356019c3d91f8e8f55b9254c8caec48e9414af6817297d06725ffeb";
private const string _shake128 = "e5f88d0db79a71c39490beb9ebac21eaf4a5d6368438fca20f5e4ce77cfee9aa";
private const string _shake256 = "24d9e83198bbc7baf4dcd293bfc35ae3fff05399786c37318f1b1ef85f41970c66926f8a2a1f912d96e2d8e45535af88a301a1c200697437c1a65d7e980344bc";
{HashType.SHA3_256, "1d76459e68c865b5911ada5104067cc604c5c60b345c4e81b3905e916a43c868"},
{HashType.SHA3_384, "1bcbed87b73f25c0adf486c3afbf0ea3105763c387af3f8b2bd79b0a1964d42832b1d7c6a2225f9153ead26f442e8b67"},
{HashType.SHA3_512, "89852144df37c58d01f5912124f1942dd00bac0346eb3971943416699c3094cff087fb42c356019c3d91f8e8f55b9254c8caec48e9414af6817297d06725ffeb"},
{HashType.SHAKE128, "e5f88d0db79a71c39490beb9ebac21eaf4a5d6368438fca20f5e4ce77cfee9aa"},
{HashType.SHAKE256, "24d9e83198bbc7baf4dcd293bfc35ae3fff05399786c37318f1b1ef85f41970c66926f8a2a1f912d96e2d8e45535af88a301a1c200697437c1a65d7e980344bc"},
#endif
private const string _spamsum = "3:hMCPQCE6AFQxWyENFACBE+rW6Tj7SMQmKozr9MVERkL:hZRdxZENFs+rPSromekL";
{HashType.SpamSum, "3:hMCPQCE6AFQxWyENFACBE+rW6Tj7SMQmKozr9MVERkL:hZRdxZENFs+rPSromekL"},
{HashType.Tiger128_3, "afc7ac1c3c031b675562f917b59f0885"},
{HashType.Tiger128_4, "e7609126923009f733cd0fcbc5a733fa"},
{HashType.Tiger160_3, "afc7ac1c3c031b675562f917b59f088533405e1a"},
{HashType.Tiger160_4, "e7609126923009f733cd0fcbc5a733fa4f4ccf7a"},
{HashType.Tiger192_3, "afc7ac1c3c031b675562f917b59f088533405e1a2f72912d"},
{HashType.Tiger192_4, "e7609126923009f733cd0fcbc5a733fa4f4ccf7ab7c0e2a3"},
{HashType.Tiger2_128_3, "b26271774e66519b1c746f210e0be05c"},
{HashType.Tiger2_128_4, "f1df540d3f2521b87a957c9b2b00fc7c"},
{HashType.Tiger2_160_3, "b26271774e66519b1c746f210e0be05c4fd9efde"},
{HashType.Tiger2_160_4, "f1df540d3f2521b87a957c9b2b00fc7c589306dc"},
{HashType.Tiger2_192_3, "b26271774e66519b1c746f210e0be05c4fd9efde26e46e89"},
{HashType.Tiger2_192_4, "f1df540d3f2521b87a957c9b2b00fc7c589306dcf094acb5"},
{HashType.XxHash32, "aa1d338e"},
{HashType.XxHash64, "181e9ea4f0f62b08"},
#if NET462_OR_GREATER || NETCOREAPP
private const string _xxhash32 = "8e331daa";
private const string _xxhash64 = "082bf6f0a49e1e18";
private const string _xxhash3 = "040474eb0eda9ff2";
private const string _xxhash128 = "d934b4b4a5e1e11baeef8012fbcd11e8";
{HashType.XxHash3, "f29fda0eeb740404"},
{HashType.XxHash128, "e811cdfb1280efae1be1e1a5b4b434d9"},
#endif
};
#endregion
@@ -111,113 +227,22 @@ namespace SabreTools.Hashing.Test
public static void ValidateHashes(Dictionary<HashType, string?>? hashDict)
{
Assert.NotNull(hashDict);
Assert.Equal(_adler32, hashDict![HashType.Adler32]);
#if NET7_0_OR_GREATER
Assert.Equal(_blake3, hashDict[HashType.BLAKE3]);
#endif
Assert.Equal(_crc16, hashDict[HashType.CRC16]);
Assert.Equal(_crc16_arc, hashDict[HashType.CRC16_ARC]);
Assert.Equal(_crc16_cdma2000, hashDict[HashType.CRC16_CDMA2000]);
Assert.Equal(_crc16_cms, hashDict[HashType.CRC16_CMS]);
Assert.Equal(_crc16_dds110, hashDict[HashType.CRC16_DDS110]);
Assert.Equal(_crc16_dectr, hashDict[HashType.CRC16_DECTR]);
Assert.Equal(_crc16_dectx, hashDict[HashType.CRC16_DECTX]);
Assert.Equal(_crc16_dnp, hashDict[HashType.CRC16_DNP]);
Assert.Equal(_crc16_en13757, hashDict[HashType.CRC16_EN13757]);
Assert.Equal(_crc16_genibus, hashDict[HashType.CRC16_GENIBUS]);
Assert.Equal(_crc16_gsm, hashDict[HashType.CRC16_GSM]);
Assert.Equal(_crc16_ibm3740, hashDict[HashType.CRC16_IBM3740]);
Assert.Equal(_crc16_ibmsdlc, hashDict[HashType.CRC16_IBMSDLC]);
//Assert.Equal(_crc16_isoiec144433a, hashDict[HashType.CRC16_ISOIEC144433A]);
Assert.Equal(_crc16_kermit, hashDict[HashType.CRC16_KERMIT]);
Assert.Equal(_crc16_lj1200, hashDict[HashType.CRC16_LJ1200]);
Assert.Equal(_crc16_m17, hashDict[HashType.CRC16_M17]);
Assert.Equal(_crc16_maximdow, hashDict[HashType.CRC16_MAXIMDOW]);
Assert.Equal(_crc16_mcrf4xx, hashDict[HashType.CRC16_MCRF4XX]);
Assert.Equal(_crc16_modbus, hashDict[HashType.CRC16_MODBUS]);
Assert.Equal(_crc16_nrsc5, hashDict[HashType.CRC16_NRSC5]);
Assert.Equal(_crc16_opensafetya, hashDict[HashType.CRC16_OPENSAFETYA]);
Assert.Equal(_crc16_opensafetyb, hashDict[HashType.CRC16_OPENSAFETYB]);
Assert.Equal(_crc16_profibus, hashDict[HashType.CRC16_PROFIBUS]);
//Assert.Equal(_crc16_riello, hashDict[HashType.CRC16_RIELLO]);
Assert.Equal(_crc16_spifujitsu, hashDict[HashType.CRC16_SPIFUJITSU]);
Assert.Equal(_crc16_t10dif, hashDict[HashType.CRC16_T10DIF]);
Assert.Equal(_crc16_teledisk, hashDict[HashType.CRC16_TELEDISK]);
//Assert.Equal(_crc16_tms37157, hashDict[HashType.CRC16_TMS37157]);
Assert.Equal(_crc16_umts, hashDict[HashType.CRC16_UMTS]);
Assert.Equal(_crc16_usb, hashDict[HashType.CRC16_USB]);
Assert.Equal(_crc16_xmodem, hashDict[HashType.CRC16_XMODEM]);
//Assert.Equal(_crc24_ble, hashDict[HashType.CRC24_BLE]);
Assert.Equal(_crc24_flexraya, hashDict[HashType.CRC24_FLEXRAYA]);
Assert.Equal(_crc24_flexrayb, hashDict[HashType.CRC24_FLEXRAYB]);
Assert.Equal(_crc24_interlaken, hashDict[HashType.CRC24_INTERLAKEN]);
Assert.Equal(_crc24_ltea, hashDict[HashType.CRC24_LTEA]);
Assert.Equal(_crc24_lteb, hashDict[HashType.CRC24_LTEB]);
Assert.Equal(_crc24_openpgp, hashDict[HashType.CRC24_OPENPGP]);
Assert.Equal(_crc24_os9, hashDict[HashType.CRC24_OS9]);
Assert.Equal(_crc32, hashDict[HashType.CRC32]);
Assert.Equal(_crc32_aixm, hashDict[HashType.CRC32_AIXM]);
Assert.Equal(_crc32_autosar, hashDict[HashType.CRC32_AUTOSAR]);
Assert.Equal(_crc32_base91d, hashDict[HashType.CRC32_BASE91D]);
Assert.Equal(_crc32_bzip2, hashDict[HashType.CRC32_BZIP2]);
Assert.Equal(_crc32_cdromedc, hashDict[HashType.CRC32_CDROMEDC]);
Assert.Equal(_crc32_cksum, hashDict[HashType.CRC32_CKSUM]);
Assert.Equal(_crc32_iscsi, hashDict[HashType.CRC32_ISCSI]);
Assert.Equal(_crc32_isohdlc, hashDict[HashType.CRC32_ISOHDLC]);
Assert.Equal(_crc32_jamcrc, hashDict[HashType.CRC32_JAMCRC]);
Assert.Equal(_crc32_mef, hashDict[HashType.CRC32_MEF]);
Assert.Equal(_crc32_mpeg2, hashDict[HashType.CRC32_MPEG2]);
Assert.Equal(_crc32_xfer, hashDict[HashType.CRC32_XFER]);
Assert.Equal(_crc40_gsm, hashDict[HashType.CRC40_GSM]);
Assert.Equal(_crc64, hashDict[HashType.CRC64]);
Assert.Equal(_crc64_ecma182, hashDict[HashType.CRC64_ECMA182]);
Assert.Equal(_crc64_goiso, hashDict[HashType.CRC64_GOISO]);
Assert.Equal(_crc64_ms, hashDict[HashType.CRC64_MS]);
Assert.Equal(_crc64_nvme, hashDict[HashType.CRC64_NVME]);
Assert.Equal(_crc64_redis, hashDict[HashType.CRC64_REDIS]);
Assert.Equal(_crc64_we, hashDict[HashType.CRC64_WE]);
Assert.Equal(_crc64_xz, hashDict[HashType.CRC64_XZ]);
Assert.Equal(_fletcher16, hashDict[HashType.Fletcher16]);
Assert.Equal(_fletcher32, hashDict[HashType.Fletcher32]);
Assert.Equal(_md5, hashDict[HashType.MD5]);
#if NETFRAMEWORK
Assert.Equal(_ripemd160, hashDict[HashType.RIPEMD160]);
#endif
Assert.Equal(_sha1, hashDict[HashType.SHA1]);
Assert.Equal(_sha256, hashDict[HashType.SHA256]);
Assert.Equal(_sha384, hashDict[HashType.SHA384]);
Assert.Equal(_sha512, hashDict[HashType.SHA512]);
#if NET8_0_OR_GREATER
if (System.Security.Cryptography.SHA3_256.IsSupported)
Assert.Equal(_sha3_256, hashDict[HashType.SHA3_256]);
if (System.Security.Cryptography.SHA3_384.IsSupported)
Assert.Equal(_sha3_384, hashDict[HashType.SHA3_384]);
if (System.Security.Cryptography.SHA3_512.IsSupported)
Assert.Equal(_sha3_512, hashDict[HashType.SHA3_512]);
if (System.Security.Cryptography.Shake128.IsSupported)
Assert.Equal(_shake128, hashDict[HashType.SHAKE128]);
if (System.Security.Cryptography.Shake256.IsSupported)
Assert.Equal(_shake256, hashDict[HashType.SHAKE256]);
#endif
Assert.Equal(_spamsum, hashDict[HashType.SpamSum]);
#if NET462_OR_GREATER || NETCOREAPP
Assert.Equal(_xxhash32, hashDict[HashType.XxHash32]);
Assert.Equal(_xxhash64, hashDict[HashType.XxHash64]);
Assert.Equal(_xxhash3, hashDict[HashType.XxHash3]);
Assert.Equal(_xxhash128, hashDict[HashType.XxHash128]);
#endif
foreach (var hashType in _knownHashes.Keys)
{
ValidateHash(hashType, hashDict![hashType]);
}
}
/// <summary>
/// Validate a single hash
/// </summary>
public static void ValidateHash(HashType hashType, string? hashValue)
=> Assert.Equal(_knownHashes[hashType], hashValue);
/// <summary>
/// Validate the file size
/// </summary>
public static void ValidateSize(long fileSize)
=> Assert.Equal(_hashFileSize, fileSize);
}
}
}

View File

@@ -0,0 +1,48 @@
using System;
using System.Linq;
using Xunit;
namespace SabreTools.Hashing.Test
{
public class ZeroHashTests
{
/// <summary>
/// Get an array of all hash types
/// </summary>
public static TheoryData<HashType> AllHashTypes
{
get
{
var values = Enum.GetValues<HashType>();
var set = new TheoryData<HashType>();
foreach (var value in values)
{
set.Add(value);
}
return set;
}
}
[Theory]
[MemberData(nameof(AllHashTypes))]
public void GetZeroByteHashes(HashType hashType)
{
var expected = ZeroHash.GetBytes(hashType);
var actual = HashTool.GetByteArrayHashArray([], hashType);
Assert.NotNull(actual);
Assert.Equal(expected.Length, actual.Length);
Assert.True(actual.SequenceEqual(expected));
}
[Theory]
[MemberData(nameof(AllHashTypes))]
public void GetZeroStringHashes(HashType hashType)
{
var expected = ZeroHash.GetString(hashType);
var actual = HashTool.GetByteArrayHash([], hashType);
Assert.Equal(expected, actual);
}
}
}

View File

@@ -7,22 +7,56 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SabreTools.Hashing", "Sabre
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SabreTools.Hashing.Test", "SabreTools.Hashing.Test\SabreTools.Hashing.Test.csproj", "{A2BCBFDE-685B-4817-B724-050A99E02601}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Hasher", "Hasher\Hasher.csproj", "{5DAC74F2-22AB-409B-B828-2FD3851586A3}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Debug|x64 = Debug|x64
Debug|x86 = Debug|x86
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Release|x64 = Release|x64
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{F7E34528-080E-4E60-B9D1-8ADF70A24BB0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{F7E34528-080E-4E60-B9D1-8ADF70A24BB0}.Debug|Any CPU.Build.0 = Debug|Any CPU
{F7E34528-080E-4E60-B9D1-8ADF70A24BB0}.Debug|x64.ActiveCfg = Debug|Any CPU
{F7E34528-080E-4E60-B9D1-8ADF70A24BB0}.Debug|x64.Build.0 = Debug|Any CPU
{F7E34528-080E-4E60-B9D1-8ADF70A24BB0}.Debug|x86.ActiveCfg = Debug|Any CPU
{F7E34528-080E-4E60-B9D1-8ADF70A24BB0}.Debug|x86.Build.0 = Debug|Any CPU
{F7E34528-080E-4E60-B9D1-8ADF70A24BB0}.Release|Any CPU.ActiveCfg = Release|Any CPU
{F7E34528-080E-4E60-B9D1-8ADF70A24BB0}.Release|Any CPU.Build.0 = Release|Any CPU
{F7E34528-080E-4E60-B9D1-8ADF70A24BB0}.Release|x64.ActiveCfg = Release|Any CPU
{F7E34528-080E-4E60-B9D1-8ADF70A24BB0}.Release|x64.Build.0 = Release|Any CPU
{F7E34528-080E-4E60-B9D1-8ADF70A24BB0}.Release|x86.ActiveCfg = Release|Any CPU
{F7E34528-080E-4E60-B9D1-8ADF70A24BB0}.Release|x86.Build.0 = Release|Any CPU
{A2BCBFDE-685B-4817-B724-050A99E02601}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{A2BCBFDE-685B-4817-B724-050A99E02601}.Debug|Any CPU.Build.0 = Debug|Any CPU
{A2BCBFDE-685B-4817-B724-050A99E02601}.Debug|x64.ActiveCfg = Debug|Any CPU
{A2BCBFDE-685B-4817-B724-050A99E02601}.Debug|x64.Build.0 = Debug|Any CPU
{A2BCBFDE-685B-4817-B724-050A99E02601}.Debug|x86.ActiveCfg = Debug|Any CPU
{A2BCBFDE-685B-4817-B724-050A99E02601}.Debug|x86.Build.0 = Debug|Any CPU
{A2BCBFDE-685B-4817-B724-050A99E02601}.Release|Any CPU.ActiveCfg = Release|Any CPU
{A2BCBFDE-685B-4817-B724-050A99E02601}.Release|Any CPU.Build.0 = Release|Any CPU
{A2BCBFDE-685B-4817-B724-050A99E02601}.Release|x64.ActiveCfg = Release|Any CPU
{A2BCBFDE-685B-4817-B724-050A99E02601}.Release|x64.Build.0 = Release|Any CPU
{A2BCBFDE-685B-4817-B724-050A99E02601}.Release|x86.ActiveCfg = Release|Any CPU
{A2BCBFDE-685B-4817-B724-050A99E02601}.Release|x86.Build.0 = Release|Any CPU
{5DAC74F2-22AB-409B-B828-2FD3851586A3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{5DAC74F2-22AB-409B-B828-2FD3851586A3}.Debug|Any CPU.Build.0 = Debug|Any CPU
{5DAC74F2-22AB-409B-B828-2FD3851586A3}.Debug|x64.ActiveCfg = Debug|Any CPU
{5DAC74F2-22AB-409B-B828-2FD3851586A3}.Debug|x64.Build.0 = Debug|Any CPU
{5DAC74F2-22AB-409B-B828-2FD3851586A3}.Debug|x86.ActiveCfg = Debug|Any CPU
{5DAC74F2-22AB-409B-B828-2FD3851586A3}.Debug|x86.Build.0 = Debug|Any CPU
{5DAC74F2-22AB-409B-B828-2FD3851586A3}.Release|Any CPU.ActiveCfg = Release|Any CPU
{5DAC74F2-22AB-409B-B828-2FD3851586A3}.Release|Any CPU.Build.0 = Release|Any CPU
{5DAC74F2-22AB-409B-B828-2FD3851586A3}.Release|x64.ActiveCfg = Release|Any CPU
{5DAC74F2-22AB-409B-B828-2FD3851586A3}.Release|x64.Build.0 = Release|Any CPU
{5DAC74F2-22AB-409B-B828-2FD3851586A3}.Release|x86.ActiveCfg = Release|Any CPU
{5DAC74F2-22AB-409B-B828-2FD3851586A3}.Release|x86.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
EndGlobal

View File

@@ -1,217 +0,0 @@
// /***************************************************************************
// Aaru Data Preservation Suite
// ----------------------------------------------------------------------------
//
// Filename : neon.cs
// Author(s) : Natalia Portillo <claunia@claunia.com>
// The Chromium Authors
//
// Component : Checksums.
//
// --[ Description ] ----------------------------------------------------------
//
// Compute Adler32 checksum using NEON vectorization.
//
// --[ License ] --------------------------------------------------------------
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// ----------------------------------------------------------------------------
// Copyright © 2011-2023 Natalia Portillo
// Copyright 2017 The Chromium Authors. All rights reserved.
// ****************************************************************************/
#if NET5_0_OR_GREATER
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.Arm;
namespace Aaru.Checksums.Adler32;
static class Neon
{
internal static void Step(ref ushort preSum1, ref ushort preSum2, byte[] buf, uint len)
{
/*
* Split Adler-32 into component sums.
*/
uint s1 = preSum1;
uint s2 = preSum2;
var bufPos = 0;
/*
* Process the data in blocks.
*/
const uint blockSize = 1 << 5;
uint blocks = len / blockSize;
len -= blocks * blockSize;
while(blocks != 0)
{
uint n = Adler32Context.NMAX / blockSize; /* The NMAX constraint. */
if(n > blocks)
n = blocks;
blocks -= n;
/*
* Process n blocks of data. At most NMAX data bytes can be
* processed before s2 must be reduced modulo ADLER_MODULE.
*/
var vS2 = Vector128.Create(s1 * n, 0, 0, 0);
var vS1 = Vector128.Create(0u, 0, 0, 0);
Vector128<ushort> vColumnSum1 = AdvSimd.DuplicateToVector128((ushort)0);
Vector128<ushort> vColumnSum2 = AdvSimd.DuplicateToVector128((ushort)0);
Vector128<ushort> vColumnSum3 = AdvSimd.DuplicateToVector128((ushort)0);
Vector128<ushort> vColumnSum4 = AdvSimd.DuplicateToVector128((ushort)0);
do
{
/*
* Load 32 input bytes.
*/
var bytes1 = Vector128.Create(buf[bufPos], buf[bufPos + 1], buf[bufPos + 2], buf[bufPos + 3],
buf[bufPos + 4], buf[bufPos + 5], buf[bufPos + 6], buf[bufPos + 7],
buf[bufPos + 8], buf[bufPos + 9], buf[bufPos + 10], buf[bufPos + 11],
buf[bufPos + 12], buf[bufPos + 13], buf[bufPos + 14], buf[bufPos + 15]);
bufPos += 16;
var bytes2 = Vector128.Create(buf[bufPos], buf[bufPos + 1], buf[bufPos + 2], buf[bufPos + 3],
buf[bufPos + 4], buf[bufPos + 5], buf[bufPos + 6], buf[bufPos + 7],
buf[bufPos + 8], buf[bufPos + 9], buf[bufPos + 10], buf[bufPos + 11],
buf[bufPos + 12], buf[bufPos + 13], buf[bufPos + 14], buf[bufPos + 15]);
bufPos += 16;
/*
* Add previous block byte sum to v_s2.
*/
vS2 = AdvSimd.Add(vS2, vS1);
/*
* Horizontally add the bytes for s1.
*/
vS1 =
AdvSimd.AddPairwiseWideningAndAdd(vS1,
AdvSimd.
AddPairwiseWideningAndAdd(AdvSimd.AddPairwiseWidening(bytes1),
bytes2));
/*
* Vertically add the bytes for s2.
*/
vColumnSum1 = AdvSimd.AddWideningLower(vColumnSum1, bytes1.GetLower());
vColumnSum2 = AdvSimd.AddWideningLower(vColumnSum2, bytes1.GetUpper());
vColumnSum3 = AdvSimd.AddWideningLower(vColumnSum3, bytes2.GetLower());
vColumnSum4 = AdvSimd.AddWideningLower(vColumnSum4, bytes2.GetUpper());
} while(--n != 0);
vS2 = AdvSimd.ShiftLeftLogical(vS2, 5);
/*
* Multiply-add bytes by [ 32, 31, 30, ... ] for s2.
*/
vS2 = AdvSimd.MultiplyWideningLowerAndAdd(vS2, vColumnSum1.GetLower(),
Vector64.Create((ushort)32, 31, 30, 29));
vS2 = AdvSimd.MultiplyWideningLowerAndAdd(vS2, vColumnSum1.GetUpper(),
Vector64.Create((ushort)28, 27, 26, 25));
vS2 = AdvSimd.MultiplyWideningLowerAndAdd(vS2, vColumnSum2.GetLower(),
Vector64.Create((ushort)24, 23, 22, 21));
vS2 = AdvSimd.MultiplyWideningLowerAndAdd(vS2, vColumnSum2.GetUpper(),
Vector64.Create((ushort)20, 19, 18, 17));
vS2 = AdvSimd.MultiplyWideningLowerAndAdd(vS2, vColumnSum3.GetLower(),
Vector64.Create((ushort)16, 15, 14, 13));
vS2 = AdvSimd.MultiplyWideningLowerAndAdd(vS2, vColumnSum3.GetUpper(),
Vector64.Create((ushort)12, 11, 10, 9));
vS2 = AdvSimd.MultiplyWideningLowerAndAdd(vS2, vColumnSum4.GetLower(), Vector64.Create((ushort)8, 7, 6, 5));
vS2 = AdvSimd.MultiplyWideningLowerAndAdd(vS2, vColumnSum4.GetUpper(), Vector64.Create((ushort)4, 3, 2, 1));
/*
* Sum epi32 ints v_s1(s2) and accumulate in s1(s2).
*/
Vector64<uint> sum1 = AdvSimd.AddPairwise(vS1.GetLower(), vS1.GetUpper());
Vector64<uint> sum2 = AdvSimd.AddPairwise(vS2.GetLower(), vS2.GetUpper());
Vector64<uint> s1S2 = AdvSimd.AddPairwise(sum1, sum2);
s1 += AdvSimd.Extract(s1S2, 0);
s2 += AdvSimd.Extract(s1S2, 1);
/*
* Reduce.
*/
s1 %= Adler32Context.ADLER_MODULE;
s2 %= Adler32Context.ADLER_MODULE;
}
/*
* Handle leftover data.
*/
if(len != 0)
{
if(len >= 16)
{
s2 += s1 += buf[bufPos++];
s2 += s1 += buf[bufPos++];
s2 += s1 += buf[bufPos++];
s2 += s1 += buf[bufPos++];
s2 += s1 += buf[bufPos++];
s2 += s1 += buf[bufPos++];
s2 += s1 += buf[bufPos++];
s2 += s1 += buf[bufPos++];
s2 += s1 += buf[bufPos++];
s2 += s1 += buf[bufPos++];
s2 += s1 += buf[bufPos++];
s2 += s1 += buf[bufPos++];
s2 += s1 += buf[bufPos++];
s2 += s1 += buf[bufPos++];
s2 += s1 += buf[bufPos++];
s2 += s1 += buf[bufPos++];
len -= 16;
}
while(len-- != 0)
s2 += s1 += buf[bufPos++];
if(s1 >= Adler32Context.ADLER_MODULE)
s1 -= Adler32Context.ADLER_MODULE;
s2 %= Adler32Context.ADLER_MODULE;
}
/*
* Return the recombined sums.
*/
preSum1 = (ushort)(s1 & 0xFFFF);
preSum2 = (ushort)(s2 & 0xFFFF);
}
}
#endif

View File

@@ -1,194 +0,0 @@
// /***************************************************************************
// Aaru Data Preservation Suite
// ----------------------------------------------------------------------------
//
// Filename : ssse3.cs
// Author(s) : Natalia Portillo <claunia@claunia.com>
// The Chromium Authors
//
// Component : Checksums.
//
// --[ Description ] ----------------------------------------------------------
//
// Compute Adler32 checksum using SSSE3 vectorization.
//
// --[ License ] --------------------------------------------------------------
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// ----------------------------------------------------------------------------
// Copyright © 2011-2023 Natalia Portillo
// Copyright 2017 The Chromium Authors. All rights reserved.
// ****************************************************************************/
#if NETCOREAPP3_1_OR_GREATER
using System;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace Aaru.Checksums.Adler32;
static class Ssse3
{
internal static void Step(ref ushort sum1, ref ushort sum2, byte[] buf, uint len)
{
uint s1 = sum1;
uint s2 = sum2;
var bufPos = 0;
/*
* Process the data in blocks.
*/
const uint blockSize = 1 << 5;
uint blocks = len / blockSize;
len -= blocks * blockSize;
while(blocks != 0)
{
uint n = Adler32Context.NMAX / blockSize; /* The NMAX constraint. */
if(n > blocks)
n = blocks;
blocks -= n;
Vector128<byte> tap1 = Vector128.Create(32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17).
AsByte();
Vector128<byte> tap2 = Vector128.Create(16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1).AsByte();
Vector128<byte> zero = Vector128.Create(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0).AsByte();
var ones = Vector128.Create(1, 1, 1, 1, 1, 1, 1, 1);
/*
* Process n blocks of data. At most NMAX data bytes can be
* processed before s2 must be reduced modulo BASE.
*/
var vPs = Vector128.Create(s1 * n, 0, 0, 0);
var vS2 = Vector128.Create(s2, 0, 0, 0);
var vS1 = Vector128.Create(0u, 0, 0, 0);
do
{
/*
* Load 32 input bytes.
*/
var bytes1 = Vector128.Create(BitConverter.ToUInt32(buf, bufPos),
BitConverter.ToUInt32(buf, bufPos + 4),
BitConverter.ToUInt32(buf, bufPos + 8),
BitConverter.ToUInt32(buf, bufPos + 12));
bufPos += 16;
var bytes2 = Vector128.Create(BitConverter.ToUInt32(buf, bufPos),
BitConverter.ToUInt32(buf, bufPos + 4),
BitConverter.ToUInt32(buf, bufPos + 8),
BitConverter.ToUInt32(buf, bufPos + 12));
bufPos += 16;
/*
* Add previous block byte sum to v_ps.
*/
vPs = Sse2.Add(vPs, vS1);
/*
* Horizontally add the bytes for s1, multiply-adds the
* bytes by [ 32, 31, 30, ... ] for s2.
*/
vS1 = Sse2.Add(vS1, Sse2.SumAbsoluteDifferences(bytes1.AsByte(), zero).AsUInt32());
Vector128<short> mad1 =
System.Runtime.Intrinsics.X86.Ssse3.MultiplyAddAdjacent(bytes1.AsByte(), tap1.AsSByte());
vS2 = Sse2.Add(vS2, Sse2.MultiplyAddAdjacent(mad1.AsInt16(), ones.AsInt16()).AsUInt32());
vS1 = Sse2.Add(vS1, Sse2.SumAbsoluteDifferences(bytes2.AsByte(), zero).AsUInt32());
Vector128<short> mad2 =
System.Runtime.Intrinsics.X86.Ssse3.MultiplyAddAdjacent(bytes2.AsByte(), tap2.AsSByte());
vS2 = Sse2.Add(vS2, Sse2.MultiplyAddAdjacent(mad2.AsInt16(), ones.AsInt16()).AsUInt32());
} while(--n != 0);
vS2 = Sse2.Add(vS2, Sse2.ShiftLeftLogical(vPs, 5));
/*
* Sum epi32 ints v_s1(s2) and accumulate in s1(s2).
*/
vS1 = Sse2.Add(vS1, Sse2.Shuffle(vS1, 177));
vS1 = Sse2.Add(vS1, Sse2.Shuffle(vS1, 78));
s1 += (uint)Sse2.ConvertToInt32(vS1.AsInt32());
vS2 = Sse2.Add(vS2, Sse2.Shuffle(vS2, 177));
vS2 = Sse2.Add(vS2, Sse2.Shuffle(vS2, 78));
s2 = (uint)Sse2.ConvertToInt32(vS2.AsInt32());
/*
* Reduce.
*/
s1 %= Adler32Context.ADLER_MODULE;
s2 %= Adler32Context.ADLER_MODULE;
}
/*
* Handle leftover data.
*/
if(len != 0)
{
if(len >= 16)
{
s2 += s1 += buf[bufPos++];
s2 += s1 += buf[bufPos++];
s2 += s1 += buf[bufPos++];
s2 += s1 += buf[bufPos++];
s2 += s1 += buf[bufPos++];
s2 += s1 += buf[bufPos++];
s2 += s1 += buf[bufPos++];
s2 += s1 += buf[bufPos++];
s2 += s1 += buf[bufPos++];
s2 += s1 += buf[bufPos++];
s2 += s1 += buf[bufPos++];
s2 += s1 += buf[bufPos++];
s2 += s1 += buf[bufPos++];
s2 += s1 += buf[bufPos++];
s2 += s1 += buf[bufPos++];
s2 += s1 += buf[bufPos++];
len -= 16;
}
while(len-- != 0)
s2 += s1 += buf[bufPos++];
if(s1 >= Adler32Context.ADLER_MODULE)
s1 -= Adler32Context.ADLER_MODULE;
s2 %= Adler32Context.ADLER_MODULE;
}
/*
* Return the recombined sums.
*/
sum1 = (ushort)(s1 & 0xFFFF);
sum2 = (ushort)(s2 & 0xFFFF);
}
}
#endif

View File

@@ -1,435 +0,0 @@
// /***************************************************************************
// Aaru Data Preservation Suite
// ----------------------------------------------------------------------------
//
// Filename : Adler32Context.cs
// Author(s) : Natalia Portillo <claunia@claunia.com>
//
// Component : Checksums.
//
// --[ Description ] ----------------------------------------------------------
//
// Implements an Adler-32 algorithm.
//
// --[ License ] --------------------------------------------------------------
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
// 3. This notice may not be removed or altered from any source distribution.
//
// ----------------------------------------------------------------------------
// Copyright © 2011-2023 Natalia Portillo
// Copyright (C) 1995-2011 Mark Adler
// Copyright (C) Jean-loup Gailly
// ****************************************************************************/
using System;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Runtime.InteropServices;
#if NET5_0_OR_GREATER
using System.Runtime.Intrinsics.Arm;
#endif
using System.Text;
#if NETCOREAPP3_1_OR_GREATER
using Aaru.Checksums.Adler32;
#endif
using Aaru.CommonTypes.Interfaces;
using Aaru.Helpers;
#if NETCOREAPP3_1_OR_GREATER
using Ssse3 = System.Runtime.Intrinsics.X86.Ssse3;
#endif
using static Aaru.Helpers.Extensions;
namespace Aaru.Checksums;
/// <inheritdoc />
/// <summary>Implements the Adler-32 algorithm</summary>
[SuppressMessage("ReSharper", "UnusedMethodReturnValue.Global")]
public sealed class Adler32Context : IChecksum
{
internal const ushort ADLER_MODULE = 65521;
internal const uint NMAX = 5552;
readonly IntPtr _nativeContext;
readonly bool _useNative;
ushort _sum1, _sum2;
/// <summary>Initializes the Adler-32 sums</summary>
public Adler32Context()
{
_sum1 = 1;
_sum2 = 0;
if(!Native.IsSupported)
return;
_nativeContext = adler32_init();
_useNative = _nativeContext != IntPtr.Zero;
}
#region IChecksum Members
/// <inheritdoc />
public string Name => "Adler-32";
/// <inheritdoc />
public Guid Id => new("D69CF1E7-4A7B-4605-9291-3A1BE4C2951F");
/// <inheritdoc />
public string Author => "Natalia Portillo";
/// <inheritdoc />
/// <summary>Updates the hash with data.</summary>
/// <param name="data">Data buffer.</param>
/// <param name="len">Length of buffer to hash.</param>
public void Update(byte[] data, uint len) => Step(ref _sum1, ref _sum2, data, len, _useNative, _nativeContext);
/// <inheritdoc />
/// <summary>Updates the hash with data.</summary>
/// <param name="data">Data buffer.</param>
public void Update(byte[] data) => Update(data, (uint)data.Length);
/// <inheritdoc />
/// <summary>Returns a byte array of the hash value.</summary>
public byte[] Final()
{
var finalSum = (uint)(_sum2 << 16 | _sum1);
if(!_useNative)
return BigEndianBitConverter.GetBytes(finalSum);
adler32_final(_nativeContext, ref finalSum);
adler32_free(_nativeContext);
return BigEndianBitConverter.GetBytes(finalSum);
}
/// <inheritdoc />
/// <summary>Returns a hexadecimal representation of the hash value.</summary>
public string End()
{
var finalSum = (uint)(_sum2 << 16 | _sum1);
if(_useNative)
{
adler32_final(_nativeContext, ref finalSum);
adler32_free(_nativeContext);
}
var adlerOutput = new StringBuilder();
for(var i = 0; i < BigEndianBitConverter.GetBytes(finalSum).Length; i++)
adlerOutput.Append(BigEndianBitConverter.GetBytes(finalSum)[i].ToString("x2"));
return adlerOutput.ToString();
}
#endregion
[DllImport("libAaru.Checksums.Native", SetLastError = true)]
static extern IntPtr adler32_init();
[DllImport("libAaru.Checksums.Native", SetLastError = true)]
static extern int adler32_update(IntPtr ctx, byte[] data, uint len);
[DllImport("libAaru.Checksums.Native", SetLastError = true)]
static extern int adler32_final(IntPtr ctx, ref uint checksum);
[DllImport("libAaru.Checksums.Native", SetLastError = true)]
static extern void adler32_free(IntPtr ctx);
static void Step(ref ushort preSum1, ref ushort preSum2, byte[] data, uint len, bool useNative,
IntPtr nativeContext)
{
if(useNative)
{
adler32_update(nativeContext, data, len);
return;
}
#if NETCOREAPP3_1_OR_GREATER
if(Ssse3.IsSupported)
{
Adler32.Ssse3.Step(ref preSum1, ref preSum2, data, len);
return;
}
#endif
#if NET5_0_OR_GREATER
if(AdvSimd.IsSupported)
{
Neon.Step(ref preSum1, ref preSum2, data, len);
return;
}
#endif
uint sum1 = preSum1;
uint sum2 = preSum2;
var dataOff = 0;
switch(len)
{
/* in case user likes doing a byte at a time, keep it fast */
case 1:
{
sum1 += data[dataOff];
if(sum1 >= ADLER_MODULE)
sum1 -= ADLER_MODULE;
sum2 += sum1;
if(sum2 >= ADLER_MODULE)
sum2 -= ADLER_MODULE;
preSum1 = (ushort)(sum1 & 0xFFFF);
preSum2 = (ushort)(sum2 & 0xFFFF);
return;
}
/* in case short lengths are provided, keep it somewhat fast */
case < 16:
{
while(len-- > 0)
{
sum1 += data[dataOff++];
sum2 += sum1;
}
if(sum1 >= ADLER_MODULE)
sum1 -= ADLER_MODULE;
sum2 %= ADLER_MODULE; /* only added so many ADLER_MODULE's */
preSum1 = (ushort)(sum1 & 0xFFFF);
preSum2 = (ushort)(sum2 & 0xFFFF);
return;
}
}
/* do length NMAX blocks -- requires just one modulo operation */
while(len >= NMAX)
{
len -= NMAX;
uint n = NMAX / 16;
do
{
sum1 += data[dataOff];
sum2 += sum1;
sum1 += data[dataOff + 1];
sum2 += sum1;
sum1 += data[dataOff + 2];
sum2 += sum1;
sum1 += data[dataOff + 2 + 1];
sum2 += sum1;
sum1 += data[dataOff + 4];
sum2 += sum1;
sum1 += data[dataOff + 4 + 1];
sum2 += sum1;
sum1 += data[dataOff + 4 + 2];
sum2 += sum1;
sum1 += data[dataOff + 4 + 2 + 1];
sum2 += sum1;
sum1 += data[dataOff + 8];
sum2 += sum1;
sum1 += data[dataOff + 8 + 1];
sum2 += sum1;
sum1 += data[dataOff + 8 + 2];
sum2 += sum1;
sum1 += data[dataOff + 8 + 2 + 1];
sum2 += sum1;
sum1 += data[dataOff + 8 + 4];
sum2 += sum1;
sum1 += data[dataOff + 8 + 4 + 1];
sum2 += sum1;
sum1 += data[dataOff + 8 + 4 + 2];
sum2 += sum1;
sum1 += data[dataOff + 8 + 4 + 2 + 1];
sum2 += sum1;
/* 16 sums unrolled */
dataOff += 16;
} while(--n != 0);
sum1 %= ADLER_MODULE;
sum2 %= ADLER_MODULE;
}
/* do remaining bytes (less than NMAX, still just one modulo) */
if(len != 0)
{
/* avoid modulos if none remaining */
while(len >= 16)
{
len -= 16;
sum1 += data[dataOff];
sum2 += sum1;
sum1 += data[dataOff + 1];
sum2 += sum1;
sum1 += data[dataOff + 2];
sum2 += sum1;
sum1 += data[dataOff + 2 + 1];
sum2 += sum1;
sum1 += data[dataOff + 4];
sum2 += sum1;
sum1 += data[dataOff + 4 + 1];
sum2 += sum1;
sum1 += data[dataOff + 4 + 2];
sum2 += sum1;
sum1 += data[dataOff + 4 + 2 + 1];
sum2 += sum1;
sum1 += data[dataOff + 8];
sum2 += sum1;
sum1 += data[dataOff + 8 + 1];
sum2 += sum1;
sum1 += data[dataOff + 8 + 2];
sum2 += sum1;
sum1 += data[dataOff + 8 + 2 + 1];
sum2 += sum1;
sum1 += data[dataOff + 8 + 4];
sum2 += sum1;
sum1 += data[dataOff + 8 + 4 + 1];
sum2 += sum1;
sum1 += data[dataOff + 8 + 4 + 2];
sum2 += sum1;
sum1 += data[dataOff + 8 + 4 + 2 + 1];
sum2 += sum1;
dataOff += 16;
}
while(len-- != 0)
{
sum1 += data[dataOff++];
sum2 += sum1;
}
sum1 %= ADLER_MODULE;
sum2 %= ADLER_MODULE;
}
preSum1 = (ushort)(sum1 & 0xFFFF);
preSum2 = (ushort)(sum2 & 0xFFFF);
}
/// <summary>Gets the hash of a file</summary>
/// <param name="filename">File path.</param>
public static byte[] File(string filename)
{
File(filename, out byte[] hash);
return hash;
}
/// <summary>Gets the hash of a file in hexadecimal and as a byte array.</summary>
/// <param name="filename">File path.</param>
/// <param name="hash">Byte array of the hash value.</param>
public static string File(string filename, out byte[] hash)
{
bool useNative = Native.IsSupported;
IntPtr nativeContext = IntPtr.Zero;
if(useNative)
{
nativeContext = adler32_init();
if(nativeContext == IntPtr.Zero)
useNative = false;
}
var fileStream = new FileStream(filename, FileMode.Open);
ushort localSum1 = 1;
ushort localSum2 = 0;
var buffer = new byte[65536];
int read = EnsureRead(fileStream, buffer, 0, 65536);
while(read > 0)
{
Step(ref localSum1, ref localSum2, buffer, (uint)read, useNative, nativeContext);
read = EnsureRead(fileStream, buffer, 0, 65536);
}
var finalSum = (uint)(localSum2 << 16 | localSum1);
if(useNative)
{
adler32_final(nativeContext, ref finalSum);
adler32_free(nativeContext);
}
hash = BigEndianBitConverter.GetBytes(finalSum);
var adlerOutput = new StringBuilder();
foreach(byte h in hash)
adlerOutput.Append(h.ToString("x2"));
fileStream.Close();
return adlerOutput.ToString();
}
/// <summary>Gets the hash of the specified data buffer.</summary>
/// <param name="data">Data buffer.</param>
/// <param name="len">Length of the data buffer to hash.</param>
/// <param name="hash">Byte array of the hash value.</param>
public static string Data(byte[] data, uint len, out byte[] hash)
{
bool useNative = Native.IsSupported;
IntPtr nativeContext = IntPtr.Zero;
if(useNative)
{
nativeContext = adler32_init();
if(nativeContext == IntPtr.Zero)
useNative = false;
}
ushort localSum1 = 1;
ushort localSum2 = 0;
Step(ref localSum1, ref localSum2, data, len, useNative, nativeContext);
var finalSum = (uint)(localSum2 << 16 | localSum1);
if(useNative)
{
adler32_final(nativeContext, ref finalSum);
adler32_free(nativeContext);
}
hash = BigEndianBitConverter.GetBytes(finalSum);
var adlerOutput = new StringBuilder();
foreach(byte h in hash)
adlerOutput.Append(h.ToString("x2"));
return adlerOutput.ToString();
}
/// <summary>Gets the hash of the specified data buffer.</summary>
/// <param name="data">Data buffer.</param>
/// <param name="hash">Byte array of the hash value.</param>
public static string Data(byte[] data, out byte[] hash) => Data(data, (uint)data.Length, out hash);
}

View File

@@ -1,219 +0,0 @@
// /***************************************************************************
// Aaru Data Preservation Suite
// ----------------------------------------------------------------------------
//
// Filename : neon.cs
// Author(s) : Natalia Portillo <claunia@claunia.com>
// The Chromium Authors
//
// Component : Checksums.
//
// --[ Description ] ----------------------------------------------------------
//
// Compute Fletcher32 checksum using NEON vectorization.
//
// --[ License ] --------------------------------------------------------------
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// ----------------------------------------------------------------------------
// Copyright © 2011-2023 Natalia Portillo
// Copyright 2017 The Chromium Authors. All rights reserved.
// ****************************************************************************/
#if NET5_0_OR_GREATER
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.Arm;
namespace Aaru.Checksums.Fletcher32;
static class Neon
{
internal static void Step(ref ushort preSum1, ref ushort preSum2, byte[] buf, uint len)
{
/*
* Split Fletcher-32 into component sums.
*/
uint s1 = preSum1;
uint s2 = preSum2;
var bufPos = 0;
/*
* Process the data in blocks.
*/
const uint block_Size = 1 << 5;
uint blocks = len / block_Size;
len -= blocks * block_Size;
while(blocks != 0)
{
uint n = Fletcher32Context.NMAX / block_Size; /* The NMAX constraint. */
if(n > blocks)
n = blocks;
blocks -= n;
/*
* Process n blocks of data. At most NMAX data bytes can be
* processed before s2 must be reduced modulo FLETCHER_MODULE.
*/
var v_S2 = Vector128.Create(s1 * n, 0, 0, 0);
var v_S1 = Vector128.Create(0u, 0, 0, 0);
Vector128<ushort> v_Column_Sum_1 = AdvSimd.DuplicateToVector128((ushort)0);
Vector128<ushort> v_Column_Sum_2 = AdvSimd.DuplicateToVector128((ushort)0);
Vector128<ushort> v_Column_Sum_3 = AdvSimd.DuplicateToVector128((ushort)0);
Vector128<ushort> v_Column_Sum_4 = AdvSimd.DuplicateToVector128((ushort)0);
do
{
/*
* Load 32 input bytes.
*/
var bytes1 = Vector128.Create(buf[bufPos], buf[bufPos + 1], buf[bufPos + 2], buf[bufPos + 3],
buf[bufPos + 4], buf[bufPos + 5], buf[bufPos + 6], buf[bufPos + 7],
buf[bufPos + 8], buf[bufPos + 9], buf[bufPos + 10], buf[bufPos + 11],
buf[bufPos + 12], buf[bufPos + 13], buf[bufPos + 14], buf[bufPos + 15]);
bufPos += 16;
var bytes2 = Vector128.Create(buf[bufPos], buf[bufPos + 1], buf[bufPos + 2], buf[bufPos + 3],
buf[bufPos + 4], buf[bufPos + 5], buf[bufPos + 6], buf[bufPos + 7],
buf[bufPos + 8], buf[bufPos + 9], buf[bufPos + 10], buf[bufPos + 11],
buf[bufPos + 12], buf[bufPos + 13], buf[bufPos + 14], buf[bufPos + 15]);
bufPos += 16;
/*
* Add previous block byte sum to v_s2.
*/
v_S2 = AdvSimd.Add(v_S2, v_S1);
/*
* Horizontally add the bytes for s1.
*/
v_S1 =
AdvSimd.AddPairwiseWideningAndAdd(v_S1,
AdvSimd.
AddPairwiseWideningAndAdd(AdvSimd.AddPairwiseWidening(bytes1),
bytes2));
/*
* Vertically add the bytes for s2.
*/
v_Column_Sum_1 = AdvSimd.AddWideningLower(v_Column_Sum_1, bytes1.GetLower());
v_Column_Sum_2 = AdvSimd.AddWideningLower(v_Column_Sum_2, bytes1.GetUpper());
v_Column_Sum_3 = AdvSimd.AddWideningLower(v_Column_Sum_3, bytes2.GetLower());
v_Column_Sum_4 = AdvSimd.AddWideningLower(v_Column_Sum_4, bytes2.GetUpper());
} while(--n != 0);
v_S2 = AdvSimd.ShiftLeftLogical(v_S2, 5);
/*
* Multiply-add bytes by [ 32, 31, 30, ... ] for s2.
*/
v_S2 = AdvSimd.MultiplyWideningLowerAndAdd(v_S2, v_Column_Sum_1.GetLower(),
Vector64.Create((ushort)32, 31, 30, 29));
v_S2 = AdvSimd.MultiplyWideningLowerAndAdd(v_S2, v_Column_Sum_1.GetUpper(),
Vector64.Create((ushort)28, 27, 26, 25));
v_S2 = AdvSimd.MultiplyWideningLowerAndAdd(v_S2, v_Column_Sum_2.GetLower(),
Vector64.Create((ushort)24, 23, 22, 21));
v_S2 = AdvSimd.MultiplyWideningLowerAndAdd(v_S2, v_Column_Sum_2.GetUpper(),
Vector64.Create((ushort)20, 19, 18, 17));
v_S2 = AdvSimd.MultiplyWideningLowerAndAdd(v_S2, v_Column_Sum_3.GetLower(),
Vector64.Create((ushort)16, 15, 14, 13));
v_S2 = AdvSimd.MultiplyWideningLowerAndAdd(v_S2, v_Column_Sum_3.GetUpper(),
Vector64.Create((ushort)12, 11, 10, 9));
v_S2 = AdvSimd.MultiplyWideningLowerAndAdd(v_S2, v_Column_Sum_4.GetLower(),
Vector64.Create((ushort)8, 7, 6, 5));
v_S2 = AdvSimd.MultiplyWideningLowerAndAdd(v_S2, v_Column_Sum_4.GetUpper(),
Vector64.Create((ushort)4, 3, 2, 1));
/*
* Sum epi32 ints v_s1(s2) and accumulate in s1(s2).
*/
Vector64<uint> sum1 = AdvSimd.AddPairwise(v_S1.GetLower(), v_S1.GetUpper());
Vector64<uint> sum2 = AdvSimd.AddPairwise(v_S2.GetLower(), v_S2.GetUpper());
Vector64<uint> s1S2 = AdvSimd.AddPairwise(sum1, sum2);
s1 += AdvSimd.Extract(s1S2, 0);
s2 += AdvSimd.Extract(s1S2, 1);
/*
* Reduce.
*/
s1 %= Fletcher32Context.FLETCHER_MODULE;
s2 %= Fletcher32Context.FLETCHER_MODULE;
}
/*
* Handle leftover data.
*/
if(len != 0)
{
if(len >= 16)
{
s2 += s1 += buf[bufPos++];
s2 += s1 += buf[bufPos++];
s2 += s1 += buf[bufPos++];
s2 += s1 += buf[bufPos++];
s2 += s1 += buf[bufPos++];
s2 += s1 += buf[bufPos++];
s2 += s1 += buf[bufPos++];
s2 += s1 += buf[bufPos++];
s2 += s1 += buf[bufPos++];
s2 += s1 += buf[bufPos++];
s2 += s1 += buf[bufPos++];
s2 += s1 += buf[bufPos++];
s2 += s1 += buf[bufPos++];
s2 += s1 += buf[bufPos++];
s2 += s1 += buf[bufPos++];
s2 += s1 += buf[bufPos++];
len -= 16;
}
while(len-- != 0)
s2 += s1 += buf[bufPos++];
if(s1 >= Fletcher32Context.FLETCHER_MODULE)
s1 -= Fletcher32Context.FLETCHER_MODULE;
s2 %= Fletcher32Context.FLETCHER_MODULE;
}
/*
* Return the recombined sums.
*/
preSum1 = (ushort)(s1 & 0xFFFF);
preSum2 = (ushort)(s2 & 0xFFFF);
}
}
#endif

View File

@@ -1,193 +0,0 @@
// /***************************************************************************
// Aaru Data Preservation Suite
// ----------------------------------------------------------------------------
//
// Filename : ssse3.cs
// Author(s) : Natalia Portillo <claunia@claunia.com>
// The Chromium Authors
//
// Component : Checksums.
//
// --[ Description ] ----------------------------------------------------------
//
// Compute Fletcher32 checksum using SSSE3 vectorization.
//
// --[ License ] --------------------------------------------------------------
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// ----------------------------------------------------------------------------
// Copyright © 2011-2023 Natalia Portillo
// Copyright 2017 The Chromium Authors. All rights reserved.
// ****************************************************************************/
#if NETCOREAPP3_1_OR_GREATER
using System;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.X86;
namespace Aaru.Checksums.Fletcher32;
static class Ssse3
{
internal static void Step(ref ushort sum1, ref ushort sum2, byte[] buf, uint len)
{
uint s1 = sum1;
uint s2 = sum2;
var bufPos = 0;
/*
* Process the data in blocks.
*/
const uint block_Size = 1 << 5;
uint blocks = len / block_Size;
len -= blocks * block_Size;
while(blocks != 0)
{
uint n = Fletcher32Context.NMAX / block_Size; /* The NMAX constraint. */
if(n > blocks)
n = blocks;
blocks -= n;
Vector128<byte> tap1 = Vector128.Create(32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17).
AsByte();
Vector128<byte> tap2 = Vector128.Create(16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1).AsByte();
Vector128<byte> zero = Vector128.Create(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0).AsByte();
var ones = Vector128.Create(1, 1, 1, 1, 1, 1, 1, 1);
/*
* Process n blocks of data. At most NMAX data bytes can be
* processed before s2 must be reduced modulo BASE.
*/
var v_Ps = Vector128.Create(s1 * n, 0, 0, 0);
var v_S2 = Vector128.Create(s2, 0, 0, 0);
var v_S1 = Vector128.Create(0u, 0, 0, 0);
do
{
/*
* Load 32 input bytes.
*/
var bytes1 = Vector128.Create(BitConverter.ToUInt32(buf, bufPos),
BitConverter.ToUInt32(buf, bufPos + 4),
BitConverter.ToUInt32(buf, bufPos + 8),
BitConverter.ToUInt32(buf, bufPos + 12));
bufPos += 16;
var bytes2 = Vector128.Create(BitConverter.ToUInt32(buf, bufPos),
BitConverter.ToUInt32(buf, bufPos + 4),
BitConverter.ToUInt32(buf, bufPos + 8),
BitConverter.ToUInt32(buf, bufPos + 12));
bufPos += 16;
/*
* Add previous block byte sum to v_ps.
*/
v_Ps = Sse2.Add(v_Ps, v_S1);
/*
* Horizontally add the bytes for s1, multiply-adds the
* bytes by [ 32, 31, 30, ... ] for s2.
*/
v_S1 = Sse2.Add(v_S1, Sse2.SumAbsoluteDifferences(bytes1.AsByte(), zero).AsUInt32());
Vector128<short> mad1 =
System.Runtime.Intrinsics.X86.Ssse3.MultiplyAddAdjacent(bytes1.AsByte(), tap1.AsSByte());
v_S2 = Sse2.Add(v_S2, Sse2.MultiplyAddAdjacent(mad1.AsInt16(), ones.AsInt16()).AsUInt32());
v_S1 = Sse2.Add(v_S1, Sse2.SumAbsoluteDifferences(bytes2.AsByte(), zero).AsUInt32());
Vector128<short> mad2 =
System.Runtime.Intrinsics.X86.Ssse3.MultiplyAddAdjacent(bytes2.AsByte(), tap2.AsSByte());
v_S2 = Sse2.Add(v_S2, Sse2.MultiplyAddAdjacent(mad2.AsInt16(), ones.AsInt16()).AsUInt32());
} while(--n != 0);
v_S2 = Sse2.Add(v_S2, Sse2.ShiftLeftLogical(v_Ps, 5));
/*
* Sum epi32 ints v_s1(s2) and accumulate in s1(s2).
*/
v_S1 = Sse2.Add(v_S1, Sse2.Shuffle(v_S1, 177));
v_S1 = Sse2.Add(v_S1, Sse2.Shuffle(v_S1, 78));
s1 += (uint)Sse2.ConvertToInt32(v_S1.AsInt32());
v_S2 = Sse2.Add(v_S2, Sse2.Shuffle(v_S2, 177));
v_S2 = Sse2.Add(v_S2, Sse2.Shuffle(v_S2, 78));
s2 = (uint)Sse2.ConvertToInt32(v_S2.AsInt32());
/*
* Reduce.
*/
s1 %= Fletcher32Context.FLETCHER_MODULE;
s2 %= Fletcher32Context.FLETCHER_MODULE;
}
/*
* Handle leftover data.
*/
if(len != 0)
{
if(len >= 16)
{
s2 += s1 += buf[bufPos++];
s2 += s1 += buf[bufPos++];
s2 += s1 += buf[bufPos++];
s2 += s1 += buf[bufPos++];
s2 += s1 += buf[bufPos++];
s2 += s1 += buf[bufPos++];
s2 += s1 += buf[bufPos++];
s2 += s1 += buf[bufPos++];
s2 += s1 += buf[bufPos++];
s2 += s1 += buf[bufPos++];
s2 += s1 += buf[bufPos++];
s2 += s1 += buf[bufPos++];
s2 += s1 += buf[bufPos++];
s2 += s1 += buf[bufPos++];
s2 += s1 += buf[bufPos++];
s2 += s1 += buf[bufPos++];
len -= 16;
}
while(len-- != 0)
s2 += s1 += buf[bufPos++];
if(s1 >= Fletcher32Context.FLETCHER_MODULE)
s1 -= Fletcher32Context.FLETCHER_MODULE;
s2 %= Fletcher32Context.FLETCHER_MODULE;
}
/*
* Return the recombined sums.
*/
sum1 = (ushort)(s1 & 0xFFFF);
sum2 = (ushort)(s2 & 0xFFFF);
}
}
#endif

View File

@@ -1,778 +0,0 @@
// /***************************************************************************
// Aaru Data Preservation Suite
// ----------------------------------------------------------------------------
//
// Filename : FletcherContext.cs
// Author(s) : Natalia Portillo <claunia@claunia.com>
//
// Component : Checksums.
//
// --[ Description ] ----------------------------------------------------------
//
// Implements Fletcher-32 and Fletcher-16 algorithms.
//
// --[ License ] --------------------------------------------------------------
//
// This library is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as
// published by the Free Software Foundation; either version 2.1 of the
// License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, see <http://www.gnu.org/licenses/>.
//
// ----------------------------------------------------------------------------
// Copyright © 2011-2023 Natalia Portillo
// ****************************************************************************/
// Disabled because the speed is abnormally slow
using System;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Runtime.InteropServices;
#if NET5_0_OR_GREATER
using System.Runtime.Intrinsics.Arm;
#endif
using System.Text;
#if NETCOREAPP3_1_OR_GREATER
using Aaru.Checksums.Fletcher32;
#endif
using Aaru.CommonTypes.Interfaces;
using Aaru.Helpers;
#if NETCOREAPP3_1_OR_GREATER
using Ssse3 = System.Runtime.Intrinsics.X86.Ssse3;
#endif
using static Aaru.Helpers.Extensions;
namespace Aaru.Checksums;
/// <inheritdoc />
/// <summary>Implements the Fletcher-32 algorithm</summary>
[SuppressMessage("ReSharper", "UnusedMethodReturnValue.Global")]
[SuppressMessage("ReSharper", "MemberCanBePrivate.Global")]
[SuppressMessage("ReSharper", "UnusedMember.Global")]
public sealed class Fletcher32Context : IChecksum
{
internal const ushort FLETCHER_MODULE = 0xFFFF;
internal const uint NMAX = 5552;
readonly IntPtr _nativeContext;
readonly bool _useNative;
ushort _sum1, _sum2;
/// <summary>Initializes the Fletcher-32 sums</summary>
public Fletcher32Context()
{
_sum1 = 0xFFFF;
_sum2 = 0xFFFF;
if(!Native.IsSupported)
return;
_nativeContext = fletcher32_init();
_useNative = _nativeContext != IntPtr.Zero;
}
#region IChecksum Members
/// <inheritdoc />
public string Name => "Fletcher-32";
/// <inheritdoc />
public Guid Id => new("0E51B39F-C5E6-4CED-9E59-BA5A42B3B2F4");
/// <inheritdoc />
public string Author => "Natalia Portillo";
/// <inheritdoc />
/// <summary>Updates the hash with data.</summary>
/// <param name="data">Data buffer.</param>
/// <param name="len">Length of buffer to hash.</param>
public void Update(byte[] data, uint len) => Step(ref _sum1, ref _sum2, data, len, _useNative, _nativeContext);
/// <inheritdoc />
/// <summary>Updates the hash with data.</summary>
/// <param name="data">Data buffer.</param>
public void Update(byte[] data) => Update(data, (uint)data.Length);
/// <inheritdoc />
/// <summary>Returns a byte array of the hash value.</summary>
public byte[] Final()
{
var finalSum = (uint)(_sum2 << 16 | _sum1);
if(!_useNative)
return BigEndianBitConverter.GetBytes(finalSum);
fletcher32_final(_nativeContext, ref finalSum);
fletcher32_free(_nativeContext);
return BigEndianBitConverter.GetBytes(finalSum);
}
/// <inheritdoc />
/// <summary>Returns a hexadecimal representation of the hash value.</summary>
public string End()
{
var finalSum = (uint)(_sum2 << 16 | _sum1);
if(_useNative)
{
fletcher32_final(_nativeContext, ref finalSum);
fletcher32_free(_nativeContext);
}
var fletcherOutput = new StringBuilder();
for(var i = 0; i < BigEndianBitConverter.GetBytes(finalSum).Length; i++)
fletcherOutput.Append(BigEndianBitConverter.GetBytes(finalSum)[i].ToString("x2"));
return fletcherOutput.ToString();
}
#endregion
[DllImport("libAaru.Checksums.Native", SetLastError = true)]
static extern IntPtr fletcher32_init();
[DllImport("libAaru.Checksums.Native", SetLastError = true)]
static extern int fletcher32_update(IntPtr ctx, byte[] data, uint len);
[DllImport("libAaru.Checksums.Native", SetLastError = true)]
static extern int fletcher32_final(IntPtr ctx, ref uint crc);
[DllImport("libAaru.Checksums.Native", SetLastError = true)]
static extern void fletcher32_free(IntPtr ctx);
static void Step(ref ushort previousSum1, ref ushort previousSum2, byte[] data, uint len, bool useNative,
IntPtr nativeContext)
{
if(useNative)
{
fletcher32_update(nativeContext, data, len);
return;
}
#if NETCOREAPP3_1_OR_GREATER
if(Ssse3.IsSupported)
{
Fletcher32.Ssse3.Step(ref previousSum1, ref previousSum2, data, len);
return;
}
#endif
#if NET5_0_OR_GREATER
if(AdvSimd.IsSupported)
{
Neon.Step(ref previousSum1, ref previousSum2, data, len);
return;
}
#endif
uint sum1 = previousSum1;
uint sum2 = previousSum2;
var dataOff = 0;
switch(len)
{
/* in case user likes doing a byte at a time, keep it fast */
case 1:
{
sum1 += data[dataOff];
if(sum1 >= FLETCHER_MODULE)
sum1 -= FLETCHER_MODULE;
sum2 += sum1;
if(sum2 >= FLETCHER_MODULE)
sum2 -= FLETCHER_MODULE;
previousSum1 = (ushort)(sum1 & 0xFFFF);
previousSum2 = (ushort)(sum2 & 0xFFFF);
return;
}
/* in case short lengths are provided, keep it somewhat fast */
case < 16:
{
while(len-- > 0)
{
sum1 += data[dataOff++];
sum2 += sum1;
}
if(sum1 >= FLETCHER_MODULE)
sum1 -= FLETCHER_MODULE;
sum2 %= FLETCHER_MODULE; /* only added so many FLETCHER_MODULE's */
previousSum1 = (ushort)(sum1 & 0xFFFF);
previousSum2 = (ushort)(sum2 & 0xFFFF);
return;
}
}
/* do length NMAX blocks -- requires just one modulo operation */
while(len >= NMAX)
{
len -= NMAX;
uint n = NMAX / 16;
do
{
sum1 += data[dataOff];
sum2 += sum1;
sum1 += data[dataOff + 1];
sum2 += sum1;
sum1 += data[dataOff + 2];
sum2 += sum1;
sum1 += data[dataOff + 2 + 1];
sum2 += sum1;
sum1 += data[dataOff + 4];
sum2 += sum1;
sum1 += data[dataOff + 4 + 1];
sum2 += sum1;
sum1 += data[dataOff + 4 + 2];
sum2 += sum1;
sum1 += data[dataOff + 4 + 2 + 1];
sum2 += sum1;
sum1 += data[dataOff + 8];
sum2 += sum1;
sum1 += data[dataOff + 8 + 1];
sum2 += sum1;
sum1 += data[dataOff + 8 + 2];
sum2 += sum1;
sum1 += data[dataOff + 8 + 2 + 1];
sum2 += sum1;
sum1 += data[dataOff + 8 + 4];
sum2 += sum1;
sum1 += data[dataOff + 8 + 4 + 1];
sum2 += sum1;
sum1 += data[dataOff + 8 + 4 + 2];
sum2 += sum1;
sum1 += data[dataOff + 8 + 4 + 2 + 1];
sum2 += sum1;
/* 16 sums unrolled */
dataOff += 16;
} while(--n != 0);
sum1 %= FLETCHER_MODULE;
sum2 %= FLETCHER_MODULE;
}
/* do remaining bytes (less than NMAX, still just one modulo) */
if(len != 0)
{
/* avoid modulos if none remaining */
while(len >= 16)
{
len -= 16;
sum1 += data[dataOff];
sum2 += sum1;
sum1 += data[dataOff + 1];
sum2 += sum1;
sum1 += data[dataOff + 2];
sum2 += sum1;
sum1 += data[dataOff + 2 + 1];
sum2 += sum1;
sum1 += data[dataOff + 4];
sum2 += sum1;
sum1 += data[dataOff + 4 + 1];
sum2 += sum1;
sum1 += data[dataOff + 4 + 2];
sum2 += sum1;
sum1 += data[dataOff + 4 + 2 + 1];
sum2 += sum1;
sum1 += data[dataOff + 8];
sum2 += sum1;
sum1 += data[dataOff + 8 + 1];
sum2 += sum1;
sum1 += data[dataOff + 8 + 2];
sum2 += sum1;
sum1 += data[dataOff + 8 + 2 + 1];
sum2 += sum1;
sum1 += data[dataOff + 8 + 4];
sum2 += sum1;
sum1 += data[dataOff + 8 + 4 + 1];
sum2 += sum1;
sum1 += data[dataOff + 8 + 4 + 2];
sum2 += sum1;
sum1 += data[dataOff + 8 + 4 + 2 + 1];
sum2 += sum1;
dataOff += 16;
}
while(len-- != 0)
{
sum1 += data[dataOff++];
sum2 += sum1;
}
sum1 %= FLETCHER_MODULE;
sum2 %= FLETCHER_MODULE;
}
previousSum1 = (ushort)(sum1 & 0xFFFF);
previousSum2 = (ushort)(sum2 & 0xFFFF);
}
/// <summary>Gets the hash of a file</summary>
/// <param name="filename">File path.</param>
public static byte[] File(string filename)
{
File(filename, out byte[] hash);
return hash;
}
/// <summary>Gets the hash of a file in hexadecimal and as a byte array.</summary>
/// <param name="filename">File path.</param>
/// <param name="hash">Byte array of the hash value.</param>
public static string File(string filename, out byte[] hash)
{
bool useNative = Native.IsSupported;
IntPtr nativeContext = IntPtr.Zero;
if(useNative)
{
nativeContext = fletcher32_init();
if(nativeContext == IntPtr.Zero)
useNative = false;
}
var fileStream = new FileStream(filename, FileMode.Open);
ushort localSum1 = 0xFFFF;
ushort localSum2 = 0xFFFF;
var buffer = new byte[65536];
int read = EnsureRead(fileStream, buffer, 0, 65536);
while(read > 0)
{
Step(ref localSum1, ref localSum2, buffer, (uint)read, useNative, nativeContext);
read = EnsureRead(fileStream, buffer, 0, 65536);
}
var finalSum = (uint)(localSum2 << 16 | localSum1);
if(useNative)
{
fletcher32_final(nativeContext, ref finalSum);
fletcher32_free(nativeContext);
}
hash = BigEndianBitConverter.GetBytes(finalSum);
var fletcherOutput = new StringBuilder();
foreach(byte h in hash)
fletcherOutput.Append(h.ToString("x2"));
fileStream.Close();
return fletcherOutput.ToString();
}
/// <summary>Gets the hash of the specified data buffer.</summary>
/// <param name="data">Data buffer.</param>
/// <param name="len">Length of the data buffer to hash.</param>
/// <param name="hash">Byte array of the hash value.</param>
public static string Data(byte[] data, uint len, out byte[] hash)
{
bool useNative = Native.IsSupported;
IntPtr nativeContext = IntPtr.Zero;
if(useNative)
{
nativeContext = fletcher32_init();
if(nativeContext == IntPtr.Zero)
useNative = false;
}
ushort localSum1 = 0xFFFF;
ushort localSum2 = 0xFFFF;
Step(ref localSum1, ref localSum2, data, len, useNative, nativeContext);
var finalSum = (uint)(localSum2 << 16 | localSum1);
if(useNative)
{
fletcher32_final(nativeContext, ref finalSum);
fletcher32_free(nativeContext);
}
hash = BigEndianBitConverter.GetBytes(finalSum);
var adlerOutput = new StringBuilder();
foreach(byte h in hash)
adlerOutput.Append(h.ToString("x2"));
return adlerOutput.ToString();
}
/// <summary>Gets the hash of the specified data buffer.</summary>
/// <param name="data">Data buffer.</param>
/// <param name="hash">Byte array of the hash value.</param>
public static string Data(byte[] data, out byte[] hash) => Data(data, (uint)data.Length, out hash);
}
/// <inheritdoc />
/// <summary>Implements the Fletcher-16 algorithm</summary>
[SuppressMessage("ReSharper", "UnusedMember.Global")]
[SuppressMessage("ReSharper", "MemberCanBePrivate.Global")]
[SuppressMessage("ReSharper", "UnusedMethodReturnValue.Global")]
public sealed class Fletcher16Context : IChecksum
{
const byte FLETCHER_MODULE = 0xFF;
const byte NMAX = 22;
readonly IntPtr _nativeContext;
readonly bool _useNative;
byte _sum1, _sum2;
/// <summary>Initializes the Fletcher-16 sums</summary>
public Fletcher16Context()
{
_sum1 = 0xFF;
_sum2 = 0xFF;
if(!Native.IsSupported)
return;
_nativeContext = fletcher16_init();
_useNative = _nativeContext != IntPtr.Zero;
}
#region IChecksum Members
/// <inheritdoc />
public string Name => "Fletcher-16";
/// <inheritdoc />
public Guid Id => new("80C51F1D-71F8-4741-A0CF-18FA8102EE4B");
/// <inheritdoc />
public string Author => "Natalia Portillo";
/// <inheritdoc />
/// <summary>Updates the hash with data.</summary>
/// <param name="data">Data buffer.</param>
/// <param name="len">Length of buffer to hash.</param>
public void Update(byte[] data, uint len) => Step(ref _sum1, ref _sum2, data, len, _useNative, _nativeContext);
/// <inheritdoc />
/// <summary>Updates the hash with data.</summary>
/// <param name="data">Data buffer.</param>
public void Update(byte[] data) => Update(data, (uint)data.Length);
/// <inheritdoc />
/// <summary>Returns a byte array of the hash value.</summary>
public byte[] Final()
{
var finalSum = (ushort)(_sum2 << 8 | _sum1);
if(!_useNative)
return BigEndianBitConverter.GetBytes(finalSum);
fletcher16_final(_nativeContext, ref finalSum);
fletcher16_free(_nativeContext);
return BigEndianBitConverter.GetBytes(finalSum);
}
/// <inheritdoc />
/// <summary>Returns a hexadecimal representation of the hash value.</summary>
public string End()
{
var finalSum = (ushort)(_sum2 << 8 | _sum1);
if(_useNative)
{
fletcher16_final(_nativeContext, ref finalSum);
fletcher16_free(_nativeContext);
}
var fletcherOutput = new StringBuilder();
for(var i = 0; i < BigEndianBitConverter.GetBytes(finalSum).Length; i++)
fletcherOutput.Append(BigEndianBitConverter.GetBytes(finalSum)[i].ToString("x2"));
return fletcherOutput.ToString();
}
#endregion
[DllImport("libAaru.Checksums.Native", SetLastError = true)]
static extern IntPtr fletcher16_init();
[DllImport("libAaru.Checksums.Native", SetLastError = true)]
static extern int fletcher16_update(IntPtr ctx, byte[] data, uint len);
[DllImport("libAaru.Checksums.Native", SetLastError = true)]
static extern int fletcher16_final(IntPtr ctx, ref ushort checksum);
[DllImport("libAaru.Checksums.Native", SetLastError = true)]
static extern void fletcher16_free(IntPtr ctx);
static void Step(ref byte previousSum1, ref byte previousSum2, byte[] data, uint len, bool useNative,
IntPtr nativeContext)
{
if(useNative)
{
fletcher16_update(nativeContext, data, len);
return;
}
uint sum1 = previousSum1;
uint sum2 = previousSum2;
var dataOff = 0;
switch(len)
{
/* in case user likes doing a byte at a time, keep it fast */
case 1:
{
sum1 += data[dataOff];
if(sum1 >= FLETCHER_MODULE)
sum1 -= FLETCHER_MODULE;
sum2 += sum1;
if(sum2 >= FLETCHER_MODULE)
sum2 -= FLETCHER_MODULE;
previousSum1 = (byte)(sum1 & 0xFF);
previousSum2 = (byte)(sum2 & 0xFF);
return;
}
/* in case short lengths are provided, keep it somewhat fast */
case < 11:
{
while(len-- > 0)
{
sum1 += data[dataOff++];
sum2 += sum1;
}
if(sum1 >= FLETCHER_MODULE)
sum1 -= FLETCHER_MODULE;
sum2 %= FLETCHER_MODULE; /* only added so many FLETCHER_MODULE's */
previousSum1 = (byte)(sum1 & 0xFF);
previousSum2 = (byte)(sum2 & 0xFF);
return;
}
}
/* do length NMAX blocks -- requires just one modulo operation */
while(len >= NMAX)
{
len -= NMAX;
uint n = NMAX / 11;
do
{
sum1 += data[dataOff];
sum2 += sum1;
sum1 += data[dataOff + 1];
sum2 += sum1;
sum1 += data[dataOff + 2];
sum2 += sum1;
sum1 += data[dataOff + 2 + 1];
sum2 += sum1;
sum1 += data[dataOff + 4];
sum2 += sum1;
sum1 += data[dataOff + 4 + 1];
sum2 += sum1;
sum1 += data[dataOff + 4 + 2];
sum2 += sum1;
sum1 += data[dataOff + 4 + 2 + 1];
sum2 += sum1;
sum1 += data[dataOff + 8];
sum2 += sum1;
sum1 += data[dataOff + 8 + 1];
sum2 += sum1;
sum1 += data[dataOff + 8 + 2];
sum2 += sum1;
/* 11 sums unrolled */
dataOff += 11;
} while(--n != 0);
sum1 %= FLETCHER_MODULE;
sum2 %= FLETCHER_MODULE;
}
/* do remaining bytes (less than NMAX, still just one modulo) */
if(len != 0)
{
/* avoid modulos if none remaining */
while(len >= 11)
{
len -= 11;
sum1 += data[dataOff];
sum2 += sum1;
sum1 += data[dataOff + 1];
sum2 += sum1;
sum1 += data[dataOff + 2];
sum2 += sum1;
sum1 += data[dataOff + 2 + 1];
sum2 += sum1;
sum1 += data[dataOff + 4];
sum2 += sum1;
sum1 += data[dataOff + 4 + 1];
sum2 += sum1;
sum1 += data[dataOff + 4 + 2];
sum2 += sum1;
sum1 += data[dataOff + 4 + 2 + 1];
sum2 += sum1;
sum1 += data[dataOff + 8];
sum2 += sum1;
sum1 += data[dataOff + 8 + 1];
sum2 += sum1;
sum1 += data[dataOff + 8 + 2];
sum2 += sum1;
dataOff += 11;
}
while(len-- != 0)
{
sum1 += data[dataOff++];
sum2 += sum1;
}
sum1 %= FLETCHER_MODULE;
sum2 %= FLETCHER_MODULE;
}
previousSum1 = (byte)(sum1 & 0xFF);
previousSum2 = (byte)(sum2 & 0xFF);
}
/// <summary>Gets the hash of a file</summary>
/// <param name="filename">File path.</param>
public static byte[] File(string filename)
{
File(filename, out byte[] hash);
return hash;
}
/// <summary>Gets the hash of a file in hexadecimal and as a byte array.</summary>
/// <param name="filename">File path.</param>
/// <param name="hash">Byte array of the hash value.</param>
public static string File(string filename, out byte[] hash)
{
bool useNative = Native.IsSupported;
IntPtr nativeContext = IntPtr.Zero;
if(useNative)
{
nativeContext = fletcher16_init();
if(nativeContext == IntPtr.Zero)
useNative = false;
}
var fileStream = new FileStream(filename, FileMode.Open);
byte localSum1 = 0xFF;
byte localSum2 = 0xFF;
var buffer = new byte[65536];
int read = EnsureRead(fileStream, buffer, 0, 65536);
while(read > 0)
{
Step(ref localSum1, ref localSum2, buffer, (uint)read, useNative, nativeContext);
read = EnsureRead(fileStream, buffer, 0, 65536);
}
var finalSum = (ushort)(localSum2 << 8 | localSum1);
if(useNative)
{
fletcher16_final(nativeContext, ref finalSum);
fletcher16_free(nativeContext);
}
hash = BigEndianBitConverter.GetBytes(finalSum);
var fletcherOutput = new StringBuilder();
foreach(byte h in hash)
fletcherOutput.Append(h.ToString("x2"));
fileStream.Close();
return fletcherOutput.ToString();
}
/// <summary>Gets the hash of the specified data buffer.</summary>
/// <param name="data">Data buffer.</param>
/// <param name="len">Length of the data buffer to hash.</param>
/// <param name="hash">Byte array of the hash value.</param>
public static string Data(byte[] data, uint len, out byte[] hash)
{
bool useNative = Native.IsSupported;
IntPtr nativeContext = IntPtr.Zero;
if(useNative)
{
nativeContext = fletcher16_init();
if(nativeContext == IntPtr.Zero)
useNative = false;
}
byte localSum1 = 0xFF;
byte localSum2 = 0xFF;
Step(ref localSum1, ref localSum2, data, len, useNative, nativeContext);
var finalSum = (ushort)(localSum2 << 8 | localSum1);
if(useNative)
{
fletcher16_final(nativeContext, ref finalSum);
fletcher16_free(nativeContext);
}
hash = BigEndianBitConverter.GetBytes(finalSum);
var adlerOutput = new StringBuilder();
foreach(byte h in hash)
adlerOutput.Append(h.ToString("x2"));
return adlerOutput.ToString();
}
/// <summary>Gets the hash of the specified data buffer.</summary>
/// <param name="data">Data buffer.</param>
/// <param name="hash">Byte array of the hash value.</param>
public static string Data(byte[] data, out byte[] hash) => Data(data, (uint)data.Length, out hash);
}

View File

@@ -1,83 +0,0 @@
// /***************************************************************************
// Aaru Data Preservation Suite
// ----------------------------------------------------------------------------
//
// Filename : Native.cs
// Author(s) : Natalia Portillo <claunia@claunia.com>
//
// Component : Checksums.
//
// --[ Description ] ----------------------------------------------------------
//
// Checks that Aaru.Checksums.Native library is available and usable.
//
// --[ License ] --------------------------------------------------------------
//
// This library is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as
// published by the Free Software Foundation; either version 2.1 of the
// License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, see <http://www.gnu.org/licenses/>.
//
// ----------------------------------------------------------------------------
// Copyright © 2011-2023 Natalia Portillo
// ****************************************************************************/
using System.Runtime.InteropServices;
namespace Aaru.Checksums;
/// <summary>Handles native implementations of compression algorithms</summary>
public static class Native
{
static bool _checked;
static bool _supported;
/// <summary>Set to return native as never supported</summary>
public static bool ForceManaged { get; set; }
/// <summary>
/// If set to <c>true</c> the native library was found and loaded correctly and its reported version is
/// compatible.
/// </summary>
public static bool IsSupported
{
get
{
if(ForceManaged)
return false;
if(_checked)
return _supported;
ulong version;
_checked = true;
try
{
version = get_acn_version();
}
catch
{
_supported = false;
return false;
}
// TODO: Check version compatibility
_supported = version >= 0x06000000;
return _supported;
}
}
[DllImport("libAaru.Checksums.Native", SetLastError = true)]
static extern ulong get_acn_version();
}

View File

@@ -1,579 +0,0 @@
// /***************************************************************************
// Aaru Data Preservation Suite
// ----------------------------------------------------------------------------
//
// Filename : SpamSumContext.cs
// Author(s) : Natalia Portillo <claunia@claunia.com>
//
// Component : Checksums.
//
// --[ Description ] ----------------------------------------------------------
//
// Implements the SpamSum fuzzy hashing algorithm.
//
// --[ License ] --------------------------------------------------------------
//
// This library is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as
// published by the Free Software Foundation; either version 2.1 of the
// License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, see <http://www.gnu.org/licenses/>.
//
// ----------------------------------------------------------------------------
// Copyright © 2011-2023 Natalia Portillo
// ****************************************************************************/
// Based on ssdeep
// Copyright (C) 2002 Andrew Tridgell <tridge@samba.org>
// Copyright (C) 2006 ManTech International Corporation
// Copyright (C) 2013 Helmut Grohne <helmut@subdivi.de>
//
// Earlier versions of this code were named fuzzy.c and can be found at:
// http://www.samba.org/ftp/unpacked/junkcode/spamsum/
// http://ssdeep.sf.net/
using System;
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
using System.Text;
using Aaru.CommonTypes.Interfaces;
namespace Aaru.Checksums;
/// <inheritdoc />
/// <summary>Implements the SpamSum fuzzy hashing algorithm.</summary>
[SuppressMessage("ReSharper", "UnusedMember.Global")]
[SuppressMessage("ReSharper", "UnusedParameter.Global")]
[SuppressMessage("ReSharper", "MemberCanBePrivate.Global")]
[SuppressMessage("ReSharper", "MemberCanBeInternal")]
[SuppressMessage("ReSharper", "OutParameterValueIsAlwaysDiscarded.Global")]
internal sealed class SpamSumContext : IChecksum
{
const uint ROLLING_WINDOW = 7;
const uint MIN_BLOCKSIZE = 3;
const uint HASH_PRIME = 0x01000193;
const uint HASH_INIT = 0x28021967;
const uint NUM_BLOCKHASHES = 31;
const uint SPAMSUM_LENGTH = 64;
const uint FUZZY_MAX_RESULT = 2 * SPAMSUM_LENGTH + 20;
//"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
#if NET20 || NET35 || NET40 || NET452
readonly byte[] _b64 = Encoding.UTF8.GetBytes("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/");
#else
readonly byte[] _b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"u8.ToArray();
#endif
FuzzyState _self;
/// <summary>Initializes the SpamSum structures</summary>
public SpamSumContext()
{
_self = new FuzzyState
{
Bh = new BlockhashContext[NUM_BLOCKHASHES]
};
for (var i = 0; i < NUM_BLOCKHASHES; i++)
_self.Bh[i].Digest = new byte[SPAMSUM_LENGTH];
_self.Bhstart = 0;
_self.Bhend = 1;
_self.Bh[0].H = HASH_INIT;
_self.Bh[0].Halfh = HASH_INIT;
_self.Bh[0].Digest[0] = 0;
_self.Bh[0].Halfdigest = 0;
_self.Bh[0].Dlen = 0;
_self.TotalSize = 0;
roll_init();
}
#region IChecksum Members
/// <inheritdoc />
public string Name => "SpamSum";
/// <inheritdoc />
public Guid Id => new("DA692981-3291-47D8-B8B9-A87F0605F6E9");
/// <inheritdoc />
public string Author => "Natalia Portillo";
/// <inheritdoc />
/// <summary>Updates the hash with data.</summary>
/// <param name="data">Data buffer.</param>
/// <param name="len">Length of buffer to hash.</param>
public void Update(byte[] data, uint len)
{
_self.TotalSize += len;
for (var i = 0; i < len; i++)
fuzzy_engine_step(data[i]);
}
/// <inheritdoc />
/// <summary>Updates the hash with data.</summary>
/// <param name="data">Data buffer.</param>
public void Update(byte[] data) => Update(data, (uint)data.Length);
/// <inheritdoc />
/// <summary>Returns a byte array of the hash value.</summary>
public byte[] Final()
{
FuzzyDigest(out byte[] result);
return result;
}
/// <inheritdoc />
/// <summary>Returns a base64 representation of the hash value.</summary>
public string End()
{
FuzzyDigest(out byte[] result);
return CToString(result);
}
#endregion
#if NET452_OR_GREATER || NETCOREAPP
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
void roll_init() => _self.Roll = new RollState
{
Window = new byte[ROLLING_WINDOW]
};
/*
* a rolling hash, based on the Adler checksum. By using a rolling hash
* we can perform auto resynchronisation after inserts/deletes
* internally, h1 is the sum of the bytes in the window and h2
* is the sum of the bytes times the index
* h3 is a shift/xor based rolling hash, and is mostly needed to ensure that
* we can cope with large blocksize values
*/
#if NET452_OR_GREATER || NETCOREAPP
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
void roll_hash(byte c)
{
_self.Roll.H2 -= _self.Roll.H1;
_self.Roll.H2 += ROLLING_WINDOW * c;
_self.Roll.H1 += c;
_self.Roll.H1 -= _self.Roll.Window[_self.Roll.N % ROLLING_WINDOW];
_self.Roll.Window[_self.Roll.N % ROLLING_WINDOW] = c;
_self.Roll.N++;
/* The original spamsum AND'ed this value with 0xFFFFFFFF which
* in theory should have no effect. This AND has been removed
* for performance (jk) */
_self.Roll.H3 <<= 5;
_self.Roll.H3 ^= c;
}
#if NET452_OR_GREATER || NETCOREAPP
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
uint roll_sum() => _self.Roll.H1 + _self.Roll.H2 + _self.Roll.H3;
/* A simple non-rolling hash, based on the FNV hash. */
#if NET452_OR_GREATER || NETCOREAPP
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
static uint sum_hash(byte c, uint h) => h * HASH_PRIME ^ c;
#if NET452_OR_GREATER || NETCOREAPP
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
static uint SSDEEP_BS(uint index) => MIN_BLOCKSIZE << (int)index;
#if NET452_OR_GREATER || NETCOREAPP
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
void fuzzy_try_fork_blockhash()
{
switch (_self.Bhend)
{
case >= NUM_BLOCKHASHES:
return;
// assert
case 0:
throw new Exception("Assertion failed");
}
uint obh = _self.Bhend - 1;
uint nbh = _self.Bhend;
_self.Bh[nbh].H = _self.Bh[obh].H;
_self.Bh[nbh].Halfh = _self.Bh[obh].Halfh;
_self.Bh[nbh].Digest[0] = 0;
_self.Bh[nbh].Halfdigest = 0;
_self.Bh[nbh].Dlen = 0;
++_self.Bhend;
}
#if NET452_OR_GREATER || NETCOREAPP
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
void fuzzy_try_reduce_blockhash()
{
if (_self.Bhstart >= _self.Bhend)
throw new Exception("Assertion failed");
if (_self.Bhend - _self.Bhstart < 2)
/* Need at least two working hashes. */
return;
if ((ulong)SSDEEP_BS(_self.Bhstart) * SPAMSUM_LENGTH >= _self.TotalSize)
/* Initial blocksize estimate would select this or a smaller
* blocksize. */
return;
if (_self.Bh[_self.Bhstart + 1].Dlen < SPAMSUM_LENGTH / 2)
/* Estimate adjustment would select this blocksize. */
return;
/* At this point we are clearly no longer interested in the
* start_blocksize. Get rid of it. */
++_self.Bhstart;
}
#if NET452_OR_GREATER || NETCOREAPP
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
void fuzzy_engine_step(byte c)
{
uint i;
/* At each character we update the rolling hash and the normal hashes.
* When the rolling hash hits a reset value then we emit a normal hash
* as a element of the signature and reset the normal hash. */
roll_hash(c);
ulong h = roll_sum();
for (i = _self.Bhstart; i < _self.Bhend; ++i)
{
_self.Bh[i].H = sum_hash(c, _self.Bh[i].H);
_self.Bh[i].Halfh = sum_hash(c, _self.Bh[i].Halfh);
}
for (i = _self.Bhstart; i < _self.Bhend; ++i)
{
/* With growing blocksize almost no runs fail the next test. */
if (h % SSDEEP_BS(i) != SSDEEP_BS(i) - 1)
/* Once this condition is false for one bs, it is
* automatically false for all further bs. I.e. if
* h === -1 (mod 2*bs) then h === -1 (mod bs). */
break;
/* We have hit a reset point. We now emit hashes which are
* based on all characters in the piece of the message between
* the last reset point and this one */
if (0 == _self.Bh[i].Dlen)
fuzzy_try_fork_blockhash();
_self.Bh[i].Digest[_self.Bh[i].Dlen] = _b64[_self.Bh[i].H % 64];
_self.Bh[i].Halfdigest = _b64[_self.Bh[i].Halfh % 64];
if (_self.Bh[i].Dlen < SPAMSUM_LENGTH - 1)
{
/* We can have a problem with the tail overflowing. The
* easiest way to cope with this is to only reset the
* normal hash if we have room for more characters in
* our signature. This has the effect of combining the
* last few pieces of the message into a single piece
* */
_self.Bh[i].Digest[++_self.Bh[i].Dlen] = 0;
_self.Bh[i].H = HASH_INIT;
if (_self.Bh[i].Dlen >= SPAMSUM_LENGTH / 2)
continue;
_self.Bh[i].Halfh = HASH_INIT;
_self.Bh[i].Halfdigest = 0;
}
else
fuzzy_try_reduce_blockhash();
}
}
// CLAUNIA: Flags seems to never be used in ssdeep, so I just removed it for code simplicity
#if NET452_OR_GREATER || NETCOREAPP
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
void FuzzyDigest(out byte[] result)
{
var sb = new StringBuilder();
uint bi = _self.Bhstart;
uint h = roll_sum();
var remain = (int)(FUZZY_MAX_RESULT - 1); /* Exclude terminating '\0'. */
result = new byte[FUZZY_MAX_RESULT];
/* Verify that our elimination was not overeager. */
if (!(bi == 0 || (ulong)SSDEEP_BS(bi) / 2 * SPAMSUM_LENGTH < _self.TotalSize))
throw new Exception("Assertion failed");
/* Initial blocksize guess. */
while ((ulong)SSDEEP_BS(bi) * SPAMSUM_LENGTH < _self.TotalSize)
{
++bi;
if (bi >= NUM_BLOCKHASHES)
throw new OverflowException("The input exceeds data types");
}
/* Adapt blocksize guess to actual digest length. */
while (bi >= _self.Bhend)
--bi;
while (bi > _self.Bhstart && _self.Bh[bi].Dlen < SPAMSUM_LENGTH / 2)
--bi;
if (bi > 0 && _self.Bh[bi].Dlen < SPAMSUM_LENGTH / 2)
throw new Exception("Assertion failed");
sb.Append($"{SSDEEP_BS(bi)}:");
int i = Encoding.ASCII.GetBytes(sb.ToString()).Length;
if (i <= 0)
/* Maybe snprintf has set errno here? */
throw new OverflowException("The input exceeds data types");
if (i >= remain)
throw new Exception("Assertion failed");
remain -= i;
Array.Copy(Encoding.ASCII.GetBytes(sb.ToString()), 0, result, 0, i);
int resultOff = i;
i = (int)_self.Bh[bi].Dlen;
if (i > remain)
throw new Exception("Assertion failed");
Array.Copy(_self.Bh[bi].Digest, 0, result, resultOff, i);
resultOff += i;
remain -= i;
if (h != 0)
{
if (remain <= 0)
throw new Exception("Assertion failed");
result[resultOff] = _b64[_self.Bh[bi].H % 64];
if (i < 3 ||
result[resultOff] != result[resultOff - 1] ||
result[resultOff] != result[resultOff - 2] ||
result[resultOff] != result[resultOff - 3])
{
++resultOff;
--remain;
}
}
else if (_self.Bh[bi].Digest[i] != 0)
{
if (remain <= 0)
throw new Exception("Assertion failed");
result[resultOff] = _self.Bh[bi].Digest[i];
if (i < 3 ||
result[resultOff] != result[resultOff - 1] ||
result[resultOff] != result[resultOff - 2] ||
result[resultOff] != result[resultOff - 3])
{
++resultOff;
--remain;
}
}
if (remain <= 0)
throw new Exception("Assertion failed");
result[resultOff++] = 0x3A; // ':'
--remain;
if (bi < _self.Bhend - 1)
{
++bi;
i = (int)_self.Bh[bi].Dlen;
if (i > remain)
throw new Exception("Assertion failed");
Array.Copy(_self.Bh[bi].Digest, 0, result, resultOff, i);
resultOff += i;
remain -= i;
if (h != 0)
{
if (remain <= 0)
throw new Exception("Assertion failed");
h = _self.Bh[bi].Halfh;
result[resultOff] = _b64[h % 64];
if (i < 3 ||
result[resultOff] != result[resultOff - 1] ||
result[resultOff] != result[resultOff - 2] ||
result[resultOff] != result[resultOff - 3])
{
++resultOff;
--remain;
}
}
else
{
i = _self.Bh[bi].Halfdigest;
if (i != 0)
{
if (remain <= 0)
throw new Exception("Assertion failed");
result[resultOff] = (byte)i;
if (i < 3 ||
result[resultOff] != result[resultOff - 1] ||
result[resultOff] != result[resultOff - 2] ||
result[resultOff] != result[resultOff - 3])
{
++resultOff;
--remain;
}
}
}
}
else if (h != 0)
{
if (_self.Bh[bi].Dlen != 0)
throw new Exception("Assertion failed");
if (remain <= 0)
throw new Exception("Assertion failed");
result[resultOff++] = _b64[_self.Bh[bi].H % 64];
/* No need to bother with FUZZY_FLAG_ELIMSEQ, because this
* digest has length 1. */
--remain;
}
result[resultOff] = 0;
}
/// <summary>Gets the hash of a file</summary>
/// <param name="filename">File path.</param>
public static byte[] File(string filename) =>
throw new NotImplementedException("SpamSum does not have a binary representation.");
/// <summary>Gets the hash of a file in hexadecimal and as a byte array.</summary>
/// <param name="filename">File path.</param>
/// <param name="hash">Byte array of the hash value.</param>
public static string File(string filename, out byte[] hash) =>
throw new NotImplementedException("Not yet implemented.");
/// <summary>Gets the hash of the specified data buffer.</summary>
/// <param name="data">Data buffer.</param>
/// <param name="len">Length of the data buffer to hash.</param>
/// <param name="hash">null</param>
/// <returns>Base64 representation of SpamSum $blocksize:$hash:$hash</returns>
public static string Data(byte[] data, uint len, out byte[]? hash)
{
var fuzzyContext = new SpamSumContext();
fuzzyContext.Update(data, len);
hash = null;
return fuzzyContext.End();
}
/// <summary>Gets the hash of the specified data buffer.</summary>
/// <param name="data">Data buffer.</param>
/// <param name="hash">null</param>
/// <returns>Base64 representation of SpamSum $blocksize:$hash:$hash</returns>
public static string Data(byte[] data, out byte[]? hash) => Data(data, (uint)data.Length, out hash);
// Converts an ASCII null-terminated string to .NET string
#if NET452_OR_GREATER || NETCOREAPP
[MethodImpl(MethodImplOptions.AggressiveInlining)]
#endif
static string CToString(byte[] cString)
{
var count = 0;
// ReSharper disable once LoopCanBeConvertedToQuery
// LINQ is six times slower
foreach (byte c in cString)
{
if (c == 0)
break;
count++;
}
return Encoding.ASCII.GetString(cString, 0, count);
}
#region Nested type: BlockhashContext
/* A blockhash contains a signature state for a specific (implicit) blocksize.
* The blocksize is given by SSDEEP_BS(index). The h and halfh members are the
* FNV hashes, where halfh stops to be reset after digest is SPAMSUM_LENGTH/2
* long. The halfh hash is needed be able to truncate digest for the second
* output hash to stay compatible with ssdeep output. */
struct BlockhashContext
{
public uint H;
public uint Halfh;
public byte[] Digest;
// SPAMSUM_LENGTH
public byte Halfdigest;
public uint Dlen;
}
#endregion
#region Nested type: FuzzyState
struct FuzzyState
{
public uint Bhstart;
public uint Bhend;
public BlockhashContext[] Bh;
//NUM_BLOCKHASHES
public ulong TotalSize;
public RollState Roll;
}
#endregion
#region Nested type: RollState
struct RollState
{
public byte[] Window;
// ROLLING_WINDOW
public uint H1;
public uint H2;
public uint H3;
public uint N;
}
#endregion
}

View File

@@ -1,69 +0,0 @@
// /***************************************************************************
// Aaru Data Preservation Suite
// ----------------------------------------------------------------------------
//
// Filename : IChecksum.cs
// Author(s) : Natalia Portillo <claunia@claunia.com>
//
// Component : Checksums.
//
// --[ Description ] ----------------------------------------------------------
//
// Provides an interface for implementing checksums and hashes.
//
// --[ License ] --------------------------------------------------------------
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// ----------------------------------------------------------------------------
// Copyright © 2011-2023 Natalia Portillo
// ****************************************************************************/
using System;
namespace Aaru.CommonTypes.Interfaces;
/// <summary>Defines the interface to implement a checksum or hashing algorithm</summary>
internal interface IChecksum
{
/// <summary>Plugin author</summary>
string Author { get; }
/// <summary>Plugin name.</summary>
string Name { get; }
/// <summary>Plugin UUID.</summary>
Guid Id { get; }
/// <summary>Updates the hash with data.</summary>
/// <param name="data">Data buffer.</param>
/// <param name="len">Length of buffer to hash.</param>
void Update(byte[] data, uint len);
/// <summary>Updates the hash with data.</summary>
/// <param name="data">Data buffer.</param>
void Update(byte[] data);
/// <summary>Returns a byte array of the hash value.</summary>
byte[] Final();
/// <summary>Returns a hexadecimal representation of the hash value.</summary>
string End();
}

View File

@@ -1,331 +0,0 @@
// /***************************************************************************
// Aaru Data Preservation Suite
// ----------------------------------------------------------------------------
//
// Filename : BigEndianBitConverter.cs
// Author(s) : Natalia Portillo <claunia@claunia.com>
//
// Component : Helpers.
//
// --[ Description ] ----------------------------------------------------------
//
// Override of System.BitConverter that knows how to handle big-endian.
//
// --[ License ] --------------------------------------------------------------
//
// This library is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as
// published by the Free Software Foundation; either version 2.1 of the
// License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, see <http://www.gnu.org/licenses/>.
//
// ----------------------------------------------------------------------------
// Copyright © 2011-2023 Natalia Portillo
// ****************************************************************************/
using System;
namespace Aaru.Helpers
{
/// <summary>
/// Converts base data types to an array of bytes, and an array of bytes to base data types. All info taken from
/// the meta data of System.BitConverter. This implementation allows for Endianness consideration.
/// </summary>
public static class BigEndianBitConverter
{
/// <summary>Converts the specified double-precision floating point number to a 64-bit signed integer.</summary>
/// <param name="value">The number to convert.</param>
/// <returns>A 64-bit signed integer whose value is equivalent to value.</returns>
/// <exception cref="NotImplementedException">It is not currently implemented</exception>
public static long DoubleToInt64Bits(double value) => throw new NotImplementedException();
/// <summary>Returns the specified Boolean value as an array of bytes.</summary>
/// <param name="value">A Boolean value.</param>
/// <returns>An array of bytes with length 1.</returns>
public static byte[] GetBytes(bool value) => Reverse(BitConverter.GetBytes(value));
/// <summary>Returns the specified Unicode character value as an array of bytes.</summary>
/// <param name="value">A character to convert.</param>
/// <returns>An array of bytes with length 2.</returns>
public static byte[] GetBytes(char value) => Reverse(BitConverter.GetBytes(value));
/// <summary>Returns the specified double-precision floating point value as an array of bytes.</summary>
/// <param name="value">The number to convert.</param>
/// <returns>An array of bytes with length 8.</returns>
public static byte[] GetBytes(double value) => Reverse(BitConverter.GetBytes(value));
/// <summary>Returns the specified single-precision floating point value as an array of bytes.</summary>
/// <param name="value">The number to convert.</param>
/// <returns>An array of bytes with length 4.</returns>
public static byte[] GetBytes(float value) => Reverse(BitConverter.GetBytes(value));
/// <summary>Returns the specified 32-bit signed integer value as an array of bytes.</summary>
/// <param name="value">The number to convert.</param>
/// <returns>An array of bytes with length 4.</returns>
public static byte[] GetBytes(int value) => Reverse(BitConverter.GetBytes(value));
/// <summary>Returns the specified 64-bit signed integer value as an array of bytes.</summary>
/// <param name="value">The number to convert.</param>
/// <returns>An array of bytes with length 8.</returns>
public static byte[] GetBytes(long value) => Reverse(BitConverter.GetBytes(value));
/// <summary>Returns the specified 16-bit signed integer value as an array of bytes.</summary>
/// <param name="value">The number to convert.</param>
/// <returns>An array of bytes with length 2.</returns>
public static byte[] GetBytes(short value) => Reverse(BitConverter.GetBytes(value));
/// <summary>Returns the specified 32-bit unsigned integer value as an array of bytes.</summary>
/// <param name="value">The number to convert.</param>
/// <returns>An array of bytes with length 4.</returns>
public static byte[] GetBytes(uint value) => Reverse(BitConverter.GetBytes(value));
/// <summary>Returns the specified 64-bit unsigned integer value as an array of bytes.</summary>
/// <param name="value">The number to convert.</param>
/// <returns>An array of bytes with length 8.</returns>
public static byte[] GetBytes(ulong value) => Reverse(BitConverter.GetBytes(value));
/// <summary>Returns the specified 16-bit unsigned integer value as an array of bytes.</summary>
/// <param name="value">The number to convert.</param>
/// <returns>An array of bytes with length 2.</returns>
public static byte[] GetBytes(ushort value) => Reverse(BitConverter.GetBytes(value));
/// <summary>Converts the specified 64-bit signed integer to a double-precision floating point number.</summary>
/// <param name="value">The number to convert.</param>
/// <returns>A double-precision floating point number whose value is equivalent to value.</returns>
public static double Int64BitsToDouble(long value) => throw new NotImplementedException();
/// <summary>Returns a Boolean value converted from one byte at a specified position in a byte array.</summary>
/// <param name="value">An array of bytes.</param>
/// <param name="startIndex">The starting position within value.</param>
/// <returns>true if the byte at <see cref="startIndex" /> in value is nonzero; otherwise, false.</returns>
/// <exception cref="System.ArgumentNullException">value is null.</exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// <see cref="startIndex" /> is less than zero or greater than the
/// length of value minus 1.
/// </exception>
public static bool ToBoolean(byte[] value, int startIndex) => throw new NotImplementedException();
/// <summary>Returns a Unicode character converted from two bytes at a specified position in a byte array.</summary>
/// <param name="value">An array.</param>
/// <param name="startIndex">The starting position within value.</param>
/// <returns>A character formed by two bytes beginning at <see cref="startIndex" />.</returns>
/// <exception cref="System.ArgumentException"><see cref="startIndex" /> equals the length of value minus 1.</exception>
/// <exception cref="System.ArgumentNullException">value is null.</exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// <see cref="startIndex" /> is less than zero or greater than the
/// length of value minus 1.
/// </exception>
public static char ToChar(byte[] value, int startIndex) => throw new NotImplementedException();
/// <summary>
/// Returns a double-precision floating point number converted from eight bytes at a specified position in a byte
/// array.
/// </summary>
/// <param name="value">An array of bytes.</param>
/// <param name="startIndex">The starting position within value.</param>
/// <returns>A double precision floating point number formed by eight bytes beginning at <see cref="startIndex" />.</returns>
/// <exception cref="System.ArgumentException">
/// <see cref="startIndex" /> is greater than or equal to the length of value
/// minus 7, and is less than or equal to the length of value minus 1.
/// </exception>
/// <exception cref="System.ArgumentNullException">value is null.</exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// <see cref="startIndex" /> is less than zero or greater than the
/// length of value minus 1.
/// </exception>
public static double ToDouble(byte[] value, int startIndex) => throw new NotImplementedException();
/// <summary>Returns a 16-bit signed integer converted from two bytes at a specified position in a byte array.</summary>
/// <param name="value">An array of bytes.</param>
/// <param name="startIndex">The starting position within value.</param>
/// <returns>A 16-bit signed integer formed by two bytes beginning at <see cref="startIndex" />.</returns>
/// <exception cref="System.ArgumentException"><see cref="startIndex" /> equals the length of value minus 1.</exception>
/// <exception cref="System.ArgumentNullException">value is null.</exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// startIndex is less than zero or greater than the length of value
/// minus 1.
/// </exception>
public static short ToInt16(byte[] value, int startIndex) =>
BitConverter.ToInt16(Reverse(value), value.Length - sizeof(short) - startIndex);
/// <summary>Returns a 32-bit signed integer converted from four bytes at a specified position in a byte array.</summary>
/// <param name="value">An array of bytes.</param>
/// <param name="startIndex">The starting position within value.</param>
/// <returns>A 32-bit signed integer formed by four bytes beginning at <see cref="startIndex" />.</returns>
/// <exception cref="System.ArgumentException">
/// <see cref="startIndex" /> is greater than or equal to the length of value
/// minus 3, and is less than or equal to the length of value minus 1.
/// </exception>
/// <exception cref="System.ArgumentNullException">value is null.</exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// startIndex is less than zero or greater than the length of value
/// minus 1.
/// </exception>
public static int ToInt32(byte[] value, int startIndex) =>
BitConverter.ToInt32(Reverse(value), value.Length - sizeof(int) - startIndex);
/// <summary>Returns a 64-bit signed integer converted from eight bytes at a specified position in a byte array.</summary>
/// <param name="value">An array of bytes.</param>
/// <param name="startIndex">The starting position within value.</param>
/// <returns>A 64-bit signed integer formed by eight bytes beginning at <see cref="startIndex" />.</returns>
/// <exception cref="System.ArgumentException">
/// <see cref="startIndex" /> is greater than or equal to the length of value
/// minus 7, and is less than or equal to the length of value minus 1.
/// </exception>
/// <exception cref="System.ArgumentNullException">value is null.</exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// <see cref="startIndex" /> is less than zero or greater than the
/// length of value minus 1.
/// </exception>
public static long ToInt64(byte[] value, int startIndex) =>
BitConverter.ToInt64(Reverse(value), value.Length - sizeof(long) - startIndex);
/// <summary>
/// Returns a single-precision floating point number converted from four bytes at a specified position in a byte
/// array.
/// </summary>
/// <param name="value">An array of bytes.</param>
/// <param name="startIndex">The starting position within value.</param>
/// <returns>A single-precision floating point number formed by four bytes beginning at <see cref="startIndex" />.</returns>
/// <exception cref="System.ArgumentException">
/// <see cref="startIndex" /> is greater than or equal to the length of value
/// minus 3, and is less than or equal to the length of value minus 1.
/// </exception>
/// <exception cref="System.ArgumentNullException">value is null.</exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// <see cref="startIndex" /> is less than zero or greater than the
/// length of value minus 1.
/// </exception>
public static float ToSingle(byte[] value, int startIndex) =>
BitConverter.ToSingle(Reverse(value), value.Length - sizeof(float) - startIndex);
/// <summary>
/// Converts the numeric value of each element of a specified array of bytes to its equivalent hexadecimal string
/// representation.
/// </summary>
/// <param name="value">An array of bytes.</param>
/// <returns>
/// A System.String of hexadecimal pairs separated by hyphens, where each pair represents the corresponding
/// element in value; for example, "7F-2C-4A".
/// </returns>
/// <exception cref="System.ArgumentNullException">value is null.</exception>
public static string ToString(byte[] value) => BitConverter.ToString(Reverse(value));
/// <summary>
/// Converts the numeric value of each element of a specified subarray of bytes to its equivalent hexadecimal
/// string representation.
/// </summary>
/// <param name="value">An array of bytes.</param>
/// <param name="startIndex">The starting position within value.</param>
/// <returns>
/// A System.String of hexadecimal pairs separated by hyphens, where each pair represents the corresponding
/// element in a subarray of value; for example, "7F-2C-4A".
/// </returns>
/// <exception cref="System.ArgumentNullException">value is null.</exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// startIndex is less than zero or greater than the length of value
/// minus 1.
/// </exception>
public static string ToString(byte[] value, int startIndex) =>
BitConverter.ToString(Reverse(value), startIndex);
/// <summary>
/// Converts the numeric value of each element of a specified subarray of bytes to its equivalent hexadecimal
/// string representation.
/// </summary>
/// <param name="value">An array of bytes.</param>
/// <param name="startIndex">The starting position within value.</param>
/// <param name="length">The number of array elements in value to convert.</param>
/// <returns>
/// A System.String of hexadecimal pairs separated by hyphens, where each pair represents the corresponding
/// element in a subarray of value; for example, "7F-2C-4A".
/// </returns>
/// <exception cref="System.ArgumentNullException">value is null.</exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// startIndex or length is less than zero. -or- startIndex is greater
/// than zero and is greater than or equal to the length of value.
/// </exception>
/// <exception cref="System.ArgumentException">
/// The combination of startIndex and length does not specify a position within
/// value; that is, the startIndex parameter is greater than the length of value minus the length parameter.
/// </exception>
public static string ToString(byte[] value, int startIndex, int length) =>
BitConverter.ToString(Reverse(value), startIndex, length);
/// <summary>Returns a 16-bit unsigned integer converted from two bytes at a specified position in a byte array.</summary>
/// <param name="value">The array of bytes.</param>
/// <param name="startIndex">The starting position within value.</param>
/// <returns>A 16-bit unsigned integer formed by two bytes beginning at startIndex.</returns>
/// <exception cref="System.ArgumentException">startIndex equals the length of value minus 1.</exception>
/// <exception cref="System.ArgumentNullException">value is null.</exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// startIndex is less than zero or greater than the length of value
/// minus 1.
/// </exception>
public static ushort ToUInt16(byte[] value, int startIndex) =>
BitConverter.ToUInt16(Reverse(value), value.Length - sizeof(ushort) - startIndex);
/// <summary>Returns a 32-bit unsigned integer converted from four bytes at a specified position in a byte array.</summary>
/// <param name="value">An array of bytes.</param>
/// <param name="startIndex">The starting position within value.</param>
/// <returns>A 32-bit unsigned integer formed by four bytes beginning at startIndex.</returns>
/// <exception cref="System.ArgumentException">
/// startIndex is greater than or equal to the length of value minus 3, and is
/// less than or equal to the length of value minus 1.
/// </exception>
/// <exception cref="System.ArgumentNullException">value is null.</exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// startIndex is less than zero or greater than the length of value
/// minus 1.
/// </exception>
public static uint ToUInt32(byte[] value, int startIndex) =>
BitConverter.ToUInt32(Reverse(value), value.Length - sizeof(uint) - startIndex);
/// <summary>Returns a 64-bit unsigned integer converted from eight bytes at a specified position in a byte array.</summary>
/// <param name="value">An array of bytes.</param>
/// <param name="startIndex">The starting position within value.</param>
/// <returns>A 64-bit unsigned integer formed by the eight bytes beginning at startIndex.</returns>
/// <exception cref="System.ArgumentException">
/// startIndex is greater than or equal to the length of value minus 7, and is
/// less than or equal to the length of value minus 1.
/// </exception>
/// <exception cref="System.ArgumentNullException">value is null.</exception>
/// <exception cref="System.ArgumentOutOfRangeException">
/// startIndex is less than zero or greater than the length of value
/// minus 1.
/// </exception>
public static ulong ToUInt64(byte[] value, int startIndex) =>
BitConverter.ToUInt64(Reverse(value), value.Length - sizeof(ulong) - startIndex);
/// <summary>Converts a big endian byte array representation of a GUID into the .NET Guid structure</summary>
/// <param name="value">Byte array containing a GUID in big endian</param>
/// <param name="startIndex">Start of the byte array to process</param>
/// <returns>Processed Guid</returns>
public static Guid ToGuid(byte[] value, int startIndex) => new Guid(ToUInt32(value, 0 + startIndex),
ToUInt16(value, 4 + startIndex),
ToUInt16(value, 6 + startIndex),
value[8 + startIndex + 0],
value[8 + startIndex + 1],
value[8 + startIndex + 2],
value[8 + startIndex + 3],
value[8 + startIndex + 5],
value[8 + startIndex + 5],
value[8 + startIndex + 6],
value[8 + startIndex + 7]);
// Additional helper method to replace single Linq use
private static T[] Reverse<T>(T[] value)
{
Array.Reverse(value);
return value;
}
}
}

View File

@@ -1,72 +0,0 @@
// /***************************************************************************
// Aaru Data Preservation Suite
// ----------------------------------------------------------------------------
//
// Filename : Extensions.cs
// Author(s) : Natalia Portillo <claunia@claunia.com>
//
// Component : Helpers.
//
// --[ Description ] ----------------------------------------------------------
//
// Provides class extensions.
//
// --[ License ] --------------------------------------------------------------
//
// This library is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as
// published by the Free Software Foundation; either version 2.1 of the
// License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, see <http://www.gnu.org/licenses/>.
//
// ----------------------------------------------------------------------------
// Copyright © 2011-2023 Natalia Portillo
// ****************************************************************************/
using System.IO;
namespace Aaru.Helpers;
public static class Extensions
{
/// <summary>
/// When overridden in a derived class, reads a sequence of bytes from the current stream and advances the
/// position within the stream by the number of bytes read.<br /> Guarantees the whole count of bytes is read or EOF is
/// found
/// </summary>
/// <param name="s">Stream to extend</param>
/// <param name="buffer">
/// An array of bytes. When this method returns, the buffer contains the specified byte array with the
/// values between <see cref="offset" /> and (<see cref="offset" /> + <see cref="count" /> - 1) replaced by the bytes
/// read from the current source.
/// </param>
/// <param name="offset">
/// The zero-based byte offset in <see cref="buffer" /> at which to begin storing the data read from
/// the current stream.
/// </param>
/// <param name="count">The maximum number of bytes to be read from the current stream.</param>
/// <returns>
/// The total number of bytes read into the buffer. This can be less than the number of bytes requested if the end
/// of the stream has been reached.
/// </returns>
public static int EnsureRead(Stream s, byte[] buffer, int offset, int count)
{
var pos = 0;
int read;
do
{
read = s.Read(buffer, pos + offset, count - pos);
pos += read;
} while(read > 0);
return pos;
}
}

View File

@@ -0,0 +1,144 @@
using System;
using static SabreTools.Hashing.Checksum.Constants;
namespace SabreTools.Hashing.Checksum
{
/// <see href="https://github.com/madler/zlib/blob/v1.2.11/adler32.c"/>
public class Adler32 : ChecksumBase<uint>
{
/// <inheritdoc/>
public override int HashSize => 32;
public Adler32()
{
Initialize();
}
/// <summary>
/// Reset the internal hashing state
/// </summary>
public override void Initialize()
{
_hash = 1;
}
/// <inheritdoc/>
protected override void HashCore(byte[] data, int offset, int length)
{
// Split Adler-32 into component sums
uint sum2 = (_hash >> 16) & 0xffff;
_hash &= 0xffff;
// In case user likes doing a byte at a time, keep it fast
if (length == 1)
{
_hash += data[offset];
if (_hash >= A32BASE)
_hash -= A32BASE;
sum2 += _hash;
if (sum2 >= A32BASE)
sum2 -= A32BASE;
_hash |= sum2 << 16;
return;
}
// In case short lengths are provided, keep it somewhat fast
if (length < 16)
{
while (length-- > 0)
{
_hash += data[offset]++;
sum2 += _hash;
}
if (_hash >= A32BASE)
_hash -= A32BASE;
// Only added so many BASE's
sum2 %= A32BASE;
_hash |= sum2 << 16;
return;
}
// Do length NMAX blocks -- requires just one modulo operation
while (length >= A32NMAX)
{
// NMAX is divisible by 16
length -= A32NMAX;
uint n = A32NMAX / 16;
do
{
_hash += data[offset + 0]; sum2 += _hash;
_hash += data[offset + 1]; sum2 += _hash;
_hash += data[offset + 2]; sum2 += _hash;
_hash += data[offset + 3]; sum2 += _hash;
_hash += data[offset + 4]; sum2 += _hash;
_hash += data[offset + 5]; sum2 += _hash;
_hash += data[offset + 6]; sum2 += _hash;
_hash += data[offset + 7]; sum2 += _hash;
_hash += data[offset + 8]; sum2 += _hash;
_hash += data[offset + 9]; sum2 += _hash;
_hash += data[offset + 10]; sum2 += _hash;
_hash += data[offset + 11]; sum2 += _hash;
_hash += data[offset + 12]; sum2 += _hash;
_hash += data[offset + 13]; sum2 += _hash;
_hash += data[offset + 14]; sum2 += _hash;
_hash += data[offset + 15]; sum2 += _hash;
offset += 16;
} while (--n > 0);
}
// Do remaining bytes (less than NMAX, still just one modulo)
if (length > 0)
{
// Avoid modulos if none remaining
while (length >= 16)
{
length -= 16;
_hash += data[offset + 0]; sum2 += _hash;
_hash += data[offset + 1]; sum2 += _hash;
_hash += data[offset + 2]; sum2 += _hash;
_hash += data[offset + 3]; sum2 += _hash;
_hash += data[offset + 4]; sum2 += _hash;
_hash += data[offset + 5]; sum2 += _hash;
_hash += data[offset + 6]; sum2 += _hash;
_hash += data[offset + 7]; sum2 += _hash;
_hash += data[offset + 8]; sum2 += _hash;
_hash += data[offset + 9]; sum2 += _hash;
_hash += data[offset + 10]; sum2 += _hash;
_hash += data[offset + 11]; sum2 += _hash;
_hash += data[offset + 12]; sum2 += _hash;
_hash += data[offset + 13]; sum2 += _hash;
_hash += data[offset + 14]; sum2 += _hash;
_hash += data[offset + 15]; sum2 += _hash;
offset += 16;
}
while (length-- > 0)
{
_hash += data[offset++];
sum2 += _hash;
}
_hash %= A32BASE;
sum2 %= A32BASE;
}
// Return recombined sums
_hash |= sum2 << 16;
}
/// <inheritdoc/>
protected override byte[] HashFinal()
{
byte[] hashArr = BitConverter.GetBytes(_hash);
Array.Reverse(hashArr);
return hashArr;
}
}
}

View File

@@ -1,23 +1,7 @@
namespace SabreTools.Hashing.Crc
namespace SabreTools.Hashing.Checksum
{
internal static class BitOperations
{
/// <summary>
/// Reverse the endianness of a value
/// </summary>
public static ulong ReverseBits(ulong value, int bitWidth)
{
ulong reverse = 0;
for (int i = 0; i < bitWidth; i++)
{
reverse <<= 1;
reverse |= value & 1;
value >>= 1;
}
return reverse;
}
/// <summary>
/// Clamp a value to a certain bit width and convert to a byte array
/// </summary>
@@ -35,4 +19,4 @@ namespace SabreTools.Hashing.Crc
return bytes;
}
}
}
}

View File

@@ -0,0 +1,50 @@
using System;
namespace SabreTools.Hashing.Checksum
{
/// <summary>
/// Common base class for Fletcher checksums
/// </summary>
public abstract class ChecksumBase : System.Security.Cryptography.HashAlgorithm
{
// No common, untyped functionality
}
/// <summary>
/// Common base class for checksums
/// </summary>
public abstract class ChecksumBase<T> : ChecksumBase where T : struct
{
/// <summary>
/// The current value of the hash
/// </summary>
protected T _hash;
/// <inheritdoc/>
public override void Initialize()
{
_hash = default;
}
/// <inheritdoc/>
protected override byte[] HashFinal()
{
byte[] hashArr = _hash switch
{
short s => BitConverter.GetBytes(s),
ushort s => BitConverter.GetBytes(s),
int i => BitConverter.GetBytes(i),
uint i => BitConverter.GetBytes(i),
long l => BitConverter.GetBytes(l),
ulong l => BitConverter.GetBytes(l),
_ => [],
};
Array.Reverse(hashArr);
return hashArr;
}
}
}

View File

@@ -0,0 +1,33 @@
namespace SabreTools.Hashing.Checksum
{
internal static class Constants
{
#region Adler-32
/// <summary>
/// Largest prime smaller than 65536
/// </summary>
public const ushort A32BASE = 65521;
/// <summary>
/// NMAX is the largest n such that 255n(n+1)/2 + (n+1)(<see cref="A32BASE">-1) <= 2^32-1
/// </summary>
public const ushort A32NMAX = 5552;
#endregion
#region Fletcher-32
/// <summary>
/// Max value for a single half of a Fletcher-32 checksum
/// </summary>
public const ushort F32BASE = 0xffff;
/// <summary>
/// Max value for a single half of a Fletcher-64 checksum
/// </summary>
public const uint F64BASE = 0xffffffff;
#endregion
}
}

View File

@@ -0,0 +1,59 @@
using System;
using static SabreTools.Hashing.HashOperations;
namespace SabreTools.Hashing.Checksum
{
public class Crc : ChecksumBase<ulong>
{
/// <inheritdoc/>
public override int HashSize => Def.Width;
/// <summary>
/// Definition used to create the runner
/// </summary>
public readonly CrcDefinition Def;
/// <summary>
/// Table used for calculation steps
/// </summary>
private readonly CrcTable _table;
public Crc(CrcDefinition def)
{
// Check for a valid bit width
if (def.Width < 0 || def.Width > 64)
throw new ArgumentOutOfRangeException(nameof(def));
Def = def;
_table = new CrcTable(def);
_hash = def.ReflectIn ? ReverseBits(def.Init, def.Width) : def.Init;
}
/// <inheritdoc/>
public override void Initialize()
{
_hash = Def.Init;
}
/// <inheritdoc/>
protected override void HashCore(byte[] data, int offset, int length)
=> _table.TransformBlock(ref _hash, data, offset, length);
/// <inheritdoc/>
protected override byte[] HashFinal()
{
// Create a copy of the hash
ulong localHash = _hash;
// Handle mutual reflection
if (Def.ReflectIn ^ Def.ReflectOut)
localHash = ReverseBits(localHash, Def.Width);
// Handle XOR
localHash ^= Def.XorOut;
// Process the value and return
return BitOperations.ClampValueToBytes(localHash, Def.Width);
}
}
}

View File

@@ -1,8 +1,13 @@
namespace SabreTools.Hashing.Crc
namespace SabreTools.Hashing.Checksum
{
/// <see href="https://reveng.sourceforge.io/crc-catalogue/all.htm#crc.legend"/>
internal class CrcDefinition
public class CrcDefinition
{
/// <summary>
/// The name assigned to the model in this Catalogue.
/// </summary>
public string? Name { get; set; }
/// <summary>
/// The number of bit cells in the linear feedback shift register;
/// the degree of the generator polynomial, less one.
@@ -57,4 +62,4 @@ namespace SabreTools.Hashing.Crc
/// </summary>
public ulong XorOut { get; set; }
}
}
}

View File

@@ -0,0 +1,333 @@
using static SabreTools.Hashing.HashOperations;
namespace SabreTools.Hashing.Checksum
{
internal class CrcTable
{
/// <summary>
/// Indicates if CRC should be processed bitwise instead of bytewise
/// </summary>
private bool Bitwise => _definition.Width < 8;
/// <summary>
/// Number of bits to process at a time
/// </summary>
private int BitsPerStep => Bitwise ? 1 : 8;
/// <summary>
/// Bit shift based on the CRC width
/// </summary>
private int BitShift => _definition.Width - BitsPerStep;
/// <summary>
/// Bit mask based on the CRC width
/// </summary>
private ulong BitMask => 1UL << (_definition.Width - 1);
/// <summary>
/// Mapping table
/// </summary>
private readonly ulong[,] _table;
/// <summary>
/// Definition used to build the table
/// </summary>
private readonly CrcDefinition _definition;
/// <summary>
/// Number of slices in the optimized table
/// </summary>
private const int SliceCount = 8;
public CrcTable(CrcDefinition def)
{
// Initialize the internal
_definition = def;
_table = new ulong[SliceCount, 1 << BitsPerStep];
// Build the standard table
for (uint i = 0; i < (1 << BitsPerStep); i++)
{
// Get the starting value for this index
ulong point = i;
if (!Bitwise && def.ReflectIn)
point = ReverseBits(point, BitsPerStep);
// Shift to account for storage
point <<= _definition.Width - BitsPerStep;
// Accumulate the value
for (int j = 0; j < BitsPerStep; j++)
{
if ((point & BitMask) > 0UL)
point = (point << 1) ^ def.Poly;
else
point <<= 1;
}
// Reflect if necessary
if (def.ReflectIn)
point = ReverseBits(point, def.Width);
// Shift back to account for storage
point &= ulong.MaxValue >> (64 - def.Width);
// Assign to the table
_table[0, i] = point;
}
// Skip building the optimized table for bitwise processing
if (Bitwise)
return;
// Build the optimized table for non-bitwise processing
for (int i = 1; i < SliceCount; i++)
{
// Build each slice from the previous
for (int j = 0; j < 1 << BitsPerStep; j++)
{
ulong last = _table[i - 1, j];
if (_definition.ReflectIn)
_table[i, j] = (last >> BitsPerStep) ^ _table[0, (byte)last];
else
_table[i, j] = (last << BitsPerStep) ^ _table[0, (byte)(last >> BitShift)];
}
}
}
/// <summary>
/// Hash a block of data and append it to the existing hash
/// </summary>
/// <param name="hash">Current hash value, updated on run</param>
/// <param name="data">Byte array representing the data</param>
/// <param name="offset">Offset in the byte array to include</param>
/// <param name="length">Length of the data to hash</param>
public void TransformBlock(ref ulong hash, byte[] data, int offset, int length)
{
// Empty data just returns
if (data.Length == 0)
return;
// Check for valid offset and length
if (offset > data.Length)
throw new System.ArgumentOutOfRangeException(nameof(offset));
else if (offset + length > data.Length)
throw new System.ArgumentOutOfRangeException(nameof(length));
// Try transforming fast first
if (TransformBlockFast(ref hash, data, offset, length))
return;
// Process the data byte-wise
for (int i = offset; i < offset + length; i++)
{
PerformChecksumStep(ref hash, data, i);
}
}
/// <summary>
/// Perform a single checksum step
/// </summary>
/// <param name="hash">Current hash value, updated on run</param>
/// <param name="data">Byte array representing the data</param>
/// <param name="offset">Offset in the data to process</param>
private void PerformChecksumStep(ref ulong hash, byte[] data, int offset)
{
// Per-bit processing
if (Bitwise)
{
for (int b = 0; b < 8; b++)
{
if (_definition.ReflectIn)
hash = (hash >> 1) ^ _table[0, (byte)(hash & 1) ^ ((byte)(data[offset] >> b) & 1)];
else
hash = (hash << 1) ^ _table[0, (byte)((hash >> BitShift) & 1) ^ ((byte)(data[offset] >> (7 - b)) & 1)];
}
}
// Per-byte processing
else
{
if (_definition.ReflectIn)
hash = (hash >> 8) ^ _table[0, (byte)hash ^ data[offset]];
else
hash = (hash << 8) ^ _table[0, ((byte)(hash >> BitShift)) ^ data[offset]];
}
}
/// <summary>
/// Perform an optimized transform step
/// </summary>
private bool TransformBlockFast(ref ulong hash, byte[] data, int offset, int length)
{
// Bitwise transformations are not optimized
if (Bitwise)
return false;
// All reflection-in implementations share an optimized path
if (_definition.Width < 64 && _definition.ReflectIn)
{
TransformBlockFast8Reflect(ref hash, data, offset, length);
return true;
}
else if (_definition.Width >= 64 && _definition.ReflectIn)
{
TransformBlockFast4Reflect(ref hash, data, offset, length);
return true;
}
// CRC-32 with no reflection-in has can be optimized
if (_definition.Width == 32 && !_definition.ReflectIn)
{
TransformBlockFast8NoReflect(ref hash, data, offset, length);
return true;
}
return false;
}
/// <summary>
/// Optimized transformation for CRC with reflection
/// </summary>
/// <remarks>Reads 4 bytes at a time</remarks>
private void TransformBlockFast4Reflect(ref ulong hash, byte[] data, int offset, int length)
{
// Process on a copy of the hash
ulong local = hash;
// Process aligned data
if (length > 4)
{
long end = offset + (length & ~(uint)3);
length &= 3;
while (offset < end)
{
ulong low = local ^ (uint)(
data[offset + 0]
+ (data[offset + 1] << 8)
+ (data[offset + 2] << 16)
+ (data[offset + 3] << 24));
offset += 4;
local = _table[3, (byte)low]
^ _table[2, (byte)(low >> 8)]
^ _table[1, (byte)(low >> 16)]
^ _table[0, (byte)(low >> 24)]
^ (local >> 32);
}
}
// Process unaligned data
while (length-- != 0)
{
PerformChecksumStep(ref local, data, offset++);
}
// Assign the new hash value
hash = local;
}
/// <summary>
/// Optimized transformation for CRC with reflection
/// </summary>
/// <remarks>Reads 8 bytes at a time</remarks>
private void TransformBlockFast8Reflect(ref ulong hash, byte[] data, int offset, int length)
{
// Process on a copy of the hash
ulong local = hash;
// Process aligned data
if (length > 8)
{
long end = offset + (length & ~(uint)7);
length &= 7;
while (offset < end)
{
ulong low = local ^ (uint)(
data[offset + 0]
+ (data[offset + 1] << 8)
+ (data[offset + 2] << 16)
+ (data[offset + 3] << 24));
ulong high = (uint)(
data[offset + 4]
+ (data[offset + 5] << 8)
+ (data[offset + 6] << 16)
+ (data[offset + 7] << 24));
offset += 8;
local = _table[7, (byte)low]
^ _table[6, (byte)(low >> 8)]
^ _table[5, (byte)(low >> 16)]
^ _table[4, (byte)(low >> 24)]
^ _table[3, (byte)high]
^ _table[2, (byte)(high >> 8)]
^ _table[1, (byte)(high >> 16)]
^ _table[0, (byte)(high >> 24)]
^ (local >> 32);
}
}
// Process unaligned data
while (length-- != 0)
{
PerformChecksumStep(ref local, data, offset++);
}
// Assign the new hash value
hash = local;
}
/// <summary>
/// Optimized transformation for 32-bit CRC with no reflection
/// </summary>
/// <remarks>Reads 8 bytes at a time</remarks>
private void TransformBlockFast8NoReflect(ref ulong hash, byte[] data, int offset, int length)
{
// Process on a copy of the hash
ulong local = hash;
// Process aligned data
if (length > 8)
{
long end = offset + (length & ~(uint)7);
length &= 7;
while (offset < end)
{
ulong low = local ^ (uint)(
data[offset + 3]
+ (data[offset + 2] << 8)
+ (data[offset + 1] << 16)
+ (data[offset + 0] << 24));
ulong high = (uint)(
data[offset + 7]
+ (data[offset + 6] << 8)
+ (data[offset + 5] << 16)
+ (data[offset + 4] << 24));
offset += 8;
local = _table[4, (byte)low]
^ _table[5, (byte)(low >> 8)]
^ _table[6, (byte)(low >> 16)]
^ _table[7, (byte)(low >> 24)]
^ _table[0, (byte)high]
^ _table[1, (byte)(high >> 8)]
^ _table[2, (byte)(high >> 16)]
^ _table[3, (byte)(high >> 24)]
^ (local << 32);
}
}
// Process unaligned data
while (length-- != 0)
{
PerformChecksumStep(ref local, data, offset++);
}
// Assign the new hash value
hash = local;
}
}
}

View File

@@ -0,0 +1,44 @@
namespace SabreTools.Hashing.Checksum
{
/// <see href="https://en.wikipedia.org/wiki/Fletcher%27s_checksum#Optimizations"/>
public class Fletcher16 : ChecksumBase<ushort>
{
/// <inheritdoc/>
public override int HashSize => 16;
public Fletcher16()
{
Initialize();
}
/// <inheritdoc/>
protected override void HashCore(byte[] data, int offset, int length)
{
// Split the existing hash
uint c0 = (uint)(_hash & 0x00ff);
uint c1 = (uint)((_hash >> 8) & 0x00ff);
// Found by solving for c1 overflow:
// n > 0 and n * (n+1) / 2 * (2^8-1) < (2^32-1).
while (length > 0)
{
int blocklen = length;
if (blocklen > 5802)
blocklen = 5802;
length -= blocklen;
do
{
c0 += data[offset++];
c1 += c0;
} while (--blocklen > 0);
c0 %= 255;
c1 %= 255;
}
// Return recombined sums
_hash = (ushort)((c1 << 8) | c0);
}
}
}

View File

@@ -0,0 +1,128 @@
using static SabreTools.Hashing.Checksum.Constants;
namespace SabreTools.Hashing.Checksum
{
/// <see href="https://en.wikipedia.org/wiki/Fletcher%27s_checksum#Optimizations"/>
/// <remarks>Uses an Adler-32-like implementation instead of the above</remarks>
public class Fletcher32 : ChecksumBase<uint>
{
/// <inheritdoc/>
public override int HashSize => 32;
public Fletcher32()
{
Initialize();
}
/// <inheritdoc/>
protected override void HashCore(byte[] data, int offset, int length)
{
// Split Fletcher-32 into component sums
uint c0 = _hash & 0xffff;
uint c1 = (_hash >> 16) & 0xffff;
// In case user likes doing a byte at a time, keep it fast
if (length == 1)
{
c0 += data[offset];
if (c0 >= F32BASE)
c0 -= F32BASE;
c1 += c0;
if (c1 >= F32BASE)
c1 -= F32BASE;
_hash = (c1 << 16) | c0;
return;
}
// In case short lengths are provided, keep it somewhat fast
if (length < 16)
{
while (length-- > 0)
{
c0 += data[offset]++;
c1 += c0;
}
if (c0 >= F32BASE)
c0 -= F32BASE;
// Only added so many BASE's
c1 %= F32BASE;
_hash = (c1 << 16) | c0;
return;
}
// Do length NMAX blocks -- requires just one modulo operation
while (length >= A32NMAX)
{
// NMAX is divisible by 16
length -= A32NMAX;
uint n = A32NMAX / 16;
do
{
c0 += data[offset + 0]; c1 += c0;
c0 += data[offset + 1]; c1 += c0;
c0 += data[offset + 2]; c1 += c0;
c0 += data[offset + 3]; c1 += c0;
c0 += data[offset + 4]; c1 += c0;
c0 += data[offset + 5]; c1 += c0;
c0 += data[offset + 6]; c1 += c0;
c0 += data[offset + 7]; c1 += c0;
c0 += data[offset + 8]; c1 += c0;
c0 += data[offset + 9]; c1 += c0;
c0 += data[offset + 10]; c1 += c0;
c0 += data[offset + 11]; c1 += c0;
c0 += data[offset + 12]; c1 += c0;
c0 += data[offset + 13]; c1 += c0;
c0 += data[offset + 14]; c1 += c0;
c0 += data[offset + 15]; c1 += c0;
offset += 16;
} while (--n > 0);
}
// Do remaining bytes (less than NMAX, still just one modulo)
if (length > 0)
{
// Avoid modulos if none remaining
while (length >= 16)
{
length -= 16;
c0 += data[offset + 0]; c1 += c0;
c0 += data[offset + 1]; c1 += c0;
c0 += data[offset + 2]; c1 += c0;
c0 += data[offset + 3]; c1 += c0;
c0 += data[offset + 4]; c1 += c0;
c0 += data[offset + 5]; c1 += c0;
c0 += data[offset + 6]; c1 += c0;
c0 += data[offset + 7]; c1 += c0;
c0 += data[offset + 8]; c1 += c0;
c0 += data[offset + 9]; c1 += c0;
c0 += data[offset + 10]; c1 += c0;
c0 += data[offset + 11]; c1 += c0;
c0 += data[offset + 12]; c1 += c0;
c0 += data[offset + 13]; c1 += c0;
c0 += data[offset + 14]; c1 += c0;
c0 += data[offset + 15]; c1 += c0;
offset += 16;
}
while (length-- > 0)
{
c0 += data[offset++];
c1 += c0;
}
c0 %= F32BASE;
c1 %= F32BASE;
}
// Return recombined sums
_hash = (c1 << 16) | c0;
}
}
}

View File

@@ -0,0 +1,128 @@
using static SabreTools.Hashing.Checksum.Constants;
namespace SabreTools.Hashing.Checksum
{
/// <see href="https://en.wikipedia.org/wiki/Fletcher%27s_checksum#Optimizations"/>
/// <remarks>Uses an Adler-32-like implementation instead of the above</remarks>
public class Fletcher64 : ChecksumBase<ulong>
{
/// <inheritdoc/>
public override int HashSize => 64;
public Fletcher64()
{
Initialize();
}
/// <inheritdoc/>
protected override void HashCore(byte[] data, int offset, int length)
{
// Split Fletcher-64 into component sums
ulong c0 = _hash & 0xffffffff;
ulong c1 = (_hash >> 32) & 0xffffffff;
// In case user likes doing a byte at a time, keep it fast
if (length == 1)
{
c0 += data[offset];
if (c0 >= F64BASE)
c0 -= F64BASE;
c1 += c0;
if (c1 >= F64BASE)
c1 -= F64BASE;
_hash = (c1 << 32) | c0;
return;
}
// In case short lengths are provided, keep it somewhat fast
if (length < 16)
{
while (length-- > 0)
{
c0 += data[offset]++;
c1 += c0;
}
if (c0 >= F64BASE)
c0 -= F64BASE;
// Only added so many BASE's
c1 %= F64BASE;
_hash = (c1 << 32) | c0;
return;
}
// Do length NMAX blocks -- requires just one modulo operation
while (length >= A32NMAX)
{
// NMAX is divisible by 16
length -= A32NMAX;
uint n = A32NMAX / 16;
do
{
c0 += data[offset + 0]; c1 += c0;
c0 += data[offset + 1]; c1 += c0;
c0 += data[offset + 2]; c1 += c0;
c0 += data[offset + 3]; c1 += c0;
c0 += data[offset + 4]; c1 += c0;
c0 += data[offset + 5]; c1 += c0;
c0 += data[offset + 6]; c1 += c0;
c0 += data[offset + 7]; c1 += c0;
c0 += data[offset + 8]; c1 += c0;
c0 += data[offset + 9]; c1 += c0;
c0 += data[offset + 10]; c1 += c0;
c0 += data[offset + 11]; c1 += c0;
c0 += data[offset + 12]; c1 += c0;
c0 += data[offset + 13]; c1 += c0;
c0 += data[offset + 14]; c1 += c0;
c0 += data[offset + 15]; c1 += c0;
offset += 16;
} while (--n > 0);
}
// Do remaining bytes (less than NMAX, still just one modulo)
if (length > 0)
{
// Avoid modulos if none remaining
while (length >= 16)
{
length -= 16;
c0 += data[offset + 0]; c1 += c0;
c0 += data[offset + 1]; c1 += c0;
c0 += data[offset + 2]; c1 += c0;
c0 += data[offset + 3]; c1 += c0;
c0 += data[offset + 4]; c1 += c0;
c0 += data[offset + 5]; c1 += c0;
c0 += data[offset + 6]; c1 += c0;
c0 += data[offset + 7]; c1 += c0;
c0 += data[offset + 8]; c1 += c0;
c0 += data[offset + 9]; c1 += c0;
c0 += data[offset + 10]; c1 += c0;
c0 += data[offset + 11]; c1 += c0;
c0 += data[offset + 12]; c1 += c0;
c0 += data[offset + 13]; c1 += c0;
c0 += data[offset + 14]; c1 += c0;
c0 += data[offset + 15]; c1 += c0;
offset += 16;
}
while (length-- > 0)
{
c0 += data[offset++];
c1 += c0;
}
c0 %= F64BASE;
c1 %= F64BASE;
}
// Return recombined sums
_hash = (c1 << 32) | c0;
}
}
}

View File

@@ -0,0 +1,46 @@
using System;
namespace SabreTools.Hashing.Checksum
{
/// <see href="https://github.com/ocornut/meka/blob/master/meka/srcs/checksum.cpp"/>
public class MekaCrc : ChecksumBase<ulong>
{
/// <inheritdoc/>
public override int HashSize => 64;
public MekaCrc()
{
Initialize();
}
/// <summary>
/// Reset the internal hashing state
/// </summary>
public override void Initialize()
{
_hash = 0;
}
/// <inheritdoc/>
/// <remarks>The original code limits the maximum processed size to 8KiB</remarks>
protected override void HashCore(byte[] data, int offset, int length)
{
// Read the current hash into a byte array
byte[] temp = BitConverter.GetBytes(_hash);
// Loop over the input and process
for (int i = 0; i < length; i++)
{
byte v = data[offset + i];
unchecked
{
temp[v & 7]++;
temp[v >> 5]++;
}
}
// Convert the hash back into a value
_hash = BitConverter.ToUInt64(temp, 0);
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -5,60 +5,6 @@ namespace SabreTools.Hashing
#region 0-byte file constants
public const long SizeZero = 0;
public const string CRCZero = "00000000";
public static readonly byte[] CRCZeroBytes = [0x00, 0x00, 0x00, 0x00];
public const string MD5Zero = "d41d8cd98f00b204e9800998ecf8427e";
public static readonly byte[] MD5ZeroBytes = [ 0xd4, 0x1d, 0x8c, 0xd9,
0x8f, 0x00, 0xb2, 0x04,
0xe9, 0x80, 0x09, 0x98,
0xec, 0xf8, 0x42, 0x7e ];
public const string SHA1Zero = "da39a3ee5e6b4b0d3255bfef95601890afd80709";
public static readonly byte[] SHA1ZeroBytes = [ 0xda, 0x39, 0xa3, 0xee,
0x5e, 0x6b, 0x4b, 0x0d,
0x32, 0x55, 0xbf, 0xef,
0x95, 0x60, 0x18, 0x90,
0xaf, 0xd8, 0x07, 0x09 ];
public const string SHA256Zero = "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad";
public static readonly byte[] SHA256ZeroBytes = [ 0xba, 0x78, 0x16, 0xbf,
0x8f, 0x01, 0xcf, 0xea,
0x41, 0x41, 0x40, 0xde,
0x5d, 0xae, 0x22, 0x23,
0xb0, 0x03, 0x61, 0xa3,
0x96, 0x17, 0x7a, 0x9c,
0xb4, 0x10, 0xff, 0x61,
0xf2, 0x00, 0x15, 0xad ];
public const string SHA384Zero = "cb00753f45a35e8bb5a03d699ac65007272c32ab0eded1631a8b605a43ff5bed8086072ba1e7cc2358baeca134c825a7";
public static readonly byte[] SHA384ZeroBytes = [ 0xcb, 0x00, 0x75, 0x3f,
0x45, 0xa3, 0x5e, 0x8b,
0xb5, 0xa0, 0x3d, 0x69,
0x9a, 0xc6, 0x50, 0x07,
0x27, 0x2c, 0x32, 0xab,
0x0e, 0xde, 0xd1, 0x63,
0x1a, 0x8b, 0x60, 0x5a,
0x43, 0xff, 0x5b, 0xed,
0x80, 0x86, 0x07, 0x2b,
0xa1, 0xe7, 0xcc, 0x23,
0x58, 0xba, 0xec, 0xa1,
0x34, 0xc8, 0x25, 0xa7 ];
public const string SHA512Zero = "ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f";
public static readonly byte[] SHA512ZeroBytes = [ 0xdd, 0xaf, 0x35, 0xa1,
0x93, 0x61, 0x7a, 0xba,
0xcc, 0x41, 0x73, 0x49,
0xae, 0x20, 0x41, 0x31,
0x12, 0xe6, 0xfa, 0x4e,
0x89, 0xa9, 0x7e, 0xa2,
0x0a, 0x9e, 0xee, 0xe6,
0x4b, 0x55, 0xd3, 0x9a,
0x21, 0x92, 0x99, 0x2a,
0x27, 0x4f, 0xc1, 0xa8,
0x36, 0xba, 0x3c, 0x23,
0xa3, 0xfe, 0xeb, 0xbd,
0x45, 0x4d, 0x44, 0x23,
0x64, 0x3c, 0xe8, 0x0e,
0x2a, 0x9a, 0xc9, 0x4f,
0xa5, 0x4c, 0xa4, 0x9f ];
public const string SpamSumZero = "QXX";
public static readonly byte[] SpamSumZeroBytes = [0x51, 0x58, 0x58];
#endregion
@@ -73,4 +19,4 @@ namespace SabreTools.Hashing
#endregion
}
}
}

View File

@@ -1,69 +0,0 @@
using System;
namespace SabreTools.Hashing.Crc
{
internal class CrcRunner
{
/// <summary>
/// Definition used to create the runner
/// </summary>
private readonly CrcDefinition _definition;
/// <summary>
/// Table used for calculation steps
/// </summary>
private readonly CrcTable _table;
/// <summary>
/// The current value of the hash
/// </summary>
private ulong _hash;
public CrcRunner(CrcDefinition def)
{
// Check for a valid bit width
if (def.Width < 0 || def.Width > 64)
throw new ArgumentOutOfRangeException(nameof(def));
_definition = def;
_table = new CrcTable(def);
_hash = def.Init;
}
/// <summary>
/// Reset the internal hashing state
/// </summary>
public void Reset()
{
_hash = _definition.Init;
}
/// <summary>
/// Hash a block of data and append it to the existing hash
/// </summary>
/// <param name="data">Byte array representing the data</param>
/// <param name="offset">Offset in the byte array to include</param>
/// <param name="length">Length of the data to hash</param>
public void TransformBlock(byte[] data, int offset, int length)
=> _table.TransformBlock(ref _hash, data, offset, length);
/// <summary>
/// Finalize the hash and return as a byte array
/// </summary>
public byte[] Finalize()
{
// Create a copy of the hash
ulong localHash = _hash;
// Handle mutual reflection
if (_definition.ReflectIn ^ _definition.ReflectOut)
localHash = BitOperations.ReverseBits(localHash, _definition.Width);
// Handle XOR
localHash ^= _definition.XorOut;
// Process the value and return
return BitOperations.ClampValueToBytes(localHash, _definition.Width);
}
}
}

View File

@@ -1,230 +0,0 @@
namespace SabreTools.Hashing.Crc
{
internal class CrcTable
{
/// <summary>
/// Indicates if CRC should be processed bitwise instead of bytewise
/// </summary>
private readonly bool _processBitwise;
/// <summary>
/// Number of bits to process at a time
/// </summary>
private readonly int _processBits;
/// <summary>
/// Bit shift based on the CRC width
/// </summary>
private readonly int _bitShift;
/// <summary>
/// Bit mask based on the CRC width
/// </summary>
private readonly ulong _bitMask;
/// <summary>
/// Mapping table
/// </summary>
private readonly ulong[,] _table;
/// <summary>
/// Definition used to build the table
/// </summary>
private readonly CrcDefinition _definition;
/// <summary>
/// Number of slices in the optimized table
/// </summary>
private const int SliceCount = 8;
public CrcTable(CrcDefinition def)
{
// Set the accessible fields
_definition = def;
_processBitwise = _definition.Width < 8;
_processBits = _processBitwise ? 1 : 8;
_bitShift = _definition.Width - _processBits;
_bitMask = 1UL << (_definition.Width - 1);
// Initialize the internal
_table = new ulong[SliceCount, 1 << _processBits];
// Build the standard table
for (int i = 0; i < 1 << _processBits; i++)
{
// Get the starting value for this index
ulong point = (ulong)i;
if (!_processBitwise && def.ReflectIn)
point = BitOperations.ReverseBits(point, _processBits);
// Shift to account for storage
point <<= _definition.Width - _processBits;
// Accumulate the value
for (int j = 0; j < 8; j++)
{
if ((point & _bitMask) > 0)
point = (point << 1) ^ def.Poly;
else
point <<= 1;
}
// Reflect if necessary
if (def.ReflectIn)
point = BitOperations.ReverseBits(point, def.Width);
// Shift back to account for storage
point &= ulong.MaxValue >> (64 - def.Width);
// Assign to both tables
_table[0, i] = point;
}
// Skip building the optimized table for bitwise processing
if (_processBitwise)
return;
// Build the optimized table for non-bitwise processing
for (int i = 1; i < SliceCount; i++)
{
// Build each slice from the previous
for (int j = 0; j < 1 << _processBits; j++)
{
ulong last = _table[i - 1, j];
if (_definition.ReflectIn)
_table[i, j] = (last >> _processBits) ^ _table[0, (byte)last];
else
_table[i, j] = (last << _processBits) ^ _table[0, (byte)(last >> _bitShift)];
}
}
}
/// <summary>
/// Hash a block of data and append it to the existing hash
/// </summary>
/// <param name="hash">Current hash value, updated on run</param>
/// <param name="data">Byte array representing the data</param>
/// <param name="offset">Offset in the byte array to include</param>
/// <param name="length">Length of the data to hash</param>
public void TransformBlock(ref ulong hash, byte[] data, int offset, int length)
{
// Empty data just returns
if (data.Length == 0)
return;
// Check for valid offset and length
if (offset > data.Length)
throw new System.ArgumentOutOfRangeException(nameof(offset));
else if (offset + length > data.Length)
throw new System.ArgumentOutOfRangeException(nameof(length));
// Try transforming fast first
if (TransformBlockFast(ref hash, data, offset, length))
return;
// Process the data byte-wise
for (int i = offset; i < offset + length; i++)
{
PerformChecksumStep(ref hash, data, i);
}
}
/// <summary>
/// Perform a single checksum step
/// </summary>
/// <param name="hash">Current hash value, updated on run</param>
/// <param name="data">Byte array representing the data</param>
/// <param name="offset">Offset in the data to process</param>
private void PerformChecksumStep(ref ulong hash, byte[] data, int offset)
{
// Per-bit processing
if (_processBitwise)
{
for (int b = 0; b < 8; b++)
{
if (_definition.ReflectIn)
hash = (hash >> _processBits) ^ _table[0, (byte)(hash & 1) ^ ((byte)(data[offset] >> b) & 1)];
else
hash = (hash << _processBits) ^ _table[0, (byte)((hash >> _bitShift) & 1) ^ ((byte)(data[offset] >> (7 - b)) & 1)];
}
}
// Per-byte processing
else
{
if (_definition.ReflectIn)
hash = (hash >> _processBits) ^ _table[0, (byte)hash ^ data[offset]];
else
hash = (hash << _processBits) ^ _table[0, ((byte)(hash >> _bitShift)) ^ data[offset]];
}
}
/// <summary>
/// Perform an optimized transform step
/// </summary>
private bool TransformBlockFast(ref ulong hash, byte[] data, int offset, int length)
{
// Bitwise transformations are not optimized
if (_processBitwise)
return false;
// Check for optimizable transformations
if (_definition.Width == 32 && _definition.ReflectIn)
{
TransformBlockFast32Reflect(ref hash, data, offset, length);
return true;
}
return false;
}
/// <summary>
/// Optimized transformation for 32-bit CRC with reflection
/// </summary>
private void TransformBlockFast32Reflect(ref ulong hash, byte[] data, int offset, int length)
{
// Process on a copy of the hash
ulong local = hash;
// Process aligned data
if (length > 8)
{
long end = offset + (length & ~(uint)7);
length &= 7;
while (offset < end)
{
ulong low = local ^ (uint)(
(data[offset + 0] )
+ (data[offset + 1] << 8 )
+ (data[offset + 2] << 16)
+ (data[offset + 3] << 24));
ulong high = (uint)(
+ (data[offset + 4] << 32)
+ (data[offset + 5] << 40)
+ (data[offset + 6] << 48)
+ (data[offset + 7] << 56));
offset += 8;
local = _table[7, (byte)(low )]
^ _table[6, (byte)(low >> 8 )]
^ _table[5, (byte)(low >> 16 )]
^ _table[4, (byte)(low >> 24 )]
^ _table[3, (byte)(high )]
^ _table[2, (byte)(high >> 8 )]
^ _table[1, (byte)(high >> 16)]
^ _table[0, (byte)(high >> 24)];
}
}
// Process unaligned data
while (length-- != 0)
{
PerformChecksumStep(ref local, data, offset++);
}
// Assign the new hash value
hash = local;
}
}
}

View File

@@ -1,793 +0,0 @@
namespace SabreTools.Hashing.Crc
{
/// <see href="https://reveng.sourceforge.io/crc-catalogue/all.htm#crc.legend"/>
internal static class StandardDefinitions
{
#region CRC-16
/// <summary>
/// CRC-16/ARC [ARC, CRC-16, CRC-16/LHA, CRC-IBM]
/// </summary>
public static readonly CrcDefinition CRC16_ARC = new()
{
Width = 16,
Poly = 0x8005,
Init = 0x0000,
ReflectIn = true,
ReflectOut = true,
XorOut = 0x0000,
};
/// <summary>
/// CRC-16/CDMA2000
/// </summary>
public static readonly CrcDefinition CRC16_CDMA2000 = new()
{
Width = 16,
Poly = 0xc867,
Init = 0xffff,
ReflectIn = false,
ReflectOut = false,
XorOut = 0x0000,
};
/// <summary>
/// CRC-16/CMS
/// </summary>
public static readonly CrcDefinition CRC16_CMS = new()
{
Width = 16,
Poly = 0x8005,
Init = 0xffff,
ReflectIn = false,
ReflectOut = false,
XorOut = 0x0000,
};
/// <summary>
/// CRC-16/DDS-110
/// </summary>
public static readonly CrcDefinition CRC16_DDS110 = new()
{
Width = 16,
Poly = 0x8005,
Init = 0x800d,
ReflectIn = false,
ReflectOut = false,
XorOut = 0x0000,
};
/// <summary>
/// CRC-16/DECT-R [R-CRC-16]
/// </summary>
public static readonly CrcDefinition CRC16_DECTR = new()
{
Width = 16,
Poly = 0x0589,
Init = 0x0000,
ReflectIn = false,
ReflectOut = false,
XorOut = 0x0001,
};
/// <summary>
/// CRC-16/DECT-X [X-CRC-16]
/// </summary>
public static readonly CrcDefinition CRC16_DECTX = new()
{
Width = 16,
Poly = 0x0589,
Init = 0x0000,
ReflectIn = false,
ReflectOut = false,
XorOut = 0x0000,
};
/// <summary>
/// CRC-16/DNP
/// </summary>
public static readonly CrcDefinition CRC16_DNP = new()
{
Width = 16,
Poly = 0x3d65,
Init = 0x0000,
ReflectIn = true,
ReflectOut = true,
XorOut = 0xffff,
};
/// <summary>
/// CRC-16/EN-13757
/// </summary>
public static readonly CrcDefinition CRC16_EN13757 = new()
{
Width = 16,
Poly = 0x3d65,
Init = 0x0000,
ReflectIn = false,
ReflectOut = false,
XorOut = 0xffff,
};
/// <summary>
/// CRC-16/GENIBUS [CRC-16/DARC, CRC-16/EPC, CRC-16/EPC-C1G2, CRC-16/I-CODE]
/// </summary>
public static readonly CrcDefinition CRC16_GENIBUS = new()
{
Width = 16,
Poly = 0x1021,
Init = 0xffff,
ReflectIn = false,
ReflectOut = false,
XorOut = 0xffff,
};
/// <summary>
/// CRC-16/GSM
/// </summary>
public static readonly CrcDefinition CRC16_GSM = new()
{
Width = 16,
Poly = 0x1021,
Init = 0x0000,
ReflectIn = false,
ReflectOut = false,
XorOut = 0xffff,
};
/// <summary>
/// CRC-16/IBM-3740 [CRC-16/AUTOSAR, CRC-16/CCITT-FALSE]
/// </summary>
public static readonly CrcDefinition CRC16_IBM3740 = new()
{
Width = 16,
Poly = 0x1021,
Init = 0xffff,
ReflectIn = false,
ReflectOut = false,
XorOut = 0x0000,
};
/// <summary>
/// CRC-16/IBM-SDLC [CRC-16/ISO-HDLC, CRC-16/ISO-IEC-14443-3-B, CRC-16/X-25, CRC-B, X-25]
/// </summary>
public static readonly CrcDefinition CRC16_IBMSDLC = new()
{
Width = 16,
Poly = 0x1021,
Init = 0xffff,
ReflectIn = true,
ReflectOut = true,
XorOut = 0xffff,
};
/// <summary>
/// CRC-16/ISO-IEC-14443-3-A [CRC-A]
/// </summary>
public static readonly CrcDefinition CRC16_ISOIEC144433A = new()
{
Width = 16,
Poly = 0x1021,
Init = 0xc6c6,
ReflectIn = true,
ReflectOut = true,
XorOut = 0x0000,
};
/// <summary>
/// CRC-16/KERMIT [CRC-16/BLUETOOTH, CRC-16/CCITT, CRC-16/CCITT-TRUE, CRC-16/V-41-LSB, CRC-CCITT, KERMIT]
/// </summary>
public static readonly CrcDefinition CRC16_KERMIT = new()
{
Width = 16,
Poly = 0x1021,
Init = 0x0000,
ReflectIn = true,
ReflectOut = true,
XorOut = 0x0000,
};
/// <summary>
/// CRC-16/LJ1200
/// </summary>
public static readonly CrcDefinition CRC16_LJ1200 = new()
{
Width = 16,
Poly = 0x6f63,
Init = 0x0000,
ReflectIn = false,
ReflectOut = false,
XorOut = 0x0000,
};
/// <summary>
/// CRC-16/M17
/// </summary>
public static readonly CrcDefinition CRC16_M17 = new()
{
Width = 16,
Poly = 0x5935,
Init = 0xffff,
ReflectIn = false,
ReflectOut = false,
XorOut = 0x0000,
};
/// <summary>
/// CRC-16/MAXIM-DOW [CRC-16/MAXIM]
/// </summary>
public static readonly CrcDefinition CRC16_MAXIMDOW = new()
{
Width = 16,
Poly = 0x8005,
Init = 0x0000,
ReflectIn = true,
ReflectOut = true,
XorOut = 0xffff,
};
/// <summary>
/// CRC-16/MCRF4XX
/// </summary>
public static readonly CrcDefinition CRC16_MCRF4XX = new()
{
Width = 16,
Poly = 0x1021,
Init = 0xffff,
ReflectIn = true,
ReflectOut = true,
XorOut = 0x0000,
};
/// <summary>
/// CRC-16/MODBUS [MODBUS]
/// </summary>
public static readonly CrcDefinition CRC16_MODBUS = new()
{
Width = 16,
Poly = 0x8005,
Init = 0xffff,
ReflectIn = true,
ReflectOut = true,
XorOut = 0x0000,
};
/// <summary>
/// CRC-16/NRSC-5
/// </summary>
public static readonly CrcDefinition CRC16_NRSC5 = new()
{
Width = 16,
Poly = 0x080b,
Init = 0xffff,
ReflectIn = true,
ReflectOut = true,
XorOut = 0x0000,
};
/// <summary>
/// CRC-16/OPENSAFETY-A
/// </summary>
public static readonly CrcDefinition CRC16_OPENSAFETYA = new()
{
Width = 16,
Poly = 0x5935,
Init = 0x0000,
ReflectIn = false,
ReflectOut = false,
XorOut = 0x0000,
};
/// <summary>
/// CRC-16/OPENSAFETY-B
/// </summary>
public static readonly CrcDefinition CRC16_OPENSAFETYB = new()
{
Width = 16,
Poly = 0x755b,
Init = 0x0000,
ReflectIn = false,
ReflectOut = false,
XorOut = 0x0000,
};
/// <summary>
/// CRC-16/PROFIBUS [CRC-16/IEC-61158-2]
/// </summary>
public static readonly CrcDefinition CRC16_PROFIBUS = new()
{
Width = 16,
Poly = 0x1dcf,
Init = 0xffff,
ReflectIn = false,
ReflectOut = false,
XorOut = 0xffff,
};
/// <summary>
/// CRC-16/RIELLO
/// </summary>
public static readonly CrcDefinition CRC16_RIELLO = new()
{
Width = 16,
Poly = 0x1021,
Init = 0xb2aa,
ReflectIn = true,
ReflectOut = true,
XorOut = 0x0000,
};
/// <summary>
/// CRC-16/SPI-FUJITSU [CRC-16/AUG-CCITT]
/// </summary>
public static readonly CrcDefinition CRC16_SPIFUJITSU = new()
{
Width = 16,
Poly = 0x1021,
Init = 0x1d0f,
ReflectIn = false,
ReflectOut = false,
XorOut = 0x0000,
};
/// <summary>
/// CRC-16/T10-DIF
/// </summary>
public static readonly CrcDefinition CRC16_T10DIF = new()
{
Width = 16,
Poly = 0x8bb7,
Init = 0x0000,
ReflectIn = false,
ReflectOut = false,
XorOut = 0x0000,
};
/// <summary>
/// CRC-16/TELEDISK
/// </summary>
public static readonly CrcDefinition CRC16_TELEDISK = new()
{
Width = 16,
Poly = 0xa097,
Init = 0x0000,
ReflectIn = false,
ReflectOut = false,
XorOut = 0x0000,
};
/// <summary>
/// CRC-16/TMS37157
/// </summary>
public static readonly CrcDefinition CRC16_TMS37157 = new()
{
Width = 16,
Poly = 0x1021,
Init = 0x89ec,
ReflectIn = true,
ReflectOut = true,
XorOut = 0x0000,
};
/// <summary>
/// CRC-16/UMTS [CRC-16/BUYPASS, CRC-16/VERIFONE]
/// </summary>
public static readonly CrcDefinition CRC16_UMTS = new()
{
Width = 16,
Poly = 0x8005,
Init = 0x0000,
ReflectIn = false,
ReflectOut = false,
XorOut = 0x0000,
};
/// <summary>
/// CRC-16/USB
/// </summary>
public static readonly CrcDefinition CRC16_USB = new()
{
Width = 16,
Poly = 0x8005,
Init = 0xffff,
ReflectIn = true,
ReflectOut = true,
XorOut = 0xffff,
};
/// <summary>
/// CRC-16/XMODEM [CRC-16/ACORN, CRC-16/LTE, CRC-16/V-41-MSB, XMODEM, ZMODEM]
/// </summary>
public static readonly CrcDefinition CRC16_XMODEM = new()
{
Width = 16,
Poly = 0x1021,
Init = 0x0000,
ReflectIn = false,
ReflectOut = false,
XorOut = 0x0000,
};
#endregion
#region CRC-24
/// <summary>
/// CRC-24/BLE
/// </summary>
public static readonly CrcDefinition CRC24_BLE = new()
{
Width = 24,
Poly = 0x00065b,
Init = 0x555555,
ReflectIn = true,
ReflectOut = true,
XorOut = 0x000000,
};
/// <summary>
/// CRC-24/FLEXRAY-A
/// </summary>
public static readonly CrcDefinition CRC24_FLEXRAYA = new()
{
Width = 24,
Poly = 0x5d6dcb,
Init = 0xfedcba,
ReflectIn = false,
ReflectOut = false,
XorOut = 0x000000,
};
/// <summary>
/// CRC-24/FLEXRAY-B
/// </summary>
public static readonly CrcDefinition CRC24_FLEXRAYB = new()
{
Width = 24,
Poly = 0x5d6dcb,
Init = 0xabcdef,
ReflectIn = false,
ReflectOut = false,
XorOut = 0x000000,
};
/// <summary>
/// CRC-24/INTERLAKEN
/// </summary>
public static readonly CrcDefinition CRC24_INTERLAKEN = new()
{
Width = 24,
Poly = 0x328b63,
Init = 0xffffff,
ReflectIn = false,
ReflectOut = false,
XorOut = 0xffffff,
};
/// <summary>
/// CRC-24/LTE-A
/// </summary>
public static readonly CrcDefinition CRC24_LTEA = new()
{
Width = 24,
Poly = 0x864cfb,
Init = 0x000000,
ReflectIn = false,
ReflectOut = false,
XorOut = 0x000000,
};
/// <summary>
/// CRC-24/LTE-B
/// </summary>
public static readonly CrcDefinition CRC24_LTEB = new()
{
Width = 24,
Poly = 0x800063,
Init = 0x000000,
ReflectIn = false,
ReflectOut = false,
XorOut = 0x000000,
};
/// <summary>
/// CRC-24/OPENPGP
/// </summary>
public static readonly CrcDefinition CRC24_OPENPGP = new()
{
Width = 24,
Poly = 0x864cfb,
Init = 0xb704ce,
ReflectIn = false,
ReflectOut = false,
XorOut = 0x000000,
};
/// <summary>
/// CRC-24/OS-9
/// </summary>
public static readonly CrcDefinition CRC24_OS9 = new()
{
Width = 24,
Poly = 0x800063,
Init = 0xffffff,
ReflectIn = false,
ReflectOut = false,
XorOut = 0xffffff,
};
#endregion
#region CRC-32
/// <summary>
/// CRC-32/AIXM
/// </summary>
public static readonly CrcDefinition CRC32_AIXM = new()
{
Width = 32,
Poly = 0x814141ab,
Init = 0x00000000,
ReflectIn = false,
ReflectOut = false,
XorOut = 0x00000000,
};
/// <summary>
/// CRC-32/AUTOSAR
/// </summary>
public static readonly CrcDefinition CRC32_AUTOSAR = new()
{
Width = 32,
Poly = 0xf4acfb13,
Init = 0xffffffff,
ReflectIn = true,
ReflectOut = true,
XorOut = 0xffffffff,
};
/// <summary>
/// CRC-32/BASE91-D
/// </summary>
public static readonly CrcDefinition CRC32_BASE91D = new()
{
Width = 32,
Poly = 0xa833982b,
Init = 0xffffffff,
ReflectIn = true,
ReflectOut = true,
XorOut = 0xffffffff,
};
/// <summary>
/// CRC-32/BZIP2
/// </summary>
public static readonly CrcDefinition CRC32_BZIP2 = new()
{
Width = 32,
Poly = 0x04c11db7,
Init = 0xffffffff,
ReflectIn = false,
ReflectOut = false,
XorOut = 0xffffffff,
};
/// <summary>
/// CRC-32/CD-ROM-EDC
/// </summary>
public static readonly CrcDefinition CRC32_CDROMEDC = new()
{
Width = 32,
Poly = 0x8001801b,
Init = 0x00000000,
ReflectIn = true,
ReflectOut = true,
XorOut = 0x00000000,
};
/// <summary>
/// CRC-32/CKSUM
/// </summary>
public static readonly CrcDefinition CRC32_CKSUM = new()
{
Width = 32,
Poly = 0x04c11db7,
Init = 0x00000000,
ReflectIn = false,
ReflectOut = false,
XorOut = 0xffffffff,
};
/// <summary>
/// CRC-32/ISCSI
/// </summary>
public static readonly CrcDefinition CRC32_ISCSI = new()
{
Width = 32,
Poly = 0x1edc6f41,
Init = 0xffffffff,
ReflectIn = true,
ReflectOut = true,
XorOut = 0xffffffff,
};
/// <summary>
/// CRC-32/ISO-HDLC
/// </summary>
public static readonly CrcDefinition CRC32_ISOHDLC = new()
{
Width = 32,
Poly = 0x04c11db7,
Init = 0xffffffff,
ReflectIn = true,
ReflectOut = true,
XorOut = 0xffffffff,
};
/// <summary>
/// CRC-32/JAMCRC
/// </summary>
public static readonly CrcDefinition CRC32_JAMCRC = new()
{
Width = 32,
Poly = 0x04c11db7,
Init = 0xffffffff,
ReflectIn = true,
ReflectOut = true,
XorOut = 0x00000000,
};
/// <summary>
/// CRC-32/MEF
/// </summary>
public static readonly CrcDefinition CRC32_MEF = new()
{
Width = 32,
Poly = 0x741b8cd7,
Init = 0xffffffff,
ReflectIn = true,
ReflectOut = true,
XorOut = 0x00000000,
};
/// <summary>
/// CRC-32/MPEG-2
/// </summary>
public static readonly CrcDefinition CRC32_MPEG2 = new()
{
Width = 32,
Poly = 0x04c11db7,
Init = 0xffffffff,
ReflectIn = false,
ReflectOut = false,
XorOut = 0x00000000,
};
/// <summary>
/// CRC-32/XFER
/// </summary>
public static readonly CrcDefinition CRC32_XFER = new()
{
Width = 32,
Poly = 0x000000af,
Init = 0x00000000,
ReflectIn = false,
ReflectOut = false,
XorOut = 0x00000000,
};
#endregion
#region CRC-40
/// <summary>
/// CRC-40/GSM
/// </summary>
public static readonly CrcDefinition CRC40_GSM = new()
{
Width = 40,
Poly = 0x0004820009,
Init = 0x0000000000,
ReflectIn = false,
ReflectOut = false,
XorOut = 0xffffffffff,
};
#endregion
#region CRC-64
/// <summary>
/// CRC-64/ECMA-182
/// </summary>
public static readonly CrcDefinition CRC64_ECMA182 = new()
{
Width = 64,
Poly = 0x42f0e1eba9ea3693,
Init = 0x0000000000000000,
ReflectIn = false,
ReflectOut = false,
XorOut = 0x0000000000000000,
};
/// <summary>
/// CRC-64/GO-ISO
/// </summary>
public static readonly CrcDefinition CRC64_GOISO = new()
{
Width = 64,
Poly = 0x000000000000001b,
Init = 0xffffffffffffffff,
ReflectIn = true,
ReflectOut = true,
XorOut = 0xffffffffffffffff,
};
/// <summary>
/// CRC-64/MS
/// </summary>
public static readonly CrcDefinition CRC64_MS = new()
{
Width = 64,
Poly = 0x259c84cba6426349,
Init = 0xffffffffffffffff,
ReflectIn = true,
ReflectOut = true,
XorOut = 0x0000000000000000,
};
/// <summary>
/// CRC-64/NVME
/// </summary>
public static readonly CrcDefinition CRC64_NVME = new()
{
Width = 64,
Poly = 0xad93d23594c93659,
Init = 0xffffffffffffffff,
ReflectIn = true,
ReflectOut = true,
XorOut = 0xffffffffffffffff,
};
/// <summary>
/// CRC-64/REDIS
/// </summary>
public static readonly CrcDefinition CRC64_REDIS = new()
{
Width = 64,
Poly = 0xad93d23594c935a9,
Init = 0x0000000000000000,
ReflectIn = true,
ReflectOut = true,
XorOut = 0x0000000000000000,
};
/// <summary>
/// CRC-64/WE
/// </summary>
public static readonly CrcDefinition CRC64_WE = new()
{
Width = 64,
Poly = 0x42f0e1eba9ea3693,
Init = 0xffffffffffffffff,
ReflectIn = false,
ReflectOut = false,
XorOut = 0xffffffffffffffff,
};
/// <summary>
/// CRC-64/XZ
/// </summary>
public static readonly CrcDefinition CRC64_XZ = new()
{
Width = 64,
Poly = 0x42f0e1eba9ea3693,
Init = 0xffffffffffffffff,
ReflectIn = true,
ReflectOut = true,
XorOut = 0xffffffffffffffff,
};
#endregion
}
}

View File

@@ -1,11 +1,182 @@
namespace SabreTools.Hashing.Tiger
namespace SabreTools.Hashing.CryptographicHash
{
/// <summary>
/// Tiger S boxes
/// </summary>
public static class SBoxes
internal static class Constants
{
public static readonly ulong[] Table =
// <see href="https://datatracker.ietf.org/doc/html/rfc1115"/>
#region MD2
/// <summary>
/// S-Boxes
/// </summary>
public static readonly byte[] MD2SBox =
[
0x29, 0x2E, 0x43, 0xC9, 0xA2, 0xD8, 0x7C, 0x01, 0x3D, 0x36, 0x54, 0xA1, 0xEC, 0xF0, 0x06, 0x13,
0x62, 0xA7, 0x05, 0xF3, 0xC0, 0xC7, 0x73, 0x8C, 0x98, 0x93, 0x2B, 0xD9, 0xBC, 0x4C, 0x82, 0xCA,
0x1E, 0x9B, 0x57, 0x3C, 0xFD, 0xD4, 0xE0, 0x16, 0x67, 0x42, 0x6F, 0x18, 0x8A, 0x17, 0xE5, 0x12,
0xBE, 0x4E, 0xC4, 0xD6, 0xDA, 0x9E, 0xDE, 0x49, 0xA0, 0xFB, 0xF5, 0x8E, 0xBB, 0x2F, 0xEE, 0x7A,
0xA9, 0x68, 0x79, 0x91, 0x15, 0xB2, 0x07, 0x3F, 0x94, 0xC2, 0x10, 0x89, 0x0B, 0x22, 0x5F, 0x21,
0x80, 0x7F, 0x5D, 0x9A, 0x5A, 0x90, 0x32, 0x27, 0x35, 0x3E, 0xCC, 0xE7, 0xBF, 0xF7, 0x97, 0x03,
0xFF, 0x19, 0x30, 0xB3, 0x48, 0xA5, 0xB5, 0xD1, 0xD7, 0x5E, 0x92, 0x2A, 0xAC, 0x56, 0xAA, 0xC6,
0x4F, 0xB8, 0x38, 0xD2, 0x96, 0xA4, 0x7D, 0xB6, 0x76, 0xFC, 0x6B, 0xE2, 0x9C, 0x74, 0x04, 0xF1,
0x45, 0x9D, 0x70, 0x59, 0x64, 0x71, 0x87, 0x20, 0x86, 0x5B, 0xCF, 0x65, 0xE6, 0x2D, 0xA8, 0x02,
0x1B, 0x60, 0x25, 0xAD, 0xAE, 0xB0, 0xB9, 0xF6, 0x1C, 0x46, 0x61, 0x69, 0x34, 0x40, 0x7E, 0x0F,
0x55, 0x47, 0xA3, 0x23, 0xDD, 0x51, 0xAF, 0x3A, 0xC3, 0x5C, 0xF9, 0xCE, 0xBA, 0xC5, 0xEA, 0x26,
0x2C, 0x53, 0x0D, 0x6E, 0x85, 0x28, 0x84, 0x09, 0xD3, 0xDF, 0xCD, 0xF4, 0x41, 0x81, 0x4D, 0x52,
0x6A, 0xDC, 0x37, 0xC8, 0x6C, 0xC1, 0xAB, 0xFA, 0x24, 0xE1, 0x7B, 0x08, 0x0C, 0xBD, 0xB1, 0x4A,
0x78, 0x88, 0x95, 0x8B, 0xE3, 0x63, 0xE8, 0x6D, 0xE9, 0xCB, 0xD5, 0xFE, 0x3B, 0x00, 0x1D, 0x39,
0xF2, 0xEF, 0xB7, 0x0E, 0x66, 0x58, 0xD0, 0xE4, 0xA6, 0x77, 0x72, 0xF8, 0xEB, 0x75, 0x4B, 0x0A,
0x31, 0x44, 0x50, 0xB4, 0x8F, 0xED, 0x1F, 0x1A, 0xDB, 0x99, 0x8D, 0x33, 0x9F, 0x11, 0x83, 0x14,
];
#endregion
// <see href="https://datatracker.ietf.org/doc/html/rfc1320"/>
#region MD4
public const uint MD4SeedA = 0x67452301;
public const uint MD4SeedB = 0xefcdab89;
public const uint MD4SeedC = 0x98badcfe;
public const uint MD4SeedD = 0x10325476;
public const uint MD4Round1 = 0x00000000;
public const uint MD4Round2 = 0x5A827999;
public const uint MD4Round3 = 0x6ED9EBA1;
#endregion
// <see href="https://cdn.standards.iteh.ai/samples/39876/10f9f9f4bb614eaaaeba7e157e183ca3/ISO-IEC-10118-3-2004.pdf"/>
#region RIPEMD-128 / RIPEMD-256
public const uint RMD128Round00To15 = 0x00000000;
public const uint RMD128Round16To31 = 0x5A827999;
public const uint RMD128Round32To47 = 0x6ED9EBA1;
public const uint RMD128Round48To63 = 0x8F1BBCDC;
public const uint RMD128RoundPrime00To15 = 0x50A28BE6;
public const uint RMD128RoundPrime16To31 = 0x5C4DD124;
public const uint RMD128RoundPrime32To47 = 0x6D703EF3;
public const uint RMD128RoundPrime48To63 = 0x00000000;
public const uint RMD128Y0 = 0x67452301;
public const uint RMD128Y1 = 0xEFCDAB89;
public const uint RMD128Y2 = 0x98BADCFE;
public const uint RMD128Y3 = 0x10325476;
public const uint RMD256Y4 = 0x76543210;
public const uint RMD256Y5 = 0xFEDCBA98;
public const uint RMD256Y6 = 0x89ABCDEF;
public const uint RMD256Y7 = 0x01234567;
#endregion
// <see href="https://cdn.standards.iteh.ai/samples/39876/10f9f9f4bb614eaaaeba7e157e183ca3/ISO-IEC-10118-3-2004.pdf"/>
#region RIPEMD-160 / RIPEMD-320
public const uint RMD160Round00To15 = 0x00000000;
public const uint RMD160Round16To31 = 0x5A827999;
public const uint RMD160Round32To47 = 0x6ED9EBA1;
public const uint RMD160Round48To63 = 0x8F1BBCDC;
public const uint RMD160Round64To79 = 0xA953FD4E;
public const uint RMD160RoundPrime00To15 = 0x50A28BE6;
public const uint RMD160RoundPrime16To31 = 0x5C4DD124;
public const uint RMD160RoundPrime32To47 = 0x6D703EF3;
public const uint RMD160RoundPrime48To63 = 0x7A6D76E9;
public const uint RMD160RoundPrime64To79 = 0x00000000;
public const uint RMD160Y0 = 0x67452301;
public const uint RMD160Y1 = 0xEFCDAB89;
public const uint RMD160Y2 = 0x98BADCFE;
public const uint RMD160Y3 = 0x10325476;
public const uint RMD160Y4 = 0xC3D2E1F0;
public const uint RMD320Y5 = 0x76543210;
public const uint RMD320Y6 = 0xFEDCBA98;
public const uint RMD320Y7 = 0x89ABCDEF;
public const uint RMD320Y8 = 0x01234567;
public const uint RMD320Y9 = 0x3C2D1E0F;
/// <summary>
/// t_i
/// </summary>
public static readonly byte[] RMD160Ti =
[
11, 14, 15, 12, 5, 8, 7, 9,
11, 13, 14, 15, 6, 7, 9, 8,
7, 6, 8, 13, 11, 9, 7, 15,
7, 12, 15, 9, 11, 7, 13, 12,
11, 13, 6, 7, 14, 9, 13, 15,
14, 8, 13, 6, 5, 12, 7, 5,
11, 12, 14, 15, 14, 15, 9, 8,
9, 14, 5, 6, 8, 6, 5, 12,
9, 15, 5, 11, 6, 8, 13, 12,
5, 12, 13, 14, 11, 8, 5, 6,
];
/// <summary>
/// t'_i
/// </summary>
public static readonly byte[] RMD160Tpi =
[
8, 9, 9, 11, 13, 15, 15, 5,
7, 7, 8, 11, 14, 14, 12, 6,
9, 13, 15, 7, 12, 8, 9, 11,
7, 7, 12, 7, 6, 15, 13, 11,
9, 7, 15, 11, 8, 6, 6, 14,
12, 13, 5, 14, 13, 13, 7, 5,
15, 5, 8, 11, 14, 14, 6, 14,
6, 9, 12, 9, 12, 5, 15, 8,
8, 5, 12, 9, 12, 5, 14, 6,
8, 13, 6, 5, 15, 13, 11, 11,
];
/// <summary>
/// a_i
/// </summary>
public static readonly byte[] RMD160Ai =
[
0, 1, 2, 3, 4, 5, 6, 7,
8, 9, 10, 11, 12, 13, 14, 15,
7, 4, 13, 1, 10, 6, 15, 3,
12, 0, 9, 5, 2, 14, 11, 8,
3, 10, 14, 4, 9, 15, 8, 1,
2, 7, 0, 6, 13, 11, 5, 12,
1, 9, 11, 10, 0, 8, 12, 4,
13, 3, 7, 15, 14, 5, 6, 2,
4, 0, 5, 9, 7, 12, 2, 10,
14, 1, 3, 8, 11, 6, 15, 13,
];
/// <summary>
/// a'_i
/// </summary>
public static readonly byte[] RMD160Api =
[
5, 14, 7, 0, 9, 2, 11, 4,
13, 6, 15, 8, 1, 10, 3, 12,
6, 11, 3, 7, 0, 13, 5, 10,
14, 15, 8, 12, 4, 9, 1, 2,
15, 5, 1, 3, 7, 14, 6, 9,
11, 8, 12, 2, 10, 0, 4, 13,
8, 6, 4, 1, 3, 11, 15, 0,
5, 12, 2, 13, 9, 7, 10, 14,
12, 15, 10, 4, 1, 5, 8, 7,
6, 2, 13, 14, 0, 3, 9, 11,
];
#endregion
/// <see href="https://biham.cs.technion.ac.il/Reports/Tiger//>
#region Tiger-128 / Tiger-160 / Tiger-192
public const ulong TigerSeedA = 0x0123456789ABCDEF;
public const ulong TigerSeedB = 0xFEDCBA9876543210;
public const ulong TigerSeedC = 0xF096A5B4C3B2E187;
/// <summary>
/// S-Boxes
/// </summary>
public static readonly ulong[] TigerSBox =
[
0x02AAB17CF7E90C5E /* 0 */, 0xAC424B03E243A8EC /* 1 */,
0x72CD5BE30DD5FCD3 /* 2 */, 0x6D019B93F6F97F3A /* 3 */,
@@ -520,5 +691,7 @@ namespace SabreTools.Hashing.Tiger
0xCD56D9430EA8280E /* 1020 */, 0xC12591D7535F5065 /* 1021 */,
0xC83223F1720AEF96 /* 1022 */, 0xC3A0396F7363A51F /* 1023 */
];
#endregion
}
}
}

View File

@@ -0,0 +1,169 @@
using System;
using static SabreTools.Hashing.CryptographicHash.Constants;
namespace SabreTools.Hashing.CryptographicHash
{
/// <see href="https://datatracker.ietf.org/doc/html/rfc1115"/>
public class MD2 : MessageDigestBase<uint>
{
/// <inheritdoc/>
public override int HashSize => 128;
/// <summary>
/// Buffer for forming digest in
/// </summary>
/// <remarks>At the end, D[0...15] form the message digest</remarks>
private readonly byte[] _digest = new byte[48];
/// <summary>
/// Checksum register
/// </summary>
private readonly byte[] _checksum = new byte[16];
/// <summary>
/// Number of bytes handled, modulo 16
/// </summary>
private byte _byteCount;
/// <summary>
/// Last checksum char saved
/// </summary>
private byte _lastByte;
public MD2() : base()
{
}
/// <inheritdoc/>
protected override void ResetImpl()
{
Array.Clear(_digest, 0, _digest.Length);
Array.Clear(_checksum, 0, _checksum.Length);
_byteCount = 0;
_lastByte = 0;
}
/// <inheritdoc/>
protected override void HashCore(byte[] data, int offset, int length)
{
// Figure out how much buffer is needed
int bufferLen = 16 - _byteCount;
// If there is buffer to fill and it will meet the limit
if (_byteCount > 0 && _byteCount + length >= 16)
{
// Fill the buffer from the input
for (int i = 0; i < bufferLen; i++)
{
// Add new character to buffer
_digest[16 + _byteCount] = data[offset + i];
_digest[32 + _byteCount] = (byte)(data[offset + i] ^ _digest[_byteCount]);
// Update checksum register C and value L
_lastByte = _checksum[_byteCount] ^= MD2SBox[0xff & (data[offset + i] ^ _lastByte)];
// Increment i by one modulo 16
_byteCount = (byte)((_byteCount + 1) & 15);
}
// Set the new values
offset += bufferLen;
length -= bufferLen;
// Run the update
Update();
}
/// Process any standalone blocks
while (length >= 16)
{
// Fill the buffer from the input
for (int i = 0; i < 16; i++)
{
// Add new character to buffer
_digest[16 + _byteCount] = data[offset + i];
_digest[32 + _byteCount] = (byte)(data[offset + i] ^ _digest[_byteCount]);
// Update checksum register C and value L
_lastByte = _checksum[_byteCount] ^= MD2SBox[0xff & (data[offset + i] ^ _lastByte)];
// Increment i by one modulo 16
_byteCount = (byte)((_byteCount + 1) & 15);
}
// Set the new values
offset += 16;
length -= 16;
// Run the update
Update();
}
// Save the remainder in the buffer
if (length > 0)
{
// Fill the buffer from the input
for (int i = 0; i < length; i++)
{
// Add new character to buffer
_digest[16 + _byteCount] = data[offset + i];
_digest[32 + _byteCount] = (byte)(data[offset + i] ^ _digest[_byteCount]);
// Update checksum register C and value L
_lastByte = _checksum[_byteCount] ^= MD2SBox[0xff & (data[offset + i] ^ _lastByte)];
// Increment i by one modulo 16
_byteCount = (byte)((_byteCount + 1) & 15);
}
}
}
/// <inheritdoc/>
protected override byte[] HashFinal()
{
// Determine the pad length
byte padLength = (byte)(16 - _byteCount);
// Pad the block
byte[] padding = new byte[padLength];
#if NETFRAMEWORK || NETSTANDARD2_0
for (int i = 0; i < padLength; i++)
{
padding[i] = padLength;
}
#else
Array.Fill(padding, padLength);
#endif
// Pad the block
HashCore(padding, 0, padLength);
HashCore(_checksum, 0, _checksum.Length);
// Get the hash
var hash = new byte[16];
Array.Copy(_digest, hash, 16);
return hash;
}
/// <summary>
/// The routine MDUPDATE updates the message digest context buffer to
/// account for the presence of the character c in the message whose
/// digest is being computed. This routine will be called for each
/// message byte in turn.
/// </summary>
/// <remarks>The following is a more efficient version of the loop</remarks>
private void Update()
{
byte t = 0;
for (byte j = 0; j < 18; j++)
{
for (byte i = 0; i < 48; i++)
{
t = _digest[i] = (byte)(_digest[i] ^ MD2SBox[t]);
}
t += j;
}
}
}
}

View File

@@ -0,0 +1,214 @@
using System;
using static SabreTools.Hashing.CryptographicHash.Constants;
using static SabreTools.Hashing.HashOperations;
namespace SabreTools.Hashing.CryptographicHash
{
/// <see href="https://datatracker.ietf.org/doc/html/rfc1320"/>
public class MD4 : MessageDigestBase<uint>
{
/// <inheritdoc/>
public override int HashSize => 128;
/// <summary>
/// Set of 4 32-bit numbers representing the hash state
/// </summary>
private readonly uint[] _state = new uint[4];
public MD4() : base()
{
}
/// <inheritdoc/>
protected override void ResetImpl()
{
_state[0] = MD4SeedA;
_state[1] = MD4SeedB;
_state[2] = MD4SeedC;
_state[3] = MD4SeedD;
}
/// <inheritdoc/>
protected override void HashCore(byte[] data, int offset, int length)
{
// Figure out how much buffer is needed
int bufferLen = (int)(_totalBytes & 0x3f);
// Increment the processed byte count
_totalBytes += length;
// If there is buffer to fill and it will meet the limit
if (bufferLen > 0 && bufferLen + length >= 64)
{
// Fill the buffer from the input
Array.Copy(data, offset, _buffer, bufferLen, 64 - bufferLen);
// Set the new values
offset += 64 - bufferLen;
length -= 64 - bufferLen;
// Split the buffer for the round
for (int i = 0; i < 16; i++)
{
_block[i] = ReadLE32(_buffer, i * 4);
}
// Run the round
Round();
bufferLen = 0;
}
/// Process any standalone blocks
while (length >= 64)
{
// Fill the buffer from the input
Array.Copy(data, offset, _buffer, 0, 64);
// Set the new values
offset += 64;
length -= 64;
// Split the buffer for the round
for (int i = 0; i < 16; i++)
{
_block[i] = ReadLE32(_buffer, i * 4);
}
// Run the round
Round();
}
// Save the remainder in the buffer
if (length > 0)
Array.Copy(data, offset, _buffer, bufferLen, length);
}
/// <inheritdoc/>
protected override byte[] HashFinal()
{
// Determine the pad length
int padLength = 64 - (int)(_totalBytes & 0x3f);
if (padLength <= 8)
padLength += 64;
// Get the total byte count in bits
long totalBitCount = _totalBytes * 8;
// Prebuild the padding
var padding = new byte[padLength];
padding[0] = 0x80;
padding[padLength - 1] = (byte)((totalBitCount >> 56) & 0xff);
padding[padLength - 2] = (byte)((totalBitCount >> 48) & 0xff);
padding[padLength - 3] = (byte)((totalBitCount >> 40) & 0xff);
padding[padLength - 4] = (byte)((totalBitCount >> 32) & 0xff);
padding[padLength - 5] = (byte)((totalBitCount >> 24) & 0xff);
padding[padLength - 6] = (byte)((totalBitCount >> 16) & 0xff);
padding[padLength - 7] = (byte)((totalBitCount >> 8) & 0xff);
padding[padLength - 8] = (byte)((totalBitCount >> 0) & 0xff);
// Pad the block
HashCore(padding, 0, padding.Length);
// Get the hash
var hash = new byte[16];
int hashOffset = 0;
// Assemble the hash array
for (int i = 0; i < _state.Length; i++)
{
byte[] segment = BitConverter.GetBytes(_state[i]);
Array.Copy(segment, 0, hash, hashOffset, 4);
hashOffset += 4;
}
return hash;
}
/// <summary>
/// Perform one round of updates on the cached values
/// </summary>
private void Round()
{
// Setup values
uint a = _state[0];
uint b = _state[1];
uint c = _state[2];
uint d = _state[3];
// Round 1
a = RotateLeft32(a + F(b, c, d) + _block[0] + MD4Round1, 3);
d = RotateLeft32(d + F(a, b, c) + _block[1] + MD4Round1, 7);
c = RotateLeft32(c + F(d, a, b) + _block[2] + MD4Round1, 11);
b = RotateLeft32(b + F(c, d, a) + _block[3] + MD4Round1, 19);
a = RotateLeft32(a + F(b, c, d) + _block[4] + MD4Round1, 3);
d = RotateLeft32(d + F(a, b, c) + _block[5] + MD4Round1, 7);
c = RotateLeft32(c + F(d, a, b) + _block[6] + MD4Round1, 11);
b = RotateLeft32(b + F(c, d, a) + _block[7] + MD4Round1, 19);
a = RotateLeft32(a + F(b, c, d) + _block[8] + MD4Round1, 3);
d = RotateLeft32(d + F(a, b, c) + _block[9] + MD4Round1, 7);
c = RotateLeft32(c + F(d, a, b) + _block[10] + MD4Round1, 11);
b = RotateLeft32(b + F(c, d, a) + _block[11] + MD4Round1, 19);
a = RotateLeft32(a + F(b, c, d) + _block[12] + MD4Round1, 3);
d = RotateLeft32(d + F(a, b, c) + _block[13] + MD4Round1, 7);
c = RotateLeft32(c + F(d, a, b) + _block[14] + MD4Round1, 11);
b = RotateLeft32(b + F(c, d, a) + _block[15] + MD4Round1, 19);
// Round 2
a = RotateLeft32(a + G(b, c, d) + _block[0] + MD4Round2, 3);
d = RotateLeft32(d + G(a, b, c) + _block[4] + MD4Round2, 5);
c = RotateLeft32(c + G(d, a, b) + _block[8] + MD4Round2, 9);
b = RotateLeft32(b + G(c, d, a) + _block[12] + MD4Round2, 13);
a = RotateLeft32(a + G(b, c, d) + _block[1] + MD4Round2, 3);
d = RotateLeft32(d + G(a, b, c) + _block[5] + MD4Round2, 5);
c = RotateLeft32(c + G(d, a, b) + _block[9] + MD4Round2, 9);
b = RotateLeft32(b + G(c, d, a) + _block[13] + MD4Round2, 13);
a = RotateLeft32(a + G(b, c, d) + _block[2] + MD4Round2, 3);
d = RotateLeft32(d + G(a, b, c) + _block[6] + MD4Round2, 5);
c = RotateLeft32(c + G(d, a, b) + _block[10] + MD4Round2, 9);
b = RotateLeft32(b + G(c, d, a) + _block[14] + MD4Round2, 13);
a = RotateLeft32(a + G(b, c, d) + _block[3] + MD4Round2, 3);
d = RotateLeft32(d + G(a, b, c) + _block[7] + MD4Round2, 5);
c = RotateLeft32(c + G(d, a, b) + _block[11] + MD4Round2, 9);
b = RotateLeft32(b + G(c, d, a) + _block[15] + MD4Round2, 13);
// Round 3
a = RotateLeft32(a + H(b, c, d) + _block[0] + MD4Round3, 3);
d = RotateLeft32(d + H(a, b, c) + _block[8] + MD4Round3, 9);
c = RotateLeft32(c + H(d, a, b) + _block[4] + MD4Round3, 11);
b = RotateLeft32(b + H(c, d, a) + _block[12] + MD4Round3, 15);
a = RotateLeft32(a + H(b, c, d) + _block[2] + MD4Round3, 3);
d = RotateLeft32(d + H(a, b, c) + _block[10] + MD4Round3, 9);
c = RotateLeft32(c + H(d, a, b) + _block[6] + MD4Round3, 11);
b = RotateLeft32(b + H(c, d, a) + _block[14] + MD4Round3, 15);
a = RotateLeft32(a + H(b, c, d) + _block[1] + MD4Round3, 3);
d = RotateLeft32(d + H(a, b, c) + _block[9] + MD4Round3, 9);
c = RotateLeft32(c + H(d, a, b) + _block[5] + MD4Round3, 11);
b = RotateLeft32(b + H(c, d, a) + _block[13] + MD4Round3, 15);
a = RotateLeft32(a + H(b, c, d) + _block[3] + MD4Round3, 3);
d = RotateLeft32(d + H(a, b, c) + _block[11] + MD4Round3, 9);
c = RotateLeft32(c + H(d, a, b) + _block[7] + MD4Round3, 11);
b = RotateLeft32(b + H(c, d, a) + _block[15] + MD4Round3, 15);
// Update stored values
_state[0] += a;
_state[1] += b;
_state[2] += c;
_state[3] += d;
}
/// <summary>
/// Auxiliary function F
/// </summary>
private static uint F(uint x, uint y, uint z) => (x & y) | (~x & z);
/// <summary>
/// Auxiliary function G
/// </summary>
private static uint G(uint x, uint y, uint z) => (x & y) | (x & z) | (y & z);
/// <summary>
/// Auxiliary function H
/// </summary>
private static uint H(uint x, uint y, uint z) => x ^ y ^ z;
}
}

View File

@@ -0,0 +1,62 @@
using System;
namespace SabreTools.Hashing.CryptographicHash
{
public abstract class MessageDigestBase : System.Security.Cryptography.HashAlgorithm
{
/// <summary>
/// Total number of bytes processed
/// </summary>
protected long _totalBytes;
/// <summary>
/// Internal byte buffer to accumulate before <see cref="_block"/>
/// </summary>
protected readonly byte[] _buffer = new byte[64];
/// <summary>
/// Reset additional values
/// </summary>
protected abstract void ResetImpl();
/// <inheritdoc/>
protected abstract override void HashCore(byte[] array, int ibStart, int cbSize);
}
public abstract class MessageDigestBase<T> : MessageDigestBase where T : struct
{
/// <summary>
/// Internal buffer for processing
/// </summary>
protected readonly T[] _block;
public MessageDigestBase()
{
if (typeof(T) == typeof(short) || typeof(T) == typeof(ushort))
_block = new T[32];
else if (typeof(T) == typeof(int) || typeof(T) == typeof(uint))
_block = new T[16];
else if (typeof(T) == typeof(long) || typeof(T) == typeof(ulong))
_block = new T[8];
else
throw new InvalidOperationException();
Initialize();
}
/// <inheritdoc/>
public override void Initialize()
{
// Reset the seed values
ResetImpl();
// Reset the byte count
_totalBytes = 0;
// Reset the buffers
Array.Clear(_buffer, 0, _buffer.Length);
Array.Clear(_block, 0, _block.Length);
}
}
}

View File

@@ -0,0 +1,447 @@
using System;
using static SabreTools.Hashing.CryptographicHash.Constants;
using static SabreTools.Hashing.HashOperations;
namespace SabreTools.Hashing.CryptographicHash
{
/// <see href="https://cdn.standards.iteh.ai/samples/39876/10f9f9f4bb614eaaaeba7e157e183ca3/ISO-IEC-10118-3-2004.pdf"/>
/// <see href="https://homes.esat.kuleuven.be/~bosselae/ripemd160/pdf/AB-9601/AB-9601.pdf"/>
public class RipeMD128 : MessageDigestBase<uint>
{
/// <inheritdoc/>
public override int HashSize => 128;
/// <summary>
/// Set of 4 32-bit numbers representing the hash state
/// </summary>
private readonly uint[] _state = new uint[4];
public RipeMD128() : base()
{
}
/// <inheritdoc/>
protected override void ResetImpl()
{
_state[0] = RMD128Y0;
_state[1] = RMD128Y1;
_state[2] = RMD128Y2;
_state[3] = RMD128Y3;
}
/// <inheritdoc/>
protected override void HashCore(byte[] data, int offset, int length)
{
// Figure out how much buffer is needed
int bufferLen = (int)(_totalBytes & 0x3f);
// Increment the processed byte count
_totalBytes += length;
// If there is buffer to fill and it will meet the limit
if (bufferLen > 0 && bufferLen + length >= 64)
{
// Fill the buffer from the input
Array.Copy(data, offset, _buffer, bufferLen, 64 - bufferLen);
// Set the new values
offset += 64 - bufferLen;
length -= 64 - bufferLen;
// Split the buffer for the round
for (int i = 0; i < 16; i++)
{
_block[i] = ReadLE32(_buffer, i * 4);
}
// Run the round
Round();
bufferLen = 0;
}
/// Process any standalone blocks
while (length >= 64)
{
// Fill the buffer from the input
Array.Copy(data, offset, _buffer, 0, 64);
// Set the new values
offset += 64;
length -= 64;
// Split the buffer for the round
for (int i = 0; i < 16; i++)
{
_block[i] = ReadLE32(_buffer, i * 4);
}
// Run the round
Round();
}
// Save the remainder in the buffer
if (length > 0)
Array.Copy(data, offset, _buffer, bufferLen, length);
}
/// <inheritdoc/>
protected override byte[] HashFinal()
{
// Determine the pad length
int padLength = 64 - (int)(_totalBytes & 0x3f);
if (padLength <= 8)
padLength += 64;
// Get the total byte count in bits
long totalBitCount = _totalBytes * 8;
// Prebuild the padding
var padding = new byte[padLength];
padding[0] = 0x80;
padding[padLength - 1] = (byte)((totalBitCount >> 56) & 0xff);
padding[padLength - 2] = (byte)((totalBitCount >> 48) & 0xff);
padding[padLength - 3] = (byte)((totalBitCount >> 40) & 0xff);
padding[padLength - 4] = (byte)((totalBitCount >> 32) & 0xff);
padding[padLength - 5] = (byte)((totalBitCount >> 24) & 0xff);
padding[padLength - 6] = (byte)((totalBitCount >> 16) & 0xff);
padding[padLength - 7] = (byte)((totalBitCount >> 8) & 0xff);
padding[padLength - 8] = (byte)((totalBitCount >> 0) & 0xff);
// Pad the block
HashCore(padding, 0, padding.Length);
// Get the hash
var hash = new byte[16];
int hashOffset = 0;
// Assemble the hash array
for (int i = 0; i < _state.Length; i++)
{
byte[] segment = BitConverter.GetBytes(_state[i]);
Array.Copy(segment, 0, hash, hashOffset, 4);
hashOffset += 4;
}
return hash;
}
/// <summary>
/// Perform one round of updates on the cached values
/// </summary>
/// <remarks>
/// The official specification for RIPEMD-128 includes tables
/// and instructions that represent a loop. Most standard implementations
/// use the unrolled version of that loop to make it more efficient.
///
/// The below code started with the looped version but has been converted
/// to the more standard implementation instead.
/// </remarks>
private void Round()
{
// Setup values
uint x0 = _state[0], xp0 = _state[0];
uint x1 = _state[1], xp1 = _state[1];
uint x2 = _state[2], xp2 = _state[2];
uint x3 = _state[3], xp3 = _state[3];
#region Rounds 0-15
// Round 0
x0 = RotateLeft32(x0 + G00_15(x1, x2, x3) + _block[0] + RMD128Round00To15, 11);
xp0 = RotateLeft32(xp0 + G48_63(xp1, xp2, xp3) + _block[5] + RMD128RoundPrime00To15, 8);
// Round 1
x3 = RotateLeft32(x3 + G00_15(x0, x1, x2) + _block[1] + RMD128Round00To15, 14);
xp3 = RotateLeft32(xp3 + G48_63(xp0, xp1, xp2) + _block[14] + RMD128RoundPrime00To15, 9);
// Round 2
x2 = RotateLeft32(x2 + G00_15(x3, x0, x1) + _block[2] + RMD128Round00To15, 15);
xp2 = RotateLeft32(xp2 + G48_63(xp3, xp0, xp1) + _block[7] + RMD128RoundPrime00To15, 9);
// Round 3
x1 = RotateLeft32(x1 + G00_15(x2, x3, x0) + _block[3] + RMD128Round00To15, 12);
xp1 = RotateLeft32(xp1 + G48_63(xp2, xp3, xp0) + _block[0] + RMD128RoundPrime00To15, 11);
// Round 4
x0 = RotateLeft32(x0 + G00_15(x1, x2, x3) + _block[4] + RMD128Round00To15, 5);
xp0 = RotateLeft32(xp0 + G48_63(xp1, xp2, xp3) + _block[9] + RMD128RoundPrime00To15, 13);
// Round 5
x3 = RotateLeft32(x3 + G00_15(x0, x1, x2) + _block[5] + RMD128Round00To15, 8);
xp3 = RotateLeft32(xp3 + G48_63(xp0, xp1, xp2) + _block[2] + RMD128RoundPrime00To15, 15);
// Round 6
x2 = RotateLeft32(x2 + G00_15(x3, x0, x1) + _block[6] + RMD128Round00To15, 7);
xp2 = RotateLeft32(xp2 + G48_63(xp3, xp0, xp1) + _block[11] + RMD128RoundPrime00To15, 15);
// Round 7
x1 = RotateLeft32(x1 + G00_15(x2, x3, x0) + _block[7] + RMD128Round00To15, 9);
xp1 = RotateLeft32(xp1 + G48_63(xp2, xp3, xp0) + _block[4] + RMD128RoundPrime00To15, 5);
// Round 8
x0 = RotateLeft32(x0 + G00_15(x1, x2, x3) + _block[8] + RMD128Round00To15, 11);
xp0 = RotateLeft32(xp0 + G48_63(xp1, xp2, xp3) + _block[13] + RMD128RoundPrime00To15, 7);
// Round 9
x3 = RotateLeft32(x3 + G00_15(x0, x1, x2) + _block[9] + RMD128Round00To15, 13);
xp3 = RotateLeft32(xp3 + G48_63(xp0, xp1, xp2) + _block[6] + RMD128RoundPrime00To15, 7);
// Round 10
x2 = RotateLeft32(x2 + G00_15(x3, x0, x1) + _block[10] + RMD128Round00To15, 14);
xp2 = RotateLeft32(xp2 + G48_63(xp3, xp0, xp1) + _block[15] + RMD128RoundPrime00To15, 8);
// Round 11
x1 = RotateLeft32(x1 + G00_15(x2, x3, x0) + _block[11] + RMD128Round00To15, 15);
xp1 = RotateLeft32(xp1 + G48_63(xp2, xp3, xp0) + _block[8] + RMD128RoundPrime00To15, 11);
// Round 12
x0 = RotateLeft32(x0 + G00_15(x1, x2, x3) + _block[12] + RMD128Round00To15, 6);
xp0 = RotateLeft32(xp0 + G48_63(xp1, xp2, xp3) + _block[1] + RMD128RoundPrime00To15, 14);
// Round 13
x3 = RotateLeft32(x3 + G00_15(x0, x1, x2) + _block[13] + RMD128Round00To15, 7);
xp3 = RotateLeft32(xp3 + G48_63(xp0, xp1, xp2) + _block[10] + RMD128RoundPrime00To15, 14);
// Round 14
x2 = RotateLeft32(x2 + G00_15(x3, x0, x1) + _block[14] + RMD128Round00To15, 9);
xp2 = RotateLeft32(xp2 + G48_63(xp3, xp0, xp1) + _block[3] + RMD128RoundPrime00To15, 12);
// Round 15
x1 = RotateLeft32(x1 + G00_15(x2, x3, x0) + _block[15] + RMD128Round00To15, 8);
xp1 = RotateLeft32(xp1 + G48_63(xp2, xp3, xp0) + _block[12] + RMD128RoundPrime00To15, 6);
#endregion
#region Rounds 16-31
// Round 16
x0 = RotateLeft32(x0 + G16_31(x1, x2, x3) + _block[7] + RMD128Round16To31, 7);
xp0 = RotateLeft32(xp0 + G32_47(xp1, xp2, xp3) + _block[6] + RMD128RoundPrime16To31, 9);
// Round 17
x3 = RotateLeft32(x3 + G16_31(x0, x1, x2) + _block[4] + RMD128Round16To31, 6);
xp3 = RotateLeft32(xp3 + G32_47(xp0, xp1, xp2) + _block[11] + RMD128RoundPrime16To31, 13);
// Round 18
x2 = RotateLeft32(x2 + G16_31(x3, x0, x1) + _block[13] + RMD128Round16To31, 8);
xp2 = RotateLeft32(xp2 + G32_47(xp3, xp0, xp1) + _block[3] + RMD128RoundPrime16To31, 15);
// Round 19
x1 = RotateLeft32(x1 + G16_31(x2, x3, x0) + _block[1] + RMD128Round16To31, 13);
xp1 = RotateLeft32(xp1 + G32_47(xp2, xp3, xp0) + _block[7] + RMD128RoundPrime16To31, 7);
// Round 20
x0 = RotateLeft32(x0 + G16_31(x1, x2, x3) + _block[10] + RMD128Round16To31, 11);
xp0 = RotateLeft32(xp0 + G32_47(xp1, xp2, xp3) + _block[0] + RMD128RoundPrime16To31, 12);
// Round 21
x3 = RotateLeft32(x3 + G16_31(x0, x1, x2) + _block[6] + RMD128Round16To31, 9);
xp3 = RotateLeft32(xp3 + G32_47(xp0, xp1, xp2) + _block[13] + RMD128RoundPrime16To31, 8);
// Round 22
x2 = RotateLeft32(x2 + G16_31(x3, x0, x1) + _block[15] + RMD128Round16To31, 7);
xp2 = RotateLeft32(xp2 + G32_47(xp3, xp0, xp1) + _block[5] + RMD128RoundPrime16To31, 9);
// Round 23
x1 = RotateLeft32(x1 + G16_31(x2, x3, x0) + _block[3] + RMD128Round16To31, 15);
xp1 = RotateLeft32(xp1 + G32_47(xp2, xp3, xp0) + _block[10] + RMD128RoundPrime16To31, 11);
// Round 24
x0 = RotateLeft32(x0 + G16_31(x1, x2, x3) + _block[12] + RMD128Round16To31, 7);
xp0 = RotateLeft32(xp0 + G32_47(xp1, xp2, xp3) + _block[14] + RMD128RoundPrime16To31, 7);
// Round 25
x3 = RotateLeft32(x3 + G16_31(x0, x1, x2) + _block[0] + RMD128Round16To31, 12);
xp3 = RotateLeft32(xp3 + G32_47(xp0, xp1, xp2) + _block[15] + RMD128RoundPrime16To31, 7);
// Round 26
x2 = RotateLeft32(x2 + G16_31(x3, x0, x1) + _block[9] + RMD128Round16To31, 15);
xp2 = RotateLeft32(xp2 + G32_47(xp3, xp0, xp1) + _block[8] + RMD128RoundPrime16To31, 12);
// Round 27
x1 = RotateLeft32(x1 + G16_31(x2, x3, x0) + _block[5] + RMD128Round16To31, 9);
xp1 = RotateLeft32(xp1 + G32_47(xp2, xp3, xp0) + _block[12] + RMD128RoundPrime16To31, 7);
// Round 28
x0 = RotateLeft32(x0 + G16_31(x1, x2, x3) + _block[2] + RMD128Round16To31, 11);
xp0 = RotateLeft32(xp0 + G32_47(xp1, xp2, xp3) + _block[4] + RMD128RoundPrime16To31, 6);
// Round 29
x3 = RotateLeft32(x3 + G16_31(x0, x1, x2) + _block[14] + RMD128Round16To31, 7);
xp3 = RotateLeft32(xp3 + G32_47(xp0, xp1, xp2) + _block[9] + RMD128RoundPrime16To31, 15);
// Round 30
x2 = RotateLeft32(x2 + G16_31(x3, x0, x1) + _block[11] + RMD128Round16To31, 13);
xp2 = RotateLeft32(xp2 + G32_47(xp3, xp0, xp1) + _block[1] + RMD128RoundPrime16To31, 13);
// Round 31
x1 = RotateLeft32(x1 + G16_31(x2, x3, x0) + _block[8] + RMD128Round16To31, 12);
xp1 = RotateLeft32(xp1 + G32_47(xp2, xp3, xp0) + _block[2] + RMD128RoundPrime16To31, 11);
#endregion
#region Rounds 32-47
// Round 32
x0 = RotateLeft32(x0 + G32_47(x1, x2, x3) + _block[3] + RMD128Round32To47, 11);
xp0 = RotateLeft32(xp0 + G16_31(xp1, xp2, xp3) + _block[15] + RMD128RoundPrime32To47, 9);
// Round 33
x3 = RotateLeft32(x3 + G32_47(x0, x1, x2) + _block[10] + RMD128Round32To47, 13);
xp3 = RotateLeft32(xp3 + G16_31(xp0, xp1, xp2) + _block[5] + RMD128RoundPrime32To47, 7);
// Round 34
x2 = RotateLeft32(x2 + G32_47(x3, x0, x1) + _block[14] + RMD128Round32To47, 6);
xp2 = RotateLeft32(xp2 + G16_31(xp3, xp0, xp1) + _block[1] + RMD128RoundPrime32To47, 15);
// Round 35
x1 = RotateLeft32(x1 + G32_47(x2, x3, x0) + _block[4] + RMD128Round32To47, 7);
xp1 = RotateLeft32(xp1 + G16_31(xp2, xp3, xp0) + _block[3] + RMD128RoundPrime32To47, 11);
// Round 36
x0 = RotateLeft32(x0 + G32_47(x1, x2, x3) + _block[9] + RMD128Round32To47, 14);
xp0 = RotateLeft32(xp0 + G16_31(xp1, xp2, xp3) + _block[7] + RMD128RoundPrime32To47, 8);
// Round 37
x3 = RotateLeft32(x3 + G32_47(x0, x1, x2) + _block[15] + RMD128Round32To47, 9);
xp3 = RotateLeft32(xp3 + G16_31(xp0, xp1, xp2) + _block[14] + RMD128RoundPrime32To47, 6);
// Round 38
x2 = RotateLeft32(x2 + G32_47(x3, x0, x1) + _block[8] + RMD128Round32To47, 13);
xp2 = RotateLeft32(xp2 + G16_31(xp3, xp0, xp1) + _block[6] + RMD128RoundPrime32To47, 6);
// Round 39
x1 = RotateLeft32(x1 + G32_47(x2, x3, x0) + _block[1] + RMD128Round32To47, 15);
xp1 = RotateLeft32(xp1 + G16_31(xp2, xp3, xp0) + _block[9] + RMD128RoundPrime32To47, 14);
// Round 40
x0 = RotateLeft32(x0 + G32_47(x1, x2, x3) + _block[2] + RMD128Round32To47, 14);
xp0 = RotateLeft32(xp0 + G16_31(xp1, xp2, xp3) + _block[11] + RMD128RoundPrime32To47, 12);
// Round 41
x3 = RotateLeft32(x3 + G32_47(x0, x1, x2) + _block[7] + RMD128Round32To47, 8);
xp3 = RotateLeft32(xp3 + G16_31(xp0, xp1, xp2) + _block[8] + RMD128RoundPrime32To47, 13);
// Round 42
x2 = RotateLeft32(x2 + G32_47(x3, x0, x1) + _block[0] + RMD128Round32To47, 13);
xp2 = RotateLeft32(xp2 + G16_31(xp3, xp0, xp1) + _block[12] + RMD128RoundPrime32To47, 5);
// Round 43
x1 = RotateLeft32(x1 + G32_47(x2, x3, x0) + _block[6] + RMD128Round32To47, 6);
xp1 = RotateLeft32(xp1 + G16_31(xp2, xp3, xp0) + _block[2] + RMD128RoundPrime32To47, 14);
// Round 44
x0 = RotateLeft32(x0 + G32_47(x1, x2, x3) + _block[13] + RMD128Round32To47, 5);
xp0 = RotateLeft32(xp0 + G16_31(xp1, xp2, xp3) + _block[10] + RMD128RoundPrime32To47, 13);
// Round 45
x3 = RotateLeft32(x3 + G32_47(x0, x1, x2) + _block[11] + RMD128Round32To47, 12);
xp3 = RotateLeft32(xp3 + G16_31(xp0, xp1, xp2) + _block[0] + RMD128RoundPrime32To47, 13);
// Round 46
x2 = RotateLeft32(x2 + G32_47(x3, x0, x1) + _block[5] + RMD128Round32To47, 7);
xp2 = RotateLeft32(xp2 + G16_31(xp3, xp0, xp1) + _block[4] + RMD128RoundPrime32To47, 7);
// Round 47
x1 = RotateLeft32(x1 + G32_47(x2, x3, x0) + _block[12] + RMD128Round32To47, 5);
xp1 = RotateLeft32(xp1 + G16_31(xp2, xp3, xp0) + _block[13] + RMD128RoundPrime32To47, 5);
#endregion
#region Rounds 48-63
// Round 48
x0 = RotateLeft32(x0 + G48_63(x1, x2, x3) + _block[1] + RMD128Round48To63, 11);
xp0 = RotateLeft32(xp0 + G00_15(xp1, xp2, xp3) + _block[8] + RMD128RoundPrime48To63, 15);
// Round 49
x3 = RotateLeft32(x3 + G48_63(x0, x1, x2) + _block[9] + RMD128Round48To63, 12);
xp3 = RotateLeft32(xp3 + G00_15(xp0, xp1, xp2) + _block[6] + RMD128RoundPrime48To63, 5);
// Round 50
x2 = RotateLeft32(x2 + G48_63(x3, x0, x1) + _block[11] + RMD128Round48To63, 14);
xp2 = RotateLeft32(xp2 + G00_15(xp3, xp0, xp1) + _block[4] + RMD128RoundPrime48To63, 8);
// Round 51
x1 = RotateLeft32(x1 + G48_63(x2, x3, x0) + _block[10] + RMD128Round48To63, 15);
xp1 = RotateLeft32(xp1 + G00_15(xp2, xp3, xp0) + _block[1] + RMD128RoundPrime48To63, 11);
// Round 52
x0 = RotateLeft32(x0 + G48_63(x1, x2, x3) + _block[0] + RMD128Round48To63, 14);
xp0 = RotateLeft32(xp0 + G00_15(xp1, xp2, xp3) + _block[3] + RMD128RoundPrime48To63, 14);
// Round 53
x3 = RotateLeft32(x3 + G48_63(x0, x1, x2) + _block[8] + RMD128Round48To63, 15);
xp3 = RotateLeft32(xp3 + G00_15(xp0, xp1, xp2) + _block[11] + RMD128RoundPrime48To63, 14);
// Round 54
x2 = RotateLeft32(x2 + G48_63(x3, x0, x1) + _block[12] + RMD128Round48To63, 9);
xp2 = RotateLeft32(xp2 + G00_15(xp3, xp0, xp1) + _block[15] + RMD128RoundPrime48To63, 6);
// Round 55
x1 = RotateLeft32(x1 + G48_63(x2, x3, x0) + _block[4] + RMD128Round48To63, 8);
xp1 = RotateLeft32(xp1 + G00_15(xp2, xp3, xp0) + _block[0] + RMD128RoundPrime48To63, 14);
// Round 56
x0 = RotateLeft32(x0 + G48_63(x1, x2, x3) + _block[13] + RMD128Round48To63, 9);
xp0 = RotateLeft32(xp0 + G00_15(xp1, xp2, xp3) + _block[5] + RMD128RoundPrime48To63, 6);
// Round 57
x3 = RotateLeft32(x3 + G48_63(x0, x1, x2) + _block[3] + RMD128Round48To63, 14);
xp3 = RotateLeft32(xp3 + G00_15(xp0, xp1, xp2) + _block[12] + RMD128RoundPrime48To63, 9);
// Round 58
x2 = RotateLeft32(x2 + G48_63(x3, x0, x1) + _block[7] + RMD128Round48To63, 5);
xp2 = RotateLeft32(xp2 + G00_15(xp3, xp0, xp1) + _block[2] + RMD128RoundPrime48To63, 12);
// Round 59
x1 = RotateLeft32(x1 + G48_63(x2, x3, x0) + _block[15] + RMD128Round48To63, 6);
xp1 = RotateLeft32(xp1 + G00_15(xp2, xp3, xp0) + _block[13] + RMD128RoundPrime48To63, 9);
// Round 60
x0 = RotateLeft32(x0 + G48_63(x1, x2, x3) + _block[14] + RMD128Round48To63, 8);
xp0 = RotateLeft32(xp0 + G00_15(xp1, xp2, xp3) + _block[9] + RMD128RoundPrime48To63, 12);
// Round 61
x3 = RotateLeft32(x3 + G48_63(x0, x1, x2) + _block[5] + RMD128Round48To63, 6);
xp3 = RotateLeft32(xp3 + G00_15(xp0, xp1, xp2) + _block[7] + RMD128RoundPrime48To63, 5);
// Round 62
x2 = RotateLeft32(x2 + G48_63(x3, x0, x1) + _block[6] + RMD128Round48To63, 5);
xp2 = RotateLeft32(xp2 + G00_15(xp3, xp0, xp1) + _block[10] + RMD128RoundPrime48To63, 15);
// Round 63
x1 = RotateLeft32(x1 + G48_63(x2, x3, x0) + _block[2] + RMD128Round48To63, 12);
xp1 = RotateLeft32(xp1 + G00_15(xp2, xp3, xp0) + _block[14] + RMD128RoundPrime48To63, 8);
#endregion
// Avalanche values
xp3 += x2 + _state[1];
_state[1] = _state[2] + x3 + xp0;
_state[2] = _state[3] + x0 + xp1;
_state[3] = _state[0] + x1 + xp2;
_state[0] = xp3;
}
/// <summary>
/// Round operation [0, 15]
/// </summary>
private static uint G00_15(uint x, uint y, uint z) => x ^ y ^ z;
/// <summary>
/// Round operation [16, 31]
/// </summary>
private static uint G16_31(uint x, uint y, uint z) => (x & y) | (~x & z);
/// <summary>
/// Round operation [32, 47]
/// </summary>
private static uint G32_47(uint x, uint y, uint z) => (x | ~y) ^ z;
/// <summary>
/// Round operation [48, 63]
/// </summary>
private static uint G48_63(uint x, uint y, uint z) => (x & z) | (y & ~z);
}
}

View File

@@ -0,0 +1,683 @@
using System;
using static SabreTools.Hashing.CryptographicHash.Constants;
using static SabreTools.Hashing.HashOperations;
namespace SabreTools.Hashing.CryptographicHash
{
/// <see href="https://cdn.standards.iteh.ai/samples/39876/10f9f9f4bb614eaaaeba7e157e183ca3/ISO-IEC-10118-3-2004.pdf"/>
/// <see href="https://homes.esat.kuleuven.be/~bosselae/ripemd160/pdf/AB-9601/AB-9601.pdf"/>
public class RipeMD160 : MessageDigestBase<uint>
{
/// <inheritdoc/>
public override int HashSize => 160;
/// <summary>
/// Set of 5 32-bit numbers representing the hash state
/// </summary>
private readonly uint[] _state = new uint[5];
public RipeMD160() : base()
{
}
/// <inheritdoc/>
protected override void ResetImpl()
{
_state[0] = RMD160Y0;
_state[1] = RMD160Y1;
_state[2] = RMD160Y2;
_state[3] = RMD160Y3;
_state[4] = RMD160Y4;
}
/// <inheritdoc/>
protected override void HashCore(byte[] data, int offset, int length)
{
// Figure out how much buffer is needed
int bufferLen = (int)(_totalBytes & 0x3f);
// Increment the processed byte count
_totalBytes += length;
// If there is buffer to fill and it will meet the limit
if (bufferLen > 0 && bufferLen + length >= 64)
{
// Fill the buffer from the input
Array.Copy(data, offset, _buffer, bufferLen, 64 - bufferLen);
// Set the new values
offset += 64 - bufferLen;
length -= 64 - bufferLen;
// Split the buffer for the round
for (int i = 0; i < 16; i++)
{
_block[i] = ReadLE32(_buffer, i * 4);
}
// Run the round
Round();
bufferLen = 0;
}
/// Process any standalone blocks
while (length >= 64)
{
// Fill the buffer from the input
Array.Copy(data, offset, _buffer, 0, 64);
// Set the new values
offset += 64;
length -= 64;
// Split the buffer for the round
for (int i = 0; i < 16; i++)
{
_block[i] = ReadLE32(_buffer, i * 4);
}
// Run the round
Round();
}
// Save the remainder in the buffer
if (length > 0)
Array.Copy(data, offset, _buffer, bufferLen, length);
}
/// <inheritdoc/>
protected override byte[] HashFinal()
{
// Determine the pad length
int padLength = 64 - (int)(_totalBytes & 0x3f);
if (padLength <= 8)
padLength += 64;
// Get the total byte count in bits
long totalBitCount = _totalBytes * 8;
// Prebuild the padding
var padding = new byte[padLength];
padding[0] = 0x80;
padding[padLength - 1] = (byte)((totalBitCount >> 56) & 0xff);
padding[padLength - 2] = (byte)((totalBitCount >> 48) & 0xff);
padding[padLength - 3] = (byte)((totalBitCount >> 40) & 0xff);
padding[padLength - 4] = (byte)((totalBitCount >> 32) & 0xff);
padding[padLength - 5] = (byte)((totalBitCount >> 24) & 0xff);
padding[padLength - 6] = (byte)((totalBitCount >> 16) & 0xff);
padding[padLength - 7] = (byte)((totalBitCount >> 8) & 0xff);
padding[padLength - 8] = (byte)((totalBitCount >> 0) & 0xff);
// Pad the block
HashCore(padding, 0, padding.Length);
// Get the hash
var hash = new byte[20];
int hashOffset = 0;
// Assemble the hash array
for (int i = 0; i < _state.Length; i++)
{
byte[] segment = BitConverter.GetBytes(_state[i]);
Array.Copy(segment, 0, hash, hashOffset, 4);
hashOffset += 4;
}
return hash;
}
/// <summary>
/// Perform one round of updates on the cached values
/// </summary>
/// <remarks>
/// The official specification for RIPEMD-160 includes tables
/// and instructions that represent a loop. Most standard implementations
/// use the unrolled version of that loop to make it more efficient.
///
/// The below code started with the looped version but has been converted
/// to the more standard implementation instead.
/// </remarks>
private void Round()
{
// Setup values
uint x0 = _state[0], xp0 = _state[0];
uint x1 = _state[1], xp1 = _state[1];
uint x2 = _state[2], xp2 = _state[2];
uint x3 = _state[3], xp3 = _state[3];
uint x4 = _state[4], xp4 = _state[4];
#region Rounds 0-15
// Round 0
x0 = RotateLeft32(x0 + G00_15(x1, x2, x3) + _block[0] + RMD160Round00To15, 11) + x4;
x2 = RotateLeft32(x2, 10);
xp0 = RotateLeft32(xp0 + G64_79(xp1, xp2, xp3) + _block[5] + RMD160RoundPrime00To15, 8) + xp4;
xp2 = RotateLeft32(xp2, 10);
// Round 1
x4 = RotateLeft32(x4 + G00_15(x0, x1, x2) + _block[1] + RMD160Round00To15, 14) + x3;
x1 = RotateLeft32(x1, 10);
xp4 = RotateLeft32(xp4 + G64_79(xp0, xp1, xp2) + _block[14] + RMD160RoundPrime00To15, 9) + xp3;
xp1 = RotateLeft32(xp1, 10);
// Round 2
x3 = RotateLeft32(x3 + G00_15(x4, x0, x1) + _block[2] + RMD160Round00To15, 15) + x2;
x0 = RotateLeft32(x0, 10);
xp3 = RotateLeft32(xp3 + G64_79(xp4, xp0, xp1) + _block[7] + RMD160RoundPrime00To15, 9) + xp2;
xp0 = RotateLeft32(xp0, 10);
// Round 3
x2 = RotateLeft32(x2 + G00_15(x3, x4, x0) + _block[3] + RMD160Round00To15, 12) + x1;
x4 = RotateLeft32(x4, 10);
xp2 = RotateLeft32(xp2 + G64_79(xp3, xp4, xp0) + _block[0] + RMD160RoundPrime00To15, 11) + xp1;
xp4 = RotateLeft32(xp4, 10);
// Round 4
x1 = RotateLeft32(x1 + G00_15(x2, x3, x4) + _block[4] + RMD160Round00To15, 5) + x0;
x3 = RotateLeft32(x3, 10);
xp1 = RotateLeft32(xp1 + G64_79(xp2, xp3, xp4) + _block[9] + RMD160RoundPrime00To15, 13) + xp0;
xp3 = RotateLeft32(xp3, 10);
// Round 5
x0 = RotateLeft32(x0 + G00_15(x1, x2, x3) + _block[5] + RMD160Round00To15, 8) + x4;
x2 = RotateLeft32(x2, 10);
xp0 = RotateLeft32(xp0 + G64_79(xp1, xp2, xp3) + _block[2] + RMD160RoundPrime00To15, 15) + xp4;
xp2 = RotateLeft32(xp2, 10);
// Round 6
x4 = RotateLeft32(x4 + G00_15(x0, x1, x2) + _block[6] + RMD160Round00To15, 7) + x3;
x1 = RotateLeft32(x1, 10);
xp4 = RotateLeft32(xp4 + G64_79(xp0, xp1, xp2) + _block[11] + RMD160RoundPrime00To15, 15) + xp3;
xp1 = RotateLeft32(xp1, 10);
// Round 7
x3 = RotateLeft32(x3 + G00_15(x4, x0, x1) + _block[7] + RMD160Round00To15, 9) + x2;
x0 = RotateLeft32(x0, 10);
xp3 = RotateLeft32(xp3 + G64_79(xp4, xp0, xp1) + _block[4] + RMD160RoundPrime00To15, 5) + xp2;
xp0 = RotateLeft32(xp0, 10);
// Round 8
x2 = RotateLeft32(x2 + G00_15(x3, x4, x0) + _block[8] + RMD160Round00To15, 11) + x1;
x4 = RotateLeft32(x4, 10);
xp2 = RotateLeft32(xp2 + G64_79(xp3, xp4, xp0) + _block[13] + RMD160RoundPrime00To15, 7) + xp1;
xp4 = RotateLeft32(xp4, 10);
// Round 9
x1 = RotateLeft32(x1 + G00_15(x2, x3, x4) + _block[9] + RMD160Round00To15, 13) + x0;
x3 = RotateLeft32(x3, 10);
xp1 = RotateLeft32(xp1 + G64_79(xp2, xp3, xp4) + _block[6] + RMD160RoundPrime00To15, 7) + xp0;
xp3 = RotateLeft32(xp3, 10);
// Round 10
x0 = RotateLeft32(x0 + G00_15(x1, x2, x3) + _block[10] + RMD160Round00To15, 14) + x4;
x2 = RotateLeft32(x2, 10);
xp0 = RotateLeft32(xp0 + G64_79(xp1, xp2, xp3) + _block[15] + RMD160RoundPrime00To15, 8) + xp4;
xp2 = RotateLeft32(xp2, 10);
// Round 11
x4 = RotateLeft32(x4 + G00_15(x0, x1, x2) + _block[11] + RMD160Round00To15, 15) + x3;
x1 = RotateLeft32(x1, 10);
xp4 = RotateLeft32(xp4 + G64_79(xp0, xp1, xp2) + _block[8] + RMD160RoundPrime00To15, 11) + xp3;
xp1 = RotateLeft32(xp1, 10);
// Round 12
x3 = RotateLeft32(x3 + G00_15(x4, x0, x1) + _block[12] + RMD160Round00To15, 6) + x2;
x0 = RotateLeft32(x0, 10);
xp3 = RotateLeft32(xp3 + G64_79(xp4, xp0, xp1) + _block[1] + RMD160RoundPrime00To15, 14) + xp2;
xp0 = RotateLeft32(xp0, 10);
// Round 13
x2 = RotateLeft32(x2 + G00_15(x3, x4, x0) + _block[13] + RMD160Round00To15, 7) + x1;
x4 = RotateLeft32(x4, 10);
xp2 = RotateLeft32(xp2 + G64_79(xp3, xp4, xp0) + _block[10] + RMD160RoundPrime00To15, 14) + xp1;
xp4 = RotateLeft32(xp4, 10);
// Round 14
x1 = RotateLeft32(x1 + G00_15(x2, x3, x4) + _block[14] + RMD160Round00To15, 9) + x0;
x3 = RotateLeft32(x3, 10);
xp1 = RotateLeft32(xp1 + G64_79(xp2, xp3, xp4) + _block[3] + RMD160RoundPrime00To15, 12) + xp0;
xp3 = RotateLeft32(xp3, 10);
// Round 15
x0 = RotateLeft32(x0 + G00_15(x1, x2, x3) + _block[15] + RMD160Round00To15, 8) + x4;
x2 = RotateLeft32(x2, 10);
xp0 = RotateLeft32(xp0 + G64_79(xp1, xp2, xp3) + _block[12] + RMD160RoundPrime00To15, 6) + xp4;
xp2 = RotateLeft32(xp2, 10);
#endregion
#region Rounds 16-31
// Round 16
x4 = RotateLeft32(x4 + G16_31(x0, x1, x2) + _block[7] + RMD160Round16To31, 7) + x3;
x1 = RotateLeft32(x1, 10);
xp4 = RotateLeft32(xp4 + G48_63(xp0, xp1, xp2) + _block[6] + RMD160RoundPrime16To31, 9) + xp3;
xp1 = RotateLeft32(xp1, 10);
// Round 17
x3 = RotateLeft32(x3 + G16_31(x4, x0, x1) + _block[4] + RMD160Round16To31, 6) + x2;
x0 = RotateLeft32(x0, 10);
xp3 = RotateLeft32(xp3 + G48_63(xp4, xp0, xp1) + _block[11] + RMD160RoundPrime16To31, 13) + xp2;
xp0 = RotateLeft32(xp0, 10);
// Round 18
x2 = RotateLeft32(x2 + G16_31(x3, x4, x0) + _block[13] + RMD160Round16To31, 8) + x1;
x4 = RotateLeft32(x4, 10);
xp2 = RotateLeft32(xp2 + G48_63(xp3, xp4, xp0) + _block[3] + RMD160RoundPrime16To31, 15) + xp1;
xp4 = RotateLeft32(xp4, 10);
// Round 19
x1 = RotateLeft32(x1 + G16_31(x2, x3, x4) + _block[1] + RMD160Round16To31, 13) + x0;
x3 = RotateLeft32(x3, 10);
xp1 = RotateLeft32(xp1 + G48_63(xp2, xp3, xp4) + _block[7] + RMD160RoundPrime16To31, 7) + xp0;
xp3 = RotateLeft32(xp3, 10);
// Round 20
x0 = RotateLeft32(x0 + G16_31(x1, x2, x3) + _block[10] + RMD160Round16To31, 11) + x4;
x2 = RotateLeft32(x2, 10);
xp0 = RotateLeft32(xp0 + G48_63(xp1, xp2, xp3) + _block[0] + RMD160RoundPrime16To31, 12) + xp4;
xp2 = RotateLeft32(xp2, 10);
// Round 21
x4 = RotateLeft32(x4 + G16_31(x0, x1, x2) + _block[6] + RMD160Round16To31, 9) + x3;
x1 = RotateLeft32(x1, 10);
xp4 = RotateLeft32(xp4 + G48_63(xp0, xp1, xp2) + _block[13] + RMD160RoundPrime16To31, 8) + xp3;
xp1 = RotateLeft32(xp1, 10);
// Round 22
x3 = RotateLeft32(x3 + G16_31(x4, x0, x1) + _block[15] + RMD160Round16To31, 7) + x2;
x0 = RotateLeft32(x0, 10);
xp3 = RotateLeft32(xp3 + G48_63(xp4, xp0, xp1) + _block[5] + RMD160RoundPrime16To31, 9) + xp2;
xp0 = RotateLeft32(xp0, 10);
// Round 23
x2 = RotateLeft32(x2 + G16_31(x3, x4, x0) + _block[3] + RMD160Round16To31, 15) + x1;
x4 = RotateLeft32(x4, 10);
xp2 = RotateLeft32(xp2 + G48_63(xp3, xp4, xp0) + _block[10] + RMD160RoundPrime16To31, 11) + xp1;
xp4 = RotateLeft32(xp4, 10);
// Round 24
x1 = RotateLeft32(x1 + G16_31(x2, x3, x4) + _block[12] + RMD160Round16To31, 7) + x0;
x3 = RotateLeft32(x3, 10);
xp1 = RotateLeft32(xp1 + G48_63(xp2, xp3, xp4) + _block[14] + RMD160RoundPrime16To31, 7) + xp0;
xp3 = RotateLeft32(xp3, 10);
// Round 25
x0 = RotateLeft32(x0 + G16_31(x1, x2, x3) + _block[0] + RMD160Round16To31, 12) + x4;
x2 = RotateLeft32(x2, 10);
xp0 = RotateLeft32(xp0 + G48_63(xp1, xp2, xp3) + _block[15] + RMD160RoundPrime16To31, 7) + xp4;
xp2 = RotateLeft32(xp2, 10);
// Round 26
x4 = RotateLeft32(x4 + G16_31(x0, x1, x2) + _block[9] + RMD160Round16To31, 15) + x3;
x1 = RotateLeft32(x1, 10);
xp4 = RotateLeft32(xp4 + G48_63(xp0, xp1, xp2) + _block[8] + RMD160RoundPrime16To31, 12) + xp3;
xp1 = RotateLeft32(xp1, 10);
// Round 27
x3 = RotateLeft32(x3 + G16_31(x4, x0, x1) + _block[5] + RMD160Round16To31, 9) + x2;
x0 = RotateLeft32(x0, 10);
xp3 = RotateLeft32(xp3 + G48_63(xp4, xp0, xp1) + _block[12] + RMD160RoundPrime16To31, 7) + xp2;
xp0 = RotateLeft32(xp0, 10);
// Round 28
x2 = RotateLeft32(x2 + G16_31(x3, x4, x0) + _block[2] + RMD160Round16To31, 11) + x1;
x4 = RotateLeft32(x4, 10);
xp2 = RotateLeft32(xp2 + G48_63(xp3, xp4, xp0) + _block[4] + RMD160RoundPrime16To31, 6) + xp1;
xp4 = RotateLeft32(xp4, 10);
// Round 29
x1 = RotateLeft32(x1 + G16_31(x2, x3, x4) + _block[14] + RMD160Round16To31, 7) + x0;
x3 = RotateLeft32(x3, 10);
xp1 = RotateLeft32(xp1 + G48_63(xp2, xp3, xp4) + _block[9] + RMD160RoundPrime16To31, 15) + xp0;
xp3 = RotateLeft32(xp3, 10);
// Round 30
x0 = RotateLeft32(x0 + G16_31(x1, x2, x3) + _block[11] + RMD160Round16To31, 13) + x4;
x2 = RotateLeft32(x2, 10);
xp0 = RotateLeft32(xp0 + G48_63(xp1, xp2, xp3) + _block[1] + RMD160RoundPrime16To31, 13) + xp4;
xp2 = RotateLeft32(xp2, 10);
// Round 31
x4 = RotateLeft32(x4 + G16_31(x0, x1, x2) + _block[8] + RMD160Round16To31, 12) + x3;
x1 = RotateLeft32(x1, 10);
xp4 = RotateLeft32(xp4 + G48_63(xp0, xp1, xp2) + _block[2] + RMD160RoundPrime16To31, 11) + xp3;
xp1 = RotateLeft32(xp1, 10);
#endregion
#region Rounds 32-47
// Round 32
x3 = RotateLeft32(x3 + G32_47(x4, x0, x1) + _block[3] + RMD160Round32To47, 11) + x2;
x0 = RotateLeft32(x0, 10);
xp3 = RotateLeft32(xp3 + G32_47(xp4, xp0, xp1) + _block[15] + RMD160RoundPrime32To47, 9) + xp2;
xp0 = RotateLeft32(xp0, 10);
// Round 33
x2 = RotateLeft32(x2 + G32_47(x3, x4, x0) + _block[10] + RMD160Round32To47, 13) + x1;
x4 = RotateLeft32(x4, 10);
xp2 = RotateLeft32(xp2 + G32_47(xp3, xp4, xp0) + _block[5] + RMD160RoundPrime32To47, 7) + xp1;
xp4 = RotateLeft32(xp4, 10);
// Round 34
x1 = RotateLeft32(x1 + G32_47(x2, x3, x4) + _block[14] + RMD160Round32To47, 6) + x0;
x3 = RotateLeft32(x3, 10);
xp1 = RotateLeft32(xp1 + G32_47(xp2, xp3, xp4) + _block[1] + RMD160RoundPrime32To47, 15) + xp0;
xp3 = RotateLeft32(xp3, 10);
// Round 35
x0 = RotateLeft32(x0 + G32_47(x1, x2, x3) + _block[4] + RMD160Round32To47, 7) + x4;
x2 = RotateLeft32(x2, 10);
xp0 = RotateLeft32(xp0 + G32_47(xp1, xp2, xp3) + _block[3] + RMD160RoundPrime32To47, 11) + xp4;
xp2 = RotateLeft32(xp2, 10);
// Round 36
x4 = RotateLeft32(x4 + G32_47(x0, x1, x2) + _block[9] + RMD160Round32To47, 14) + x3;
x1 = RotateLeft32(x1, 10);
xp4 = RotateLeft32(xp4 + G32_47(xp0, xp1, xp2) + _block[7] + RMD160RoundPrime32To47, 8) + xp3;
xp1 = RotateLeft32(xp1, 10);
// Round 37
x3 = RotateLeft32(x3 + G32_47(x4, x0, x1) + _block[15] + RMD160Round32To47, 9) + x2;
x0 = RotateLeft32(x0, 10);
xp3 = RotateLeft32(xp3 + G32_47(xp4, xp0, xp1) + _block[14] + RMD160RoundPrime32To47, 6) + xp2;
xp0 = RotateLeft32(xp0, 10);
// Round 38
x2 = RotateLeft32(x2 + G32_47(x3, x4, x0) + _block[8] + RMD160Round32To47, 13) + x1;
x4 = RotateLeft32(x4, 10);
xp2 = RotateLeft32(xp2 + G32_47(xp3, xp4, xp0) + _block[6] + RMD160RoundPrime32To47, 6) + xp1;
xp4 = RotateLeft32(xp4, 10);
// Round 39
x1 = RotateLeft32(x1 + G32_47(x2, x3, x4) + _block[1] + RMD160Round32To47, 15) + x0;
x3 = RotateLeft32(x3, 10);
xp1 = RotateLeft32(xp1 + G32_47(xp2, xp3, xp4) + _block[9] + RMD160RoundPrime32To47, 14) + xp0;
xp3 = RotateLeft32(xp3, 10);
// Round 40
x0 = RotateLeft32(x0 + G32_47(x1, x2, x3) + _block[2] + RMD160Round32To47, 14) + x4;
x2 = RotateLeft32(x2, 10);
xp0 = RotateLeft32(xp0 + G32_47(xp1, xp2, xp3) + _block[11] + RMD160RoundPrime32To47, 12) + xp4;
xp2 = RotateLeft32(xp2, 10);
// Round 41
x4 = RotateLeft32(x4 + G32_47(x0, x1, x2) + _block[7] + RMD160Round32To47, 8) + x3;
x1 = RotateLeft32(x1, 10);
xp4 = RotateLeft32(xp4 + G32_47(xp0, xp1, xp2) + _block[8] + RMD160RoundPrime32To47, 13) + xp3;
xp1 = RotateLeft32(xp1, 10);
// Round 42
x3 = RotateLeft32(x3 + G32_47(x4, x0, x1) + _block[0] + RMD160Round32To47, 13) + x2;
x0 = RotateLeft32(x0, 10);
xp3 = RotateLeft32(xp3 + G32_47(xp4, xp0, xp1) + _block[12] + RMD160RoundPrime32To47, 5) + xp2;
xp0 = RotateLeft32(xp0, 10);
// Round 43
x2 = RotateLeft32(x2 + G32_47(x3, x4, x0) + _block[6] + RMD160Round32To47, 6) + x1;
x4 = RotateLeft32(x4, 10);
xp2 = RotateLeft32(xp2 + G32_47(xp3, xp4, xp0) + _block[2] + RMD160RoundPrime32To47, 14) + xp1;
xp4 = RotateLeft32(xp4, 10);
// Round 44
x1 = RotateLeft32(x1 + G32_47(x2, x3, x4) + _block[13] + RMD160Round32To47, 5) + x0;
x3 = RotateLeft32(x3, 10);
xp1 = RotateLeft32(xp1 + G32_47(xp2, xp3, xp4) + _block[10] + RMD160RoundPrime32To47, 13) + xp0;
xp3 = RotateLeft32(xp3, 10);
// Round 45
x0 = RotateLeft32(x0 + G32_47(x1, x2, x3) + _block[11] + RMD160Round32To47, 12) + x4;
x2 = RotateLeft32(x2, 10);
xp0 = RotateLeft32(xp0 + G32_47(xp1, xp2, xp3) + _block[0] + RMD160RoundPrime32To47, 13) + xp4;
xp2 = RotateLeft32(xp2, 10);
// Round 46
x4 = RotateLeft32(x4 + G32_47(x0, x1, x2) + _block[5] + RMD160Round32To47, 7) + x3;
x1 = RotateLeft32(x1, 10);
xp4 = RotateLeft32(xp4 + G32_47(xp0, xp1, xp2) + _block[4] + RMD160RoundPrime32To47, 7) + xp3;
xp1 = RotateLeft32(xp1, 10);
// Round 47
x3 = RotateLeft32(x3 + G32_47(x4, x0, x1) + _block[12] + RMD160Round32To47, 5) + x2;
x0 = RotateLeft32(x0, 10);
xp3 = RotateLeft32(xp3 + G32_47(xp4, xp0, xp1) + _block[13] + RMD160RoundPrime32To47, 5) + xp2;
xp0 = RotateLeft32(xp0, 10);
#endregion
#region Rounds 48-63
// Round 48
x2 = RotateLeft32(x2 + G48_63(x3, x4, x0) + _block[1] + RMD160Round48To63, 11) + x1;
x4 = RotateLeft32(x4, 10);
xp2 = RotateLeft32(xp2 + G16_31(xp3, xp4, xp0) + _block[8] + RMD160RoundPrime48To63, 15) + xp1;
xp4 = RotateLeft32(xp4, 10);
// Round 49
x1 = RotateLeft32(x1 + G48_63(x2, x3, x4) + _block[9] + RMD160Round48To63, 12) + x0;
x3 = RotateLeft32(x3, 10);
xp1 = RotateLeft32(xp1 + G16_31(xp2, xp3, xp4) + _block[6] + RMD160RoundPrime48To63, 5) + xp0;
xp3 = RotateLeft32(xp3, 10);
// Round 50
x0 = RotateLeft32(x0 + G48_63(x1, x2, x3) + _block[11] + RMD160Round48To63, 14) + x4;
x2 = RotateLeft32(x2, 10);
xp0 = RotateLeft32(xp0 + G16_31(xp1, xp2, xp3) + _block[4] + RMD160RoundPrime48To63, 8) + xp4;
xp2 = RotateLeft32(xp2, 10);
// Round 51
x4 = RotateLeft32(x4 + G48_63(x0, x1, x2) + _block[10] + RMD160Round48To63, 15) + x3;
x1 = RotateLeft32(x1, 10);
xp4 = RotateLeft32(xp4 + G16_31(xp0, xp1, xp2) + _block[1] + RMD160RoundPrime48To63, 11) + xp3;
xp1 = RotateLeft32(xp1, 10);
// Round 52
x3 = RotateLeft32(x3 + G48_63(x4, x0, x1) + _block[0] + RMD160Round48To63, 14) + x2;
x0 = RotateLeft32(x0, 10);
xp3 = RotateLeft32(xp3 + G16_31(xp4, xp0, xp1) + _block[3] + RMD160RoundPrime48To63, 14) + xp2;
xp0 = RotateLeft32(xp0, 10);
// Round 53
x2 = RotateLeft32(x2 + G48_63(x3, x4, x0) + _block[8] + RMD160Round48To63, 15) + x1;
x4 = RotateLeft32(x4, 10);
xp2 = RotateLeft32(xp2 + G16_31(xp3, xp4, xp0) + _block[11] + RMD160RoundPrime48To63, 14) + xp1;
xp4 = RotateLeft32(xp4, 10);
// Round 54
x1 = RotateLeft32(x1 + G48_63(x2, x3, x4) + _block[12] + RMD160Round48To63, 9) + x0;
x3 = RotateLeft32(x3, 10);
xp1 = RotateLeft32(xp1 + G16_31(xp2, xp3, xp4) + _block[15] + RMD160RoundPrime48To63, 6) + xp0;
xp3 = RotateLeft32(xp3, 10);
// Round 55
x0 = RotateLeft32(x0 + G48_63(x1, x2, x3) + _block[4] + RMD160Round48To63, 8) + x4;
x2 = RotateLeft32(x2, 10);
xp0 = RotateLeft32(xp0 + G16_31(xp1, xp2, xp3) + _block[0] + RMD160RoundPrime48To63, 14) + xp4;
xp2 = RotateLeft32(xp2, 10);
// Round 56
x4 = RotateLeft32(x4 + G48_63(x0, x1, x2) + _block[13] + RMD160Round48To63, 9) + x3;
x1 = RotateLeft32(x1, 10);
xp4 = RotateLeft32(xp4 + G16_31(xp0, xp1, xp2) + _block[5] + RMD160RoundPrime48To63, 6) + xp3;
xp1 = RotateLeft32(xp1, 10);
// Round 57
x3 = RotateLeft32(x3 + G48_63(x4, x0, x1) + _block[3] + RMD160Round48To63, 14) + x2;
x0 = RotateLeft32(x0, 10);
xp3 = RotateLeft32(xp3 + G16_31(xp4, xp0, xp1) + _block[12] + RMD160RoundPrime48To63, 9) + xp2;
xp0 = RotateLeft32(xp0, 10);
// Round 58
x2 = RotateLeft32(x2 + G48_63(x3, x4, x0) + _block[7] + RMD160Round48To63, 5) + x1;
x4 = RotateLeft32(x4, 10);
xp2 = RotateLeft32(xp2 + G16_31(xp3, xp4, xp0) + _block[2] + RMD160RoundPrime48To63, 12) + xp1;
xp4 = RotateLeft32(xp4, 10);
// Round 59
x1 = RotateLeft32(x1 + G48_63(x2, x3, x4) + _block[15] + RMD160Round48To63, 6) + x0;
x3 = RotateLeft32(x3, 10);
xp1 = RotateLeft32(xp1 + G16_31(xp2, xp3, xp4) + _block[13] + RMD160RoundPrime48To63, 9) + xp0;
xp3 = RotateLeft32(xp3, 10);
// Round 60
x0 = RotateLeft32(x0 + G48_63(x1, x2, x3) + _block[14] + RMD160Round48To63, 8) + x4;
x2 = RotateLeft32(x2, 10);
xp0 = RotateLeft32(xp0 + G16_31(xp1, xp2, xp3) + _block[9] + RMD160RoundPrime48To63, 12) + xp4;
xp2 = RotateLeft32(xp2, 10);
// Round 61
x4 = RotateLeft32(x4 + G48_63(x0, x1, x2) + _block[5] + RMD160Round48To63, 6) + x3;
x1 = RotateLeft32(x1, 10);
xp4 = RotateLeft32(xp4 + G16_31(xp0, xp1, xp2) + _block[7] + RMD160RoundPrime48To63, 5) + xp3;
xp1 = RotateLeft32(xp1, 10);
// Round 62
x3 = RotateLeft32(x3 + G48_63(x4, x0, x1) + _block[6] + RMD160Round48To63, 5) + x2;
x0 = RotateLeft32(x0, 10);
xp3 = RotateLeft32(xp3 + G16_31(xp4, xp0, xp1) + _block[10] + RMD160RoundPrime48To63, 15) + xp2;
xp0 = RotateLeft32(xp0, 10);
// Round 63
x2 = RotateLeft32(x2 + G48_63(x3, x4, x0) + _block[2] + RMD160Round48To63, 12) + x1;
x4 = RotateLeft32(x4, 10);
xp2 = RotateLeft32(xp2 + G16_31(xp3, xp4, xp0) + _block[14] + RMD160RoundPrime48To63, 8) + xp1;
xp4 = RotateLeft32(xp4, 10);
#endregion
#region Rounds 64-79
// Round 64
x1 = RotateLeft32(x1 + G64_79(x2, x3, x4) + _block[4] + RMD160Round64To79, 9) + x0;
x3 = RotateLeft32(x3, 10);
xp1 = RotateLeft32(xp1 + G00_15(xp2, xp3, xp4) + _block[12] + RMD160RoundPrime64To79, 8) + xp0;
xp3 = RotateLeft32(xp3, 10);
// Round 65
x0 = RotateLeft32(x0 + G64_79(x1, x2, x3) + _block[0] + RMD160Round64To79, 15) + x4;
x2 = RotateLeft32(x2, 10);
xp0 = RotateLeft32(xp0 + G00_15(xp1, xp2, xp3) + _block[15] + RMD160RoundPrime64To79, 5) + xp4;
xp2 = RotateLeft32(xp2, 10);
// Round 66
x4 = RotateLeft32(x4 + G64_79(x0, x1, x2) + _block[5] + RMD160Round64To79, 5) + x3;
x1 = RotateLeft32(x1, 10);
xp4 = RotateLeft32(xp4 + G00_15(xp0, xp1, xp2) + _block[10] + RMD160RoundPrime64To79, 12) + xp3;
xp1 = RotateLeft32(xp1, 10);
// Round 67
x3 = RotateLeft32(x3 + G64_79(x4, x0, x1) + _block[9] + RMD160Round64To79, 11) + x2;
x0 = RotateLeft32(x0, 10);
xp3 = RotateLeft32(xp3 + G00_15(xp4, xp0, xp1) + _block[4] + RMD160RoundPrime64To79, 9) + xp2;
xp0 = RotateLeft32(xp0, 10);
// Round 68
x2 = RotateLeft32(x2 + G64_79(x3, x4, x0) + _block[7] + RMD160Round64To79, 6) + x1;
x4 = RotateLeft32(x4, 10);
xp2 = RotateLeft32(xp2 + G00_15(xp3, xp4, xp0) + _block[1] + RMD160RoundPrime64To79, 12) + xp1;
xp4 = RotateLeft32(xp4, 10);
// Round 69
x1 = RotateLeft32(x1 + G64_79(x2, x3, x4) + _block[12] + RMD160Round64To79, 8) + x0;
x3 = RotateLeft32(x3, 10);
xp1 = RotateLeft32(xp1 + G00_15(xp2, xp3, xp4) + _block[5] + RMD160RoundPrime64To79, 5) + xp0;
xp3 = RotateLeft32(xp3, 10);
// Round 70
x0 = RotateLeft32(x0 + G64_79(x1, x2, x3) + _block[2] + RMD160Round64To79, 13) + x4;
x2 = RotateLeft32(x2, 10);
xp0 = RotateLeft32(xp0 + G00_15(xp1, xp2, xp3) + _block[8] + RMD160RoundPrime64To79, 14) + xp4;
xp2 = RotateLeft32(xp2, 10);
// Round 71
x4 = RotateLeft32(x4 + G64_79(x0, x1, x2) + _block[10] + RMD160Round64To79, 12) + x3;
x1 = RotateLeft32(x1, 10);
xp4 = RotateLeft32(xp4 + G00_15(xp0, xp1, xp2) + _block[7] + RMD160RoundPrime64To79, 6) + xp3;
xp1 = RotateLeft32(xp1, 10);
// Round 72
x3 = RotateLeft32(x3 + G64_79(x4, x0, x1) + _block[14] + RMD160Round64To79, 5) + x2;
x0 = RotateLeft32(x0, 10);
xp3 = RotateLeft32(xp3 + G00_15(xp4, xp0, xp1) + _block[6] + RMD160RoundPrime64To79, 8) + xp2;
xp0 = RotateLeft32(xp0, 10);
// Round 73
x2 = RotateLeft32(x2 + G64_79(x3, x4, x0) + _block[1] + RMD160Round64To79, 12) + x1;
x4 = RotateLeft32(x4, 10);
xp2 = RotateLeft32(xp2 + G00_15(xp3, xp4, xp0) + _block[2] + RMD160RoundPrime64To79, 13) + xp1;
xp4 = RotateLeft32(xp4, 10);
// Round 74
x1 = RotateLeft32(x1 + G64_79(x2, x3, x4) + _block[3] + RMD160Round64To79, 13) + x0;
x3 = RotateLeft32(x3, 10);
xp1 = RotateLeft32(xp1 + G00_15(xp2, xp3, xp4) + _block[13] + RMD160RoundPrime64To79, 6) + xp0;
xp3 = RotateLeft32(xp3, 10);
// Round 75
x0 = RotateLeft32(x0 + G64_79(x1, x2, x3) + _block[8] + RMD160Round64To79, 14) + x4;
x2 = RotateLeft32(x2, 10);
xp0 = RotateLeft32(xp0 + G00_15(xp1, xp2, xp3) + _block[14] + RMD160RoundPrime64To79, 5) + xp4;
xp2 = RotateLeft32(xp2, 10);
// Round 76
x4 = RotateLeft32(x4 + G64_79(x0, x1, x2) + _block[11] + RMD160Round64To79, 11) + x3;
x1 = RotateLeft32(x1, 10);
xp4 = RotateLeft32(xp4 + G00_15(xp0, xp1, xp2) + _block[0] + RMD160RoundPrime64To79, 15) + xp3;
xp1 = RotateLeft32(xp1, 10);
// Round 77
x3 = RotateLeft32(x3 + G64_79(x4, x0, x1) + _block[6] + RMD160Round64To79, 8) + x2;
x0 = RotateLeft32(x0, 10);
xp3 = RotateLeft32(xp3 + G00_15(xp4, xp0, xp1) + _block[3] + RMD160RoundPrime64To79, 13) + xp2;
xp0 = RotateLeft32(xp0, 10);
// Round 78
x2 = RotateLeft32(x2 + G64_79(x3, x4, x0) + _block[15] + RMD160Round64To79, 5) + x1;
x4 = RotateLeft32(x4, 10);
xp2 = RotateLeft32(xp2 + G00_15(xp3, xp4, xp0) + _block[9] + RMD160RoundPrime64To79, 11) + xp1;
xp4 = RotateLeft32(xp4, 10);
// Round 79
x1 = RotateLeft32(x1 + G64_79(x2, x3, x4) + _block[13] + RMD160Round64To79, 6) + x0;
x3 = RotateLeft32(x3, 10);
xp1 = RotateLeft32(xp1 + G00_15(xp2, xp3, xp4) + _block[11] + RMD160RoundPrime64To79, 11) + xp0;
xp3 = RotateLeft32(xp3, 10);
#endregion
// Avalanche values
xp3 += x2 + _state[1];
_state[1] = _state[2] + x3 + xp4;
_state[2] = _state[3] + x4 + xp0;
_state[3] = _state[4] + x0 + xp1;
_state[4] = _state[0] + x1 + xp2;
_state[0] = xp3;
}
/// <summary>
/// Round operation [0, 15]
/// </summary>
private static uint G00_15(uint x, uint y, uint z) => x ^ y ^ z;
/// <summary>
/// Round operation [16, 31]
/// </summary>
private static uint G16_31(uint x, uint y, uint z) => (x & y) | (~x & z);
/// <summary>
/// Round operation [32, 47]
/// </summary>
private static uint G32_47(uint x, uint y, uint z) => (x | ~y) ^ z;
/// <summary>
/// Round operation [48, 63]
/// </summary>
private static uint G48_63(uint x, uint y, uint z) => (x & z) | (y & ~z);
/// <summary>
/// Round operation [64, 79]
/// </summary>
private static uint G64_79(uint x, uint y, uint z) => x ^ (y | ~z);
}
}

View File

@@ -0,0 +1,467 @@
using System;
using static SabreTools.Hashing.CryptographicHash.Constants;
using static SabreTools.Hashing.HashOperations;
namespace SabreTools.Hashing.CryptographicHash
{
/// <see href="https://cdn.standards.iteh.ai/samples/39876/10f9f9f4bb614eaaaeba7e157e183ca3/ISO-IEC-10118-3-2004.pdf"/>
/// <see href="https://homes.esat.kuleuven.be/~bosselae/ripemd160/pdf/AB-9601/AB-9601.pdf"/>
public class RipeMD256 : MessageDigestBase<uint>
{
/// <inheritdoc/>
public override int HashSize => 256;
/// <summary>
/// Set of 4 32-bit numbers representing the hash state
/// </summary>
private readonly uint[] _state = new uint[8];
public RipeMD256() : base()
{
}
/// <inheritdoc/>
protected override void ResetImpl()
{
_state[0] = RMD128Y0;
_state[1] = RMD128Y1;
_state[2] = RMD128Y2;
_state[3] = RMD128Y3;
_state[4] = RMD256Y4;
_state[5] = RMD256Y5;
_state[6] = RMD256Y6;
_state[7] = RMD256Y7;
}
/// <inheritdoc/>
protected override void HashCore(byte[] data, int offset, int length)
{
// Figure out how much buffer is needed
int bufferLen = (int)(_totalBytes & 0x3f);
// Increment the processed byte count
_totalBytes += length;
// If there is buffer to fill and it will meet the limit
if (bufferLen > 0 && bufferLen + length >= 64)
{
// Fill the buffer from the input
Array.Copy(data, offset, _buffer, bufferLen, 64 - bufferLen);
// Set the new values
offset += 64 - bufferLen;
length -= 64 - bufferLen;
// Split the buffer for the round
for (int i = 0; i < 16; i++)
{
_block[i] = ReadLE32(_buffer, i * 4);
}
// Run the round
Round();
bufferLen = 0;
}
/// Process any standalone blocks
while (length >= 64)
{
// Fill the buffer from the input
Array.Copy(data, offset, _buffer, 0, 64);
// Set the new values
offset += 64;
length -= 64;
// Split the buffer for the round
for (int i = 0; i < 16; i++)
{
_block[i] = ReadLE32(_buffer, i * 4);
}
// Run the round
Round();
}
// Save the remainder in the buffer
if (length > 0)
Array.Copy(data, offset, _buffer, bufferLen, length);
}
/// <inheritdoc/>
protected override byte[] HashFinal()
{
// Determine the pad length
int padLength = 64 - (int)(_totalBytes & 0x3f);
if (padLength <= 8)
padLength += 64;
// Get the total byte count in bits
long totalBitCount = _totalBytes * 8;
// Prebuild the padding
var padding = new byte[padLength];
padding[0] = 0x80;
padding[padLength - 1] = (byte)((totalBitCount >> 56) & 0xff);
padding[padLength - 2] = (byte)((totalBitCount >> 48) & 0xff);
padding[padLength - 3] = (byte)((totalBitCount >> 40) & 0xff);
padding[padLength - 4] = (byte)((totalBitCount >> 32) & 0xff);
padding[padLength - 5] = (byte)((totalBitCount >> 24) & 0xff);
padding[padLength - 6] = (byte)((totalBitCount >> 16) & 0xff);
padding[padLength - 7] = (byte)((totalBitCount >> 8) & 0xff);
padding[padLength - 8] = (byte)((totalBitCount >> 0) & 0xff);
// Pad the block
HashCore(padding, 0, padding.Length);
// Get the hash
var hash = new byte[32];
int hashOffset = 0;
// Assemble the hash array
for (int i = 0; i < _state.Length; i++)
{
byte[] segment = BitConverter.GetBytes(_state[i]);
Array.Copy(segment, 0, hash, hashOffset, 4);
hashOffset += 4;
}
return hash;
}
/// <summary>
/// Perform one round of updates on the cached values
/// </summary>
/// <remarks>
/// The official specification for RIPEMD-128 includes tables
/// and instructions that represent a loop. Most standard implementations
/// use the unrolled version of that loop to make it more efficient.
///
/// The below code started with the looped version but has been converted
/// to the more standard implementation instead.
/// </remarks>
private void Round()
{
// Setup values
uint x0 = _state[0], xp0 = _state[4];
uint x1 = _state[1], xp1 = _state[5];
uint x2 = _state[2], xp2 = _state[6];
uint x3 = _state[3], xp3 = _state[7];
uint t;
#region Rounds 0-15
// Round 0
x0 = RotateLeft32(x0 + G00_15(x1, x2, x3) + _block[0] + RMD128Round00To15, 11);
xp0 = RotateLeft32(xp0 + G48_63(xp1, xp2, xp3) + _block[5] + RMD128RoundPrime00To15, 8);
// Round 1
x3 = RotateLeft32(x3 + G00_15(x0, x1, x2) + _block[1] + RMD128Round00To15, 14);
xp3 = RotateLeft32(xp3 + G48_63(xp0, xp1, xp2) + _block[14] + RMD128RoundPrime00To15, 9);
// Round 2
x2 = RotateLeft32(x2 + G00_15(x3, x0, x1) + _block[2] + RMD128Round00To15, 15);
xp2 = RotateLeft32(xp2 + G48_63(xp3, xp0, xp1) + _block[7] + RMD128RoundPrime00To15, 9);
// Round 3
x1 = RotateLeft32(x1 + G00_15(x2, x3, x0) + _block[3] + RMD128Round00To15, 12);
xp1 = RotateLeft32(xp1 + G48_63(xp2, xp3, xp0) + _block[0] + RMD128RoundPrime00To15, 11);
// Round 4
x0 = RotateLeft32(x0 + G00_15(x1, x2, x3) + _block[4] + RMD128Round00To15, 5);
xp0 = RotateLeft32(xp0 + G48_63(xp1, xp2, xp3) + _block[9] + RMD128RoundPrime00To15, 13);
// Round 5
x3 = RotateLeft32(x3 + G00_15(x0, x1, x2) + _block[5] + RMD128Round00To15, 8);
xp3 = RotateLeft32(xp3 + G48_63(xp0, xp1, xp2) + _block[2] + RMD128RoundPrime00To15, 15);
// Round 6
x2 = RotateLeft32(x2 + G00_15(x3, x0, x1) + _block[6] + RMD128Round00To15, 7);
xp2 = RotateLeft32(xp2 + G48_63(xp3, xp0, xp1) + _block[11] + RMD128RoundPrime00To15, 15);
// Round 7
x1 = RotateLeft32(x1 + G00_15(x2, x3, x0) + _block[7] + RMD128Round00To15, 9);
xp1 = RotateLeft32(xp1 + G48_63(xp2, xp3, xp0) + _block[4] + RMD128RoundPrime00To15, 5);
// Round 8
x0 = RotateLeft32(x0 + G00_15(x1, x2, x3) + _block[8] + RMD128Round00To15, 11);
xp0 = RotateLeft32(xp0 + G48_63(xp1, xp2, xp3) + _block[13] + RMD128RoundPrime00To15, 7);
// Round 9
x3 = RotateLeft32(x3 + G00_15(x0, x1, x2) + _block[9] + RMD128Round00To15, 13);
xp3 = RotateLeft32(xp3 + G48_63(xp0, xp1, xp2) + _block[6] + RMD128RoundPrime00To15, 7);
// Round 10
x2 = RotateLeft32(x2 + G00_15(x3, x0, x1) + _block[10] + RMD128Round00To15, 14);
xp2 = RotateLeft32(xp2 + G48_63(xp3, xp0, xp1) + _block[15] + RMD128RoundPrime00To15, 8);
// Round 11
x1 = RotateLeft32(x1 + G00_15(x2, x3, x0) + _block[11] + RMD128Round00To15, 15);
xp1 = RotateLeft32(xp1 + G48_63(xp2, xp3, xp0) + _block[8] + RMD128RoundPrime00To15, 11);
// Round 12
x0 = RotateLeft32(x0 + G00_15(x1, x2, x3) + _block[12] + RMD128Round00To15, 6);
xp0 = RotateLeft32(xp0 + G48_63(xp1, xp2, xp3) + _block[1] + RMD128RoundPrime00To15, 14);
// Round 13
x3 = RotateLeft32(x3 + G00_15(x0, x1, x2) + _block[13] + RMD128Round00To15, 7);
xp3 = RotateLeft32(xp3 + G48_63(xp0, xp1, xp2) + _block[10] + RMD128RoundPrime00To15, 14);
// Round 14
x2 = RotateLeft32(x2 + G00_15(x3, x0, x1) + _block[14] + RMD128Round00To15, 9);
xp2 = RotateLeft32(xp2 + G48_63(xp3, xp0, xp1) + _block[3] + RMD128RoundPrime00To15, 12);
// Round 15
x1 = RotateLeft32(x1 + G00_15(x2, x3, x0) + _block[15] + RMD128Round00To15, 8);
xp1 = RotateLeft32(xp1 + G48_63(xp2, xp3, xp0) + _block[12] + RMD128RoundPrime00To15, 6);
// Swap set 1
t = x0; x0 = xp0; xp0 = t;
#endregion
#region Rounds 16-31
// Round 16
x0 = RotateLeft32(x0 + G16_31(x1, x2, x3) + _block[7] + RMD128Round16To31, 7);
xp0 = RotateLeft32(xp0 + G32_47(xp1, xp2, xp3) + _block[6] + RMD128RoundPrime16To31, 9);
// Round 17
x3 = RotateLeft32(x3 + G16_31(x0, x1, x2) + _block[4] + RMD128Round16To31, 6);
xp3 = RotateLeft32(xp3 + G32_47(xp0, xp1, xp2) + _block[11] + RMD128RoundPrime16To31, 13);
// Round 18
x2 = RotateLeft32(x2 + G16_31(x3, x0, x1) + _block[13] + RMD128Round16To31, 8);
xp2 = RotateLeft32(xp2 + G32_47(xp3, xp0, xp1) + _block[3] + RMD128RoundPrime16To31, 15);
// Round 19
x1 = RotateLeft32(x1 + G16_31(x2, x3, x0) + _block[1] + RMD128Round16To31, 13);
xp1 = RotateLeft32(xp1 + G32_47(xp2, xp3, xp0) + _block[7] + RMD128RoundPrime16To31, 7);
// Round 20
x0 = RotateLeft32(x0 + G16_31(x1, x2, x3) + _block[10] + RMD128Round16To31, 11);
xp0 = RotateLeft32(xp0 + G32_47(xp1, xp2, xp3) + _block[0] + RMD128RoundPrime16To31, 12);
// Round 21
x3 = RotateLeft32(x3 + G16_31(x0, x1, x2) + _block[6] + RMD128Round16To31, 9);
xp3 = RotateLeft32(xp3 + G32_47(xp0, xp1, xp2) + _block[13] + RMD128RoundPrime16To31, 8);
// Round 22
x2 = RotateLeft32(x2 + G16_31(x3, x0, x1) + _block[15] + RMD128Round16To31, 7);
xp2 = RotateLeft32(xp2 + G32_47(xp3, xp0, xp1) + _block[5] + RMD128RoundPrime16To31, 9);
// Round 23
x1 = RotateLeft32(x1 + G16_31(x2, x3, x0) + _block[3] + RMD128Round16To31, 15);
xp1 = RotateLeft32(xp1 + G32_47(xp2, xp3, xp0) + _block[10] + RMD128RoundPrime16To31, 11);
// Round 24
x0 = RotateLeft32(x0 + G16_31(x1, x2, x3) + _block[12] + RMD128Round16To31, 7);
xp0 = RotateLeft32(xp0 + G32_47(xp1, xp2, xp3) + _block[14] + RMD128RoundPrime16To31, 7);
// Round 25
x3 = RotateLeft32(x3 + G16_31(x0, x1, x2) + _block[0] + RMD128Round16To31, 12);
xp3 = RotateLeft32(xp3 + G32_47(xp0, xp1, xp2) + _block[15] + RMD128RoundPrime16To31, 7);
// Round 26
x2 = RotateLeft32(x2 + G16_31(x3, x0, x1) + _block[9] + RMD128Round16To31, 15);
xp2 = RotateLeft32(xp2 + G32_47(xp3, xp0, xp1) + _block[8] + RMD128RoundPrime16To31, 12);
// Round 27
x1 = RotateLeft32(x1 + G16_31(x2, x3, x0) + _block[5] + RMD128Round16To31, 9);
xp1 = RotateLeft32(xp1 + G32_47(xp2, xp3, xp0) + _block[12] + RMD128RoundPrime16To31, 7);
// Round 28
x0 = RotateLeft32(x0 + G16_31(x1, x2, x3) + _block[2] + RMD128Round16To31, 11);
xp0 = RotateLeft32(xp0 + G32_47(xp1, xp2, xp3) + _block[4] + RMD128RoundPrime16To31, 6);
// Round 29
x3 = RotateLeft32(x3 + G16_31(x0, x1, x2) + _block[14] + RMD128Round16To31, 7);
xp3 = RotateLeft32(xp3 + G32_47(xp0, xp1, xp2) + _block[9] + RMD128RoundPrime16To31, 15);
// Round 30
x2 = RotateLeft32(x2 + G16_31(x3, x0, x1) + _block[11] + RMD128Round16To31, 13);
xp2 = RotateLeft32(xp2 + G32_47(xp3, xp0, xp1) + _block[1] + RMD128RoundPrime16To31, 13);
// Round 31
x1 = RotateLeft32(x1 + G16_31(x2, x3, x0) + _block[8] + RMD128Round16To31, 12);
xp1 = RotateLeft32(xp1 + G32_47(xp2, xp3, xp0) + _block[2] + RMD128RoundPrime16To31, 11);
// Swap set 2
t = x1; x1 = xp1; xp1 = t;
#endregion
#region Rounds 32-47
// Round 32
x0 = RotateLeft32(x0 + G32_47(x1, x2, x3) + _block[3] + RMD128Round32To47, 11);
xp0 = RotateLeft32(xp0 + G16_31(xp1, xp2, xp3) + _block[15] + RMD128RoundPrime32To47, 9);
// Round 33
x3 = RotateLeft32(x3 + G32_47(x0, x1, x2) + _block[10] + RMD128Round32To47, 13);
xp3 = RotateLeft32(xp3 + G16_31(xp0, xp1, xp2) + _block[5] + RMD128RoundPrime32To47, 7);
// Round 34
x2 = RotateLeft32(x2 + G32_47(x3, x0, x1) + _block[14] + RMD128Round32To47, 6);
xp2 = RotateLeft32(xp2 + G16_31(xp3, xp0, xp1) + _block[1] + RMD128RoundPrime32To47, 15);
// Round 35
x1 = RotateLeft32(x1 + G32_47(x2, x3, x0) + _block[4] + RMD128Round32To47, 7);
xp1 = RotateLeft32(xp1 + G16_31(xp2, xp3, xp0) + _block[3] + RMD128RoundPrime32To47, 11);
// Round 36
x0 = RotateLeft32(x0 + G32_47(x1, x2, x3) + _block[9] + RMD128Round32To47, 14);
xp0 = RotateLeft32(xp0 + G16_31(xp1, xp2, xp3) + _block[7] + RMD128RoundPrime32To47, 8);
// Round 37
x3 = RotateLeft32(x3 + G32_47(x0, x1, x2) + _block[15] + RMD128Round32To47, 9);
xp3 = RotateLeft32(xp3 + G16_31(xp0, xp1, xp2) + _block[14] + RMD128RoundPrime32To47, 6);
// Round 38
x2 = RotateLeft32(x2 + G32_47(x3, x0, x1) + _block[8] + RMD128Round32To47, 13);
xp2 = RotateLeft32(xp2 + G16_31(xp3, xp0, xp1) + _block[6] + RMD128RoundPrime32To47, 6);
// Round 39
x1 = RotateLeft32(x1 + G32_47(x2, x3, x0) + _block[1] + RMD128Round32To47, 15);
xp1 = RotateLeft32(xp1 + G16_31(xp2, xp3, xp0) + _block[9] + RMD128RoundPrime32To47, 14);
// Round 40
x0 = RotateLeft32(x0 + G32_47(x1, x2, x3) + _block[2] + RMD128Round32To47, 14);
xp0 = RotateLeft32(xp0 + G16_31(xp1, xp2, xp3) + _block[11] + RMD128RoundPrime32To47, 12);
// Round 41
x3 = RotateLeft32(x3 + G32_47(x0, x1, x2) + _block[7] + RMD128Round32To47, 8);
xp3 = RotateLeft32(xp3 + G16_31(xp0, xp1, xp2) + _block[8] + RMD128RoundPrime32To47, 13);
// Round 42
x2 = RotateLeft32(x2 + G32_47(x3, x0, x1) + _block[0] + RMD128Round32To47, 13);
xp2 = RotateLeft32(xp2 + G16_31(xp3, xp0, xp1) + _block[12] + RMD128RoundPrime32To47, 5);
// Round 43
x1 = RotateLeft32(x1 + G32_47(x2, x3, x0) + _block[6] + RMD128Round32To47, 6);
xp1 = RotateLeft32(xp1 + G16_31(xp2, xp3, xp0) + _block[2] + RMD128RoundPrime32To47, 14);
// Round 44
x0 = RotateLeft32(x0 + G32_47(x1, x2, x3) + _block[13] + RMD128Round32To47, 5);
xp0 = RotateLeft32(xp0 + G16_31(xp1, xp2, xp3) + _block[10] + RMD128RoundPrime32To47, 13);
// Round 45
x3 = RotateLeft32(x3 + G32_47(x0, x1, x2) + _block[11] + RMD128Round32To47, 12);
xp3 = RotateLeft32(xp3 + G16_31(xp0, xp1, xp2) + _block[0] + RMD128RoundPrime32To47, 13);
// Round 46
x2 = RotateLeft32(x2 + G32_47(x3, x0, x1) + _block[5] + RMD128Round32To47, 7);
xp2 = RotateLeft32(xp2 + G16_31(xp3, xp0, xp1) + _block[4] + RMD128RoundPrime32To47, 7);
// Round 47
x1 = RotateLeft32(x1 + G32_47(x2, x3, x0) + _block[12] + RMD128Round32To47, 5);
xp1 = RotateLeft32(xp1 + G16_31(xp2, xp3, xp0) + _block[13] + RMD128RoundPrime32To47, 5);
// Swap set 3
t = x2; x2 = xp2; xp2 = t;
#endregion
#region Rounds 48-63
// Round 48
x0 = RotateLeft32(x0 + G48_63(x1, x2, x3) + _block[1] + RMD128Round48To63, 11);
xp0 = RotateLeft32(xp0 + G00_15(xp1, xp2, xp3) + _block[8] + RMD128RoundPrime48To63, 15);
// Round 49
x3 = RotateLeft32(x3 + G48_63(x0, x1, x2) + _block[9] + RMD128Round48To63, 12);
xp3 = RotateLeft32(xp3 + G00_15(xp0, xp1, xp2) + _block[6] + RMD128RoundPrime48To63, 5);
// Round 50
x2 = RotateLeft32(x2 + G48_63(x3, x0, x1) + _block[11] + RMD128Round48To63, 14);
xp2 = RotateLeft32(xp2 + G00_15(xp3, xp0, xp1) + _block[4] + RMD128RoundPrime48To63, 8);
// Round 51
x1 = RotateLeft32(x1 + G48_63(x2, x3, x0) + _block[10] + RMD128Round48To63, 15);
xp1 = RotateLeft32(xp1 + G00_15(xp2, xp3, xp0) + _block[1] + RMD128RoundPrime48To63, 11);
// Round 52
x0 = RotateLeft32(x0 + G48_63(x1, x2, x3) + _block[0] + RMD128Round48To63, 14);
xp0 = RotateLeft32(xp0 + G00_15(xp1, xp2, xp3) + _block[3] + RMD128RoundPrime48To63, 14);
// Round 53
x3 = RotateLeft32(x3 + G48_63(x0, x1, x2) + _block[8] + RMD128Round48To63, 15);
xp3 = RotateLeft32(xp3 + G00_15(xp0, xp1, xp2) + _block[11] + RMD128RoundPrime48To63, 14);
// Round 54
x2 = RotateLeft32(x2 + G48_63(x3, x0, x1) + _block[12] + RMD128Round48To63, 9);
xp2 = RotateLeft32(xp2 + G00_15(xp3, xp0, xp1) + _block[15] + RMD128RoundPrime48To63, 6);
// Round 55
x1 = RotateLeft32(x1 + G48_63(x2, x3, x0) + _block[4] + RMD128Round48To63, 8);
xp1 = RotateLeft32(xp1 + G00_15(xp2, xp3, xp0) + _block[0] + RMD128RoundPrime48To63, 14);
// Round 56
x0 = RotateLeft32(x0 + G48_63(x1, x2, x3) + _block[13] + RMD128Round48To63, 9);
xp0 = RotateLeft32(xp0 + G00_15(xp1, xp2, xp3) + _block[5] + RMD128RoundPrime48To63, 6);
// Round 57
x3 = RotateLeft32(x3 + G48_63(x0, x1, x2) + _block[3] + RMD128Round48To63, 14);
xp3 = RotateLeft32(xp3 + G00_15(xp0, xp1, xp2) + _block[12] + RMD128RoundPrime48To63, 9);
// Round 58
x2 = RotateLeft32(x2 + G48_63(x3, x0, x1) + _block[7] + RMD128Round48To63, 5);
xp2 = RotateLeft32(xp2 + G00_15(xp3, xp0, xp1) + _block[2] + RMD128RoundPrime48To63, 12);
// Round 59
x1 = RotateLeft32(x1 + G48_63(x2, x3, x0) + _block[15] + RMD128Round48To63, 6);
xp1 = RotateLeft32(xp1 + G00_15(xp2, xp3, xp0) + _block[13] + RMD128RoundPrime48To63, 9);
// Round 60
x0 = RotateLeft32(x0 + G48_63(x1, x2, x3) + _block[14] + RMD128Round48To63, 8);
xp0 = RotateLeft32(xp0 + G00_15(xp1, xp2, xp3) + _block[9] + RMD128RoundPrime48To63, 12);
// Round 61
x3 = RotateLeft32(x3 + G48_63(x0, x1, x2) + _block[5] + RMD128Round48To63, 6);
xp3 = RotateLeft32(xp3 + G00_15(xp0, xp1, xp2) + _block[7] + RMD128RoundPrime48To63, 5);
// Round 62
x2 = RotateLeft32(x2 + G48_63(x3, x0, x1) + _block[6] + RMD128Round48To63, 5);
xp2 = RotateLeft32(xp2 + G00_15(xp3, xp0, xp1) + _block[10] + RMD128RoundPrime48To63, 15);
// Round 63
x1 = RotateLeft32(x1 + G48_63(x2, x3, x0) + _block[2] + RMD128Round48To63, 12);
xp1 = RotateLeft32(xp1 + G00_15(xp2, xp3, xp0) + _block[14] + RMD128RoundPrime48To63, 8);
// Swap set 4
t = x3; x3 = xp3; xp3 = t;
#endregion
// Avalanche values
_state[0] += x0;
_state[1] += x1;
_state[2] += x2;
_state[3] += x3;
_state[4] += xp0;
_state[5] += xp1;
_state[6] += xp2;
_state[7] += xp3;
}
/// <summary>
/// Round operation [0, 15]
/// </summary>
private static uint G00_15(uint x, uint y, uint z) => x ^ y ^ z;
/// <summary>
/// Round operation [16, 31]
/// </summary>
private static uint G16_31(uint x, uint y, uint z) => (x & y) | (~x & z);
/// <summary>
/// Round operation [32, 47]
/// </summary>
private static uint G32_47(uint x, uint y, uint z) => (x | ~y) ^ z;
/// <summary>
/// Round operation [48, 63]
/// </summary>
private static uint G48_63(uint x, uint y, uint z) => (x & z) | (y & ~z);
}
}

View File

@@ -0,0 +1,708 @@
using System;
using static SabreTools.Hashing.CryptographicHash.Constants;
using static SabreTools.Hashing.HashOperations;
namespace SabreTools.Hashing.CryptographicHash
{
/// <see href="https://cdn.standards.iteh.ai/samples/39876/10f9f9f4bb614eaaaeba7e157e183ca3/ISO-IEC-10118-3-2004.pdf"/>
/// <see href="https://homes.esat.kuleuven.be/~bosselae/ripemd160/pdf/AB-9601/AB-9601.pdf"/>
public class RipeMD320 : MessageDigestBase<uint>
{
/// <inheritdoc/>
public override int HashSize => 320;
/// <summary>
/// Set of 10 32-bit numbers representing the hash state
/// </summary>
private readonly uint[] _state = new uint[10];
public RipeMD320() : base()
{
}
/// <inheritdoc/>
protected override void ResetImpl()
{
_state[0] = RMD160Y0;
_state[1] = RMD160Y1;
_state[2] = RMD160Y2;
_state[3] = RMD160Y3;
_state[4] = RMD160Y4;
_state[5] = RMD320Y5;
_state[6] = RMD320Y6;
_state[7] = RMD320Y7;
_state[8] = RMD320Y8;
_state[9] = RMD320Y9;
}
/// <inheritdoc/>
protected override void HashCore(byte[] data, int offset, int length)
{
// Figure out how much buffer is needed
int bufferLen = (int)(_totalBytes & 0x3f);
// Increment the processed byte count
_totalBytes += length;
// If there is buffer to fill and it will meet the limit
if (bufferLen > 0 && bufferLen + length >= 64)
{
// Fill the buffer from the input
Array.Copy(data, offset, _buffer, bufferLen, 64 - bufferLen);
// Set the new values
offset += 64 - bufferLen;
length -= 64 - bufferLen;
// Split the buffer for the round
for (int i = 0; i < 16; i++)
{
_block[i] = ReadLE32(_buffer, i * 4);
}
// Run the round
Round();
bufferLen = 0;
}
/// Process any standalone blocks
while (length >= 64)
{
// Fill the buffer from the input
Array.Copy(data, offset, _buffer, 0, 64);
// Set the new values
offset += 64;
length -= 64;
// Split the buffer for the round
for (int i = 0; i < 16; i++)
{
_block[i] = ReadLE32(_buffer, i * 4);
}
// Run the round
Round();
}
// Save the remainder in the buffer
if (length > 0)
Array.Copy(data, offset, _buffer, bufferLen, length);
}
/// <inheritdoc/>
protected override byte[] HashFinal()
{
// Determine the pad length
int padLength = 64 - (int)(_totalBytes & 0x3f);
if (padLength <= 8)
padLength += 64;
// Get the total byte count in bits
long totalBitCount = _totalBytes * 8;
// Prebuild the padding
var padding = new byte[padLength];
padding[0] = 0x80;
padding[padLength - 1] = (byte)((totalBitCount >> 56) & 0xff);
padding[padLength - 2] = (byte)((totalBitCount >> 48) & 0xff);
padding[padLength - 3] = (byte)((totalBitCount >> 40) & 0xff);
padding[padLength - 4] = (byte)((totalBitCount >> 32) & 0xff);
padding[padLength - 5] = (byte)((totalBitCount >> 24) & 0xff);
padding[padLength - 6] = (byte)((totalBitCount >> 16) & 0xff);
padding[padLength - 7] = (byte)((totalBitCount >> 8) & 0xff);
padding[padLength - 8] = (byte)((totalBitCount >> 0) & 0xff);
// Pad the block
HashCore(padding, 0, padding.Length);
// Get the hash
var hash = new byte[40];
int hashOffset = 0;
// Assemble the hash array
for (int i = 0; i < _state.Length; i++)
{
byte[] segment = BitConverter.GetBytes(_state[i]);
Array.Copy(segment, 0, hash, hashOffset, 4);
hashOffset += 4;
}
return hash;
}
/// <summary>
/// Perform one round of updates on the cached values
/// </summary>
/// <remarks>
/// The official specification for RIPEMD-160 includes tables
/// and instructions that represent a loop. Most standard implementations
/// use the unrolled version of that loop to make it more efficient.
///
/// The below code started with the looped version but has been converted
/// to the more standard implementation instead.
/// </remarks>
private void Round()
{
// Setup values
uint x0 = _state[0], xp0 = _state[5];
uint x1 = _state[1], xp1 = _state[6];
uint x2 = _state[2], xp2 = _state[7];
uint x3 = _state[3], xp3 = _state[8];
uint x4 = _state[4], xp4 = _state[9];
uint t;
#region Rounds 0-15
// Round 0
x0 = RotateLeft32(x0 + G00_15(x1, x2, x3) + _block[0] + RMD160Round00To15, 11) + x4;
x2 = RotateLeft32(x2, 10);
xp0 = RotateLeft32(xp0 + G64_79(xp1, xp2, xp3) + _block[5] + RMD160RoundPrime00To15, 8) + xp4;
xp2 = RotateLeft32(xp2, 10);
// Round 1
x4 = RotateLeft32(x4 + G00_15(x0, x1, x2) + _block[1] + RMD160Round00To15, 14) + x3;
x1 = RotateLeft32(x1, 10);
xp4 = RotateLeft32(xp4 + G64_79(xp0, xp1, xp2) + _block[14] + RMD160RoundPrime00To15, 9) + xp3;
xp1 = RotateLeft32(xp1, 10);
// Round 2
x3 = RotateLeft32(x3 + G00_15(x4, x0, x1) + _block[2] + RMD160Round00To15, 15) + x2;
x0 = RotateLeft32(x0, 10);
xp3 = RotateLeft32(xp3 + G64_79(xp4, xp0, xp1) + _block[7] + RMD160RoundPrime00To15, 9) + xp2;
xp0 = RotateLeft32(xp0, 10);
// Round 3
x2 = RotateLeft32(x2 + G00_15(x3, x4, x0) + _block[3] + RMD160Round00To15, 12) + x1;
x4 = RotateLeft32(x4, 10);
xp2 = RotateLeft32(xp2 + G64_79(xp3, xp4, xp0) + _block[0] + RMD160RoundPrime00To15, 11) + xp1;
xp4 = RotateLeft32(xp4, 10);
// Round 4
x1 = RotateLeft32(x1 + G00_15(x2, x3, x4) + _block[4] + RMD160Round00To15, 5) + x0;
x3 = RotateLeft32(x3, 10);
xp1 = RotateLeft32(xp1 + G64_79(xp2, xp3, xp4) + _block[9] + RMD160RoundPrime00To15, 13) + xp0;
xp3 = RotateLeft32(xp3, 10);
// Round 5
x0 = RotateLeft32(x0 + G00_15(x1, x2, x3) + _block[5] + RMD160Round00To15, 8) + x4;
x2 = RotateLeft32(x2, 10);
xp0 = RotateLeft32(xp0 + G64_79(xp1, xp2, xp3) + _block[2] + RMD160RoundPrime00To15, 15) + xp4;
xp2 = RotateLeft32(xp2, 10);
// Round 6
x4 = RotateLeft32(x4 + G00_15(x0, x1, x2) + _block[6] + RMD160Round00To15, 7) + x3;
x1 = RotateLeft32(x1, 10);
xp4 = RotateLeft32(xp4 + G64_79(xp0, xp1, xp2) + _block[11] + RMD160RoundPrime00To15, 15) + xp3;
xp1 = RotateLeft32(xp1, 10);
// Round 7
x3 = RotateLeft32(x3 + G00_15(x4, x0, x1) + _block[7] + RMD160Round00To15, 9) + x2;
x0 = RotateLeft32(x0, 10);
xp3 = RotateLeft32(xp3 + G64_79(xp4, xp0, xp1) + _block[4] + RMD160RoundPrime00To15, 5) + xp2;
xp0 = RotateLeft32(xp0, 10);
// Round 8
x2 = RotateLeft32(x2 + G00_15(x3, x4, x0) + _block[8] + RMD160Round00To15, 11) + x1;
x4 = RotateLeft32(x4, 10);
xp2 = RotateLeft32(xp2 + G64_79(xp3, xp4, xp0) + _block[13] + RMD160RoundPrime00To15, 7) + xp1;
xp4 = RotateLeft32(xp4, 10);
// Round 9
x1 = RotateLeft32(x1 + G00_15(x2, x3, x4) + _block[9] + RMD160Round00To15, 13) + x0;
x3 = RotateLeft32(x3, 10);
xp1 = RotateLeft32(xp1 + G64_79(xp2, xp3, xp4) + _block[6] + RMD160RoundPrime00To15, 7) + xp0;
xp3 = RotateLeft32(xp3, 10);
// Round 10
x0 = RotateLeft32(x0 + G00_15(x1, x2, x3) + _block[10] + RMD160Round00To15, 14) + x4;
x2 = RotateLeft32(x2, 10);
xp0 = RotateLeft32(xp0 + G64_79(xp1, xp2, xp3) + _block[15] + RMD160RoundPrime00To15, 8) + xp4;
xp2 = RotateLeft32(xp2, 10);
// Round 11
x4 = RotateLeft32(x4 + G00_15(x0, x1, x2) + _block[11] + RMD160Round00To15, 15) + x3;
x1 = RotateLeft32(x1, 10);
xp4 = RotateLeft32(xp4 + G64_79(xp0, xp1, xp2) + _block[8] + RMD160RoundPrime00To15, 11) + xp3;
xp1 = RotateLeft32(xp1, 10);
// Round 12
x3 = RotateLeft32(x3 + G00_15(x4, x0, x1) + _block[12] + RMD160Round00To15, 6) + x2;
x0 = RotateLeft32(x0, 10);
xp3 = RotateLeft32(xp3 + G64_79(xp4, xp0, xp1) + _block[1] + RMD160RoundPrime00To15, 14) + xp2;
xp0 = RotateLeft32(xp0, 10);
// Round 13
x2 = RotateLeft32(x2 + G00_15(x3, x4, x0) + _block[13] + RMD160Round00To15, 7) + x1;
x4 = RotateLeft32(x4, 10);
xp2 = RotateLeft32(xp2 + G64_79(xp3, xp4, xp0) + _block[10] + RMD160RoundPrime00To15, 14) + xp1;
xp4 = RotateLeft32(xp4, 10);
// Round 14
x1 = RotateLeft32(x1 + G00_15(x2, x3, x4) + _block[14] + RMD160Round00To15, 9) + x0;
x3 = RotateLeft32(x3, 10);
xp1 = RotateLeft32(xp1 + G64_79(xp2, xp3, xp4) + _block[3] + RMD160RoundPrime00To15, 12) + xp0;
xp3 = RotateLeft32(xp3, 10);
// Round 15
x0 = RotateLeft32(x0 + G00_15(x1, x2, x3) + _block[15] + RMD160Round00To15, 8) + x4;
x2 = RotateLeft32(x2, 10);
xp0 = RotateLeft32(xp0 + G64_79(xp1, xp2, xp3) + _block[12] + RMD160RoundPrime00To15, 6) + xp4;
xp2 = RotateLeft32(xp2, 10);
// Swap set 1
t = x0; x0 = xp0; xp0 = t;
#endregion
#region Rounds 16-31
// Round 16
x4 = RotateLeft32(x4 + G16_31(x0, x1, x2) + _block[7] + RMD160Round16To31, 7) + x3;
x1 = RotateLeft32(x1, 10);
xp4 = RotateLeft32(xp4 + G48_63(xp0, xp1, xp2) + _block[6] + RMD160RoundPrime16To31, 9) + xp3;
xp1 = RotateLeft32(xp1, 10);
// Round 17
x3 = RotateLeft32(x3 + G16_31(x4, x0, x1) + _block[4] + RMD160Round16To31, 6) + x2;
x0 = RotateLeft32(x0, 10);
xp3 = RotateLeft32(xp3 + G48_63(xp4, xp0, xp1) + _block[11] + RMD160RoundPrime16To31, 13) + xp2;
xp0 = RotateLeft32(xp0, 10);
// Round 18
x2 = RotateLeft32(x2 + G16_31(x3, x4, x0) + _block[13] + RMD160Round16To31, 8) + x1;
x4 = RotateLeft32(x4, 10);
xp2 = RotateLeft32(xp2 + G48_63(xp3, xp4, xp0) + _block[3] + RMD160RoundPrime16To31, 15) + xp1;
xp4 = RotateLeft32(xp4, 10);
// Round 19
x1 = RotateLeft32(x1 + G16_31(x2, x3, x4) + _block[1] + RMD160Round16To31, 13) + x0;
x3 = RotateLeft32(x3, 10);
xp1 = RotateLeft32(xp1 + G48_63(xp2, xp3, xp4) + _block[7] + RMD160RoundPrime16To31, 7) + xp0;
xp3 = RotateLeft32(xp3, 10);
// Round 20
x0 = RotateLeft32(x0 + G16_31(x1, x2, x3) + _block[10] + RMD160Round16To31, 11) + x4;
x2 = RotateLeft32(x2, 10);
xp0 = RotateLeft32(xp0 + G48_63(xp1, xp2, xp3) + _block[0] + RMD160RoundPrime16To31, 12) + xp4;
xp2 = RotateLeft32(xp2, 10);
// Round 21
x4 = RotateLeft32(x4 + G16_31(x0, x1, x2) + _block[6] + RMD160Round16To31, 9) + x3;
x1 = RotateLeft32(x1, 10);
xp4 = RotateLeft32(xp4 + G48_63(xp0, xp1, xp2) + _block[13] + RMD160RoundPrime16To31, 8) + xp3;
xp1 = RotateLeft32(xp1, 10);
// Round 22
x3 = RotateLeft32(x3 + G16_31(x4, x0, x1) + _block[15] + RMD160Round16To31, 7) + x2;
x0 = RotateLeft32(x0, 10);
xp3 = RotateLeft32(xp3 + G48_63(xp4, xp0, xp1) + _block[5] + RMD160RoundPrime16To31, 9) + xp2;
xp0 = RotateLeft32(xp0, 10);
// Round 23
x2 = RotateLeft32(x2 + G16_31(x3, x4, x0) + _block[3] + RMD160Round16To31, 15) + x1;
x4 = RotateLeft32(x4, 10);
xp2 = RotateLeft32(xp2 + G48_63(xp3, xp4, xp0) + _block[10] + RMD160RoundPrime16To31, 11) + xp1;
xp4 = RotateLeft32(xp4, 10);
// Round 24
x1 = RotateLeft32(x1 + G16_31(x2, x3, x4) + _block[12] + RMD160Round16To31, 7) + x0;
x3 = RotateLeft32(x3, 10);
xp1 = RotateLeft32(xp1 + G48_63(xp2, xp3, xp4) + _block[14] + RMD160RoundPrime16To31, 7) + xp0;
xp3 = RotateLeft32(xp3, 10);
// Round 25
x0 = RotateLeft32(x0 + G16_31(x1, x2, x3) + _block[0] + RMD160Round16To31, 12) + x4;
x2 = RotateLeft32(x2, 10);
xp0 = RotateLeft32(xp0 + G48_63(xp1, xp2, xp3) + _block[15] + RMD160RoundPrime16To31, 7) + xp4;
xp2 = RotateLeft32(xp2, 10);
// Round 26
x4 = RotateLeft32(x4 + G16_31(x0, x1, x2) + _block[9] + RMD160Round16To31, 15) + x3;
x1 = RotateLeft32(x1, 10);
xp4 = RotateLeft32(xp4 + G48_63(xp0, xp1, xp2) + _block[8] + RMD160RoundPrime16To31, 12) + xp3;
xp1 = RotateLeft32(xp1, 10);
// Round 27
x3 = RotateLeft32(x3 + G16_31(x4, x0, x1) + _block[5] + RMD160Round16To31, 9) + x2;
x0 = RotateLeft32(x0, 10);
xp3 = RotateLeft32(xp3 + G48_63(xp4, xp0, xp1) + _block[12] + RMD160RoundPrime16To31, 7) + xp2;
xp0 = RotateLeft32(xp0, 10);
// Round 28
x2 = RotateLeft32(x2 + G16_31(x3, x4, x0) + _block[2] + RMD160Round16To31, 11) + x1;
x4 = RotateLeft32(x4, 10);
xp2 = RotateLeft32(xp2 + G48_63(xp3, xp4, xp0) + _block[4] + RMD160RoundPrime16To31, 6) + xp1;
xp4 = RotateLeft32(xp4, 10);
// Round 29
x1 = RotateLeft32(x1 + G16_31(x2, x3, x4) + _block[14] + RMD160Round16To31, 7) + x0;
x3 = RotateLeft32(x3, 10);
xp1 = RotateLeft32(xp1 + G48_63(xp2, xp3, xp4) + _block[9] + RMD160RoundPrime16To31, 15) + xp0;
xp3 = RotateLeft32(xp3, 10);
// Round 30
x0 = RotateLeft32(x0 + G16_31(x1, x2, x3) + _block[11] + RMD160Round16To31, 13) + x4;
x2 = RotateLeft32(x2, 10);
xp0 = RotateLeft32(xp0 + G48_63(xp1, xp2, xp3) + _block[1] + RMD160RoundPrime16To31, 13) + xp4;
xp2 = RotateLeft32(xp2, 10);
// Round 31
x4 = RotateLeft32(x4 + G16_31(x0, x1, x2) + _block[8] + RMD160Round16To31, 12) + x3;
x1 = RotateLeft32(x1, 10);
xp4 = RotateLeft32(xp4 + G48_63(xp0, xp1, xp2) + _block[2] + RMD160RoundPrime16To31, 11) + xp3;
xp1 = RotateLeft32(xp1, 10);
// Swap set 2
t = x1; x1 = xp1; xp1 = t;
#endregion
#region Rounds 32-47
// Round 32
x3 = RotateLeft32(x3 + G32_47(x4, x0, x1) + _block[3] + RMD160Round32To47, 11) + x2;
x0 = RotateLeft32(x0, 10);
xp3 = RotateLeft32(xp3 + G32_47(xp4, xp0, xp1) + _block[15] + RMD160RoundPrime32To47, 9) + xp2;
xp0 = RotateLeft32(xp0, 10);
// Round 33
x2 = RotateLeft32(x2 + G32_47(x3, x4, x0) + _block[10] + RMD160Round32To47, 13) + x1;
x4 = RotateLeft32(x4, 10);
xp2 = RotateLeft32(xp2 + G32_47(xp3, xp4, xp0) + _block[5] + RMD160RoundPrime32To47, 7) + xp1;
xp4 = RotateLeft32(xp4, 10);
// Round 34
x1 = RotateLeft32(x1 + G32_47(x2, x3, x4) + _block[14] + RMD160Round32To47, 6) + x0;
x3 = RotateLeft32(x3, 10);
xp1 = RotateLeft32(xp1 + G32_47(xp2, xp3, xp4) + _block[1] + RMD160RoundPrime32To47, 15) + xp0;
xp3 = RotateLeft32(xp3, 10);
// Round 35
x0 = RotateLeft32(x0 + G32_47(x1, x2, x3) + _block[4] + RMD160Round32To47, 7) + x4;
x2 = RotateLeft32(x2, 10);
xp0 = RotateLeft32(xp0 + G32_47(xp1, xp2, xp3) + _block[3] + RMD160RoundPrime32To47, 11) + xp4;
xp2 = RotateLeft32(xp2, 10);
// Round 36
x4 = RotateLeft32(x4 + G32_47(x0, x1, x2) + _block[9] + RMD160Round32To47, 14) + x3;
x1 = RotateLeft32(x1, 10);
xp4 = RotateLeft32(xp4 + G32_47(xp0, xp1, xp2) + _block[7] + RMD160RoundPrime32To47, 8) + xp3;
xp1 = RotateLeft32(xp1, 10);
// Round 37
x3 = RotateLeft32(x3 + G32_47(x4, x0, x1) + _block[15] + RMD160Round32To47, 9) + x2;
x0 = RotateLeft32(x0, 10);
xp3 = RotateLeft32(xp3 + G32_47(xp4, xp0, xp1) + _block[14] + RMD160RoundPrime32To47, 6) + xp2;
xp0 = RotateLeft32(xp0, 10);
// Round 38
x2 = RotateLeft32(x2 + G32_47(x3, x4, x0) + _block[8] + RMD160Round32To47, 13) + x1;
x4 = RotateLeft32(x4, 10);
xp2 = RotateLeft32(xp2 + G32_47(xp3, xp4, xp0) + _block[6] + RMD160RoundPrime32To47, 6) + xp1;
xp4 = RotateLeft32(xp4, 10);
// Round 39
x1 = RotateLeft32(x1 + G32_47(x2, x3, x4) + _block[1] + RMD160Round32To47, 15) + x0;
x3 = RotateLeft32(x3, 10);
xp1 = RotateLeft32(xp1 + G32_47(xp2, xp3, xp4) + _block[9] + RMD160RoundPrime32To47, 14) + xp0;
xp3 = RotateLeft32(xp3, 10);
// Round 40
x0 = RotateLeft32(x0 + G32_47(x1, x2, x3) + _block[2] + RMD160Round32To47, 14) + x4;
x2 = RotateLeft32(x2, 10);
xp0 = RotateLeft32(xp0 + G32_47(xp1, xp2, xp3) + _block[11] + RMD160RoundPrime32To47, 12) + xp4;
xp2 = RotateLeft32(xp2, 10);
// Round 41
x4 = RotateLeft32(x4 + G32_47(x0, x1, x2) + _block[7] + RMD160Round32To47, 8) + x3;
x1 = RotateLeft32(x1, 10);
xp4 = RotateLeft32(xp4 + G32_47(xp0, xp1, xp2) + _block[8] + RMD160RoundPrime32To47, 13) + xp3;
xp1 = RotateLeft32(xp1, 10);
// Round 42
x3 = RotateLeft32(x3 + G32_47(x4, x0, x1) + _block[0] + RMD160Round32To47, 13) + x2;
x0 = RotateLeft32(x0, 10);
xp3 = RotateLeft32(xp3 + G32_47(xp4, xp0, xp1) + _block[12] + RMD160RoundPrime32To47, 5) + xp2;
xp0 = RotateLeft32(xp0, 10);
// Round 43
x2 = RotateLeft32(x2 + G32_47(x3, x4, x0) + _block[6] + RMD160Round32To47, 6) + x1;
x4 = RotateLeft32(x4, 10);
xp2 = RotateLeft32(xp2 + G32_47(xp3, xp4, xp0) + _block[2] + RMD160RoundPrime32To47, 14) + xp1;
xp4 = RotateLeft32(xp4, 10);
// Round 44
x1 = RotateLeft32(x1 + G32_47(x2, x3, x4) + _block[13] + RMD160Round32To47, 5) + x0;
x3 = RotateLeft32(x3, 10);
xp1 = RotateLeft32(xp1 + G32_47(xp2, xp3, xp4) + _block[10] + RMD160RoundPrime32To47, 13) + xp0;
xp3 = RotateLeft32(xp3, 10);
// Round 45
x0 = RotateLeft32(x0 + G32_47(x1, x2, x3) + _block[11] + RMD160Round32To47, 12) + x4;
x2 = RotateLeft32(x2, 10);
xp0 = RotateLeft32(xp0 + G32_47(xp1, xp2, xp3) + _block[0] + RMD160RoundPrime32To47, 13) + xp4;
xp2 = RotateLeft32(xp2, 10);
// Round 46
x4 = RotateLeft32(x4 + G32_47(x0, x1, x2) + _block[5] + RMD160Round32To47, 7) + x3;
x1 = RotateLeft32(x1, 10);
xp4 = RotateLeft32(xp4 + G32_47(xp0, xp1, xp2) + _block[4] + RMD160RoundPrime32To47, 7) + xp3;
xp1 = RotateLeft32(xp1, 10);
// Round 47
x3 = RotateLeft32(x3 + G32_47(x4, x0, x1) + _block[12] + RMD160Round32To47, 5) + x2;
x0 = RotateLeft32(x0, 10);
xp3 = RotateLeft32(xp3 + G32_47(xp4, xp0, xp1) + _block[13] + RMD160RoundPrime32To47, 5) + xp2;
xp0 = RotateLeft32(xp0, 10);
// Swap set 3
t = x2; x2 = xp2; xp2 = t;
#endregion
#region Rounds 48-63
// Round 48
x2 = RotateLeft32(x2 + G48_63(x3, x4, x0) + _block[1] + RMD160Round48To63, 11) + x1;
x4 = RotateLeft32(x4, 10);
xp2 = RotateLeft32(xp2 + G16_31(xp3, xp4, xp0) + _block[8] + RMD160RoundPrime48To63, 15) + xp1;
xp4 = RotateLeft32(xp4, 10);
// Round 49
x1 = RotateLeft32(x1 + G48_63(x2, x3, x4) + _block[9] + RMD160Round48To63, 12) + x0;
x3 = RotateLeft32(x3, 10);
xp1 = RotateLeft32(xp1 + G16_31(xp2, xp3, xp4) + _block[6] + RMD160RoundPrime48To63, 5) + xp0;
xp3 = RotateLeft32(xp3, 10);
// Round 50
x0 = RotateLeft32(x0 + G48_63(x1, x2, x3) + _block[11] + RMD160Round48To63, 14) + x4;
x2 = RotateLeft32(x2, 10);
xp0 = RotateLeft32(xp0 + G16_31(xp1, xp2, xp3) + _block[4] + RMD160RoundPrime48To63, 8) + xp4;
xp2 = RotateLeft32(xp2, 10);
// Round 51
x4 = RotateLeft32(x4 + G48_63(x0, x1, x2) + _block[10] + RMD160Round48To63, 15) + x3;
x1 = RotateLeft32(x1, 10);
xp4 = RotateLeft32(xp4 + G16_31(xp0, xp1, xp2) + _block[1] + RMD160RoundPrime48To63, 11) + xp3;
xp1 = RotateLeft32(xp1, 10);
// Round 52
x3 = RotateLeft32(x3 + G48_63(x4, x0, x1) + _block[0] + RMD160Round48To63, 14) + x2;
x0 = RotateLeft32(x0, 10);
xp3 = RotateLeft32(xp3 + G16_31(xp4, xp0, xp1) + _block[3] + RMD160RoundPrime48To63, 14) + xp2;
xp0 = RotateLeft32(xp0, 10);
// Round 53
x2 = RotateLeft32(x2 + G48_63(x3, x4, x0) + _block[8] + RMD160Round48To63, 15) + x1;
x4 = RotateLeft32(x4, 10);
xp2 = RotateLeft32(xp2 + G16_31(xp3, xp4, xp0) + _block[11] + RMD160RoundPrime48To63, 14) + xp1;
xp4 = RotateLeft32(xp4, 10);
// Round 54
x1 = RotateLeft32(x1 + G48_63(x2, x3, x4) + _block[12] + RMD160Round48To63, 9) + x0;
x3 = RotateLeft32(x3, 10);
xp1 = RotateLeft32(xp1 + G16_31(xp2, xp3, xp4) + _block[15] + RMD160RoundPrime48To63, 6) + xp0;
xp3 = RotateLeft32(xp3, 10);
// Round 55
x0 = RotateLeft32(x0 + G48_63(x1, x2, x3) + _block[4] + RMD160Round48To63, 8) + x4;
x2 = RotateLeft32(x2, 10);
xp0 = RotateLeft32(xp0 + G16_31(xp1, xp2, xp3) + _block[0] + RMD160RoundPrime48To63, 14) + xp4;
xp2 = RotateLeft32(xp2, 10);
// Round 56
x4 = RotateLeft32(x4 + G48_63(x0, x1, x2) + _block[13] + RMD160Round48To63, 9) + x3;
x1 = RotateLeft32(x1, 10);
xp4 = RotateLeft32(xp4 + G16_31(xp0, xp1, xp2) + _block[5] + RMD160RoundPrime48To63, 6) + xp3;
xp1 = RotateLeft32(xp1, 10);
// Round 57
x3 = RotateLeft32(x3 + G48_63(x4, x0, x1) + _block[3] + RMD160Round48To63, 14) + x2;
x0 = RotateLeft32(x0, 10);
xp3 = RotateLeft32(xp3 + G16_31(xp4, xp0, xp1) + _block[12] + RMD160RoundPrime48To63, 9) + xp2;
xp0 = RotateLeft32(xp0, 10);
// Round 58
x2 = RotateLeft32(x2 + G48_63(x3, x4, x0) + _block[7] + RMD160Round48To63, 5) + x1;
x4 = RotateLeft32(x4, 10);
xp2 = RotateLeft32(xp2 + G16_31(xp3, xp4, xp0) + _block[2] + RMD160RoundPrime48To63, 12) + xp1;
xp4 = RotateLeft32(xp4, 10);
// Round 59
x1 = RotateLeft32(x1 + G48_63(x2, x3, x4) + _block[15] + RMD160Round48To63, 6) + x0;
x3 = RotateLeft32(x3, 10);
xp1 = RotateLeft32(xp1 + G16_31(xp2, xp3, xp4) + _block[13] + RMD160RoundPrime48To63, 9) + xp0;
xp3 = RotateLeft32(xp3, 10);
// Round 60
x0 = RotateLeft32(x0 + G48_63(x1, x2, x3) + _block[14] + RMD160Round48To63, 8) + x4;
x2 = RotateLeft32(x2, 10);
xp0 = RotateLeft32(xp0 + G16_31(xp1, xp2, xp3) + _block[9] + RMD160RoundPrime48To63, 12) + xp4;
xp2 = RotateLeft32(xp2, 10);
// Round 61
x4 = RotateLeft32(x4 + G48_63(x0, x1, x2) + _block[5] + RMD160Round48To63, 6) + x3;
x1 = RotateLeft32(x1, 10);
xp4 = RotateLeft32(xp4 + G16_31(xp0, xp1, xp2) + _block[7] + RMD160RoundPrime48To63, 5) + xp3;
xp1 = RotateLeft32(xp1, 10);
// Round 62
x3 = RotateLeft32(x3 + G48_63(x4, x0, x1) + _block[6] + RMD160Round48To63, 5) + x2;
x0 = RotateLeft32(x0, 10);
xp3 = RotateLeft32(xp3 + G16_31(xp4, xp0, xp1) + _block[10] + RMD160RoundPrime48To63, 15) + xp2;
xp0 = RotateLeft32(xp0, 10);
// Round 63
x2 = RotateLeft32(x2 + G48_63(x3, x4, x0) + _block[2] + RMD160Round48To63, 12) + x1;
x4 = RotateLeft32(x4, 10);
xp2 = RotateLeft32(xp2 + G16_31(xp3, xp4, xp0) + _block[14] + RMD160RoundPrime48To63, 8) + xp1;
xp4 = RotateLeft32(xp4, 10);
// Swap set 4
t = x3; x3 = xp3; xp3 = t;
#endregion
#region Rounds 64-79
// Round 64
x1 = RotateLeft32(x1 + G64_79(x2, x3, x4) + _block[4] + RMD160Round64To79, 9) + x0;
x3 = RotateLeft32(x3, 10);
xp1 = RotateLeft32(xp1 + G00_15(xp2, xp3, xp4) + _block[12] + RMD160RoundPrime64To79, 8) + xp0;
xp3 = RotateLeft32(xp3, 10);
// Round 65
x0 = RotateLeft32(x0 + G64_79(x1, x2, x3) + _block[0] + RMD160Round64To79, 15) + x4;
x2 = RotateLeft32(x2, 10);
xp0 = RotateLeft32(xp0 + G00_15(xp1, xp2, xp3) + _block[15] + RMD160RoundPrime64To79, 5) + xp4;
xp2 = RotateLeft32(xp2, 10);
// Round 66
x4 = RotateLeft32(x4 + G64_79(x0, x1, x2) + _block[5] + RMD160Round64To79, 5) + x3;
x1 = RotateLeft32(x1, 10);
xp4 = RotateLeft32(xp4 + G00_15(xp0, xp1, xp2) + _block[10] + RMD160RoundPrime64To79, 12) + xp3;
xp1 = RotateLeft32(xp1, 10);
// Round 67
x3 = RotateLeft32(x3 + G64_79(x4, x0, x1) + _block[9] + RMD160Round64To79, 11) + x2;
x0 = RotateLeft32(x0, 10);
xp3 = RotateLeft32(xp3 + G00_15(xp4, xp0, xp1) + _block[4] + RMD160RoundPrime64To79, 9) + xp2;
xp0 = RotateLeft32(xp0, 10);
// Round 68
x2 = RotateLeft32(x2 + G64_79(x3, x4, x0) + _block[7] + RMD160Round64To79, 6) + x1;
x4 = RotateLeft32(x4, 10);
xp2 = RotateLeft32(xp2 + G00_15(xp3, xp4, xp0) + _block[1] + RMD160RoundPrime64To79, 12) + xp1;
xp4 = RotateLeft32(xp4, 10);
// Round 69
x1 = RotateLeft32(x1 + G64_79(x2, x3, x4) + _block[12] + RMD160Round64To79, 8) + x0;
x3 = RotateLeft32(x3, 10);
xp1 = RotateLeft32(xp1 + G00_15(xp2, xp3, xp4) + _block[5] + RMD160RoundPrime64To79, 5) + xp0;
xp3 = RotateLeft32(xp3, 10);
// Round 70
x0 = RotateLeft32(x0 + G64_79(x1, x2, x3) + _block[2] + RMD160Round64To79, 13) + x4;
x2 = RotateLeft32(x2, 10);
xp0 = RotateLeft32(xp0 + G00_15(xp1, xp2, xp3) + _block[8] + RMD160RoundPrime64To79, 14) + xp4;
xp2 = RotateLeft32(xp2, 10);
// Round 71
x4 = RotateLeft32(x4 + G64_79(x0, x1, x2) + _block[10] + RMD160Round64To79, 12) + x3;
x1 = RotateLeft32(x1, 10);
xp4 = RotateLeft32(xp4 + G00_15(xp0, xp1, xp2) + _block[7] + RMD160RoundPrime64To79, 6) + xp3;
xp1 = RotateLeft32(xp1, 10);
// Round 72
x3 = RotateLeft32(x3 + G64_79(x4, x0, x1) + _block[14] + RMD160Round64To79, 5) + x2;
x0 = RotateLeft32(x0, 10);
xp3 = RotateLeft32(xp3 + G00_15(xp4, xp0, xp1) + _block[6] + RMD160RoundPrime64To79, 8) + xp2;
xp0 = RotateLeft32(xp0, 10);
// Round 73
x2 = RotateLeft32(x2 + G64_79(x3, x4, x0) + _block[1] + RMD160Round64To79, 12) + x1;
x4 = RotateLeft32(x4, 10);
xp2 = RotateLeft32(xp2 + G00_15(xp3, xp4, xp0) + _block[2] + RMD160RoundPrime64To79, 13) + xp1;
xp4 = RotateLeft32(xp4, 10);
// Round 74
x1 = RotateLeft32(x1 + G64_79(x2, x3, x4) + _block[3] + RMD160Round64To79, 13) + x0;
x3 = RotateLeft32(x3, 10);
xp1 = RotateLeft32(xp1 + G00_15(xp2, xp3, xp4) + _block[13] + RMD160RoundPrime64To79, 6) + xp0;
xp3 = RotateLeft32(xp3, 10);
// Round 75
x0 = RotateLeft32(x0 + G64_79(x1, x2, x3) + _block[8] + RMD160Round64To79, 14) + x4;
x2 = RotateLeft32(x2, 10);
xp0 = RotateLeft32(xp0 + G00_15(xp1, xp2, xp3) + _block[14] + RMD160RoundPrime64To79, 5) + xp4;
xp2 = RotateLeft32(xp2, 10);
// Round 76
x4 = RotateLeft32(x4 + G64_79(x0, x1, x2) + _block[11] + RMD160Round64To79, 11) + x3;
x1 = RotateLeft32(x1, 10);
xp4 = RotateLeft32(xp4 + G00_15(xp0, xp1, xp2) + _block[0] + RMD160RoundPrime64To79, 15) + xp3;
xp1 = RotateLeft32(xp1, 10);
// Round 77
x3 = RotateLeft32(x3 + G64_79(x4, x0, x1) + _block[6] + RMD160Round64To79, 8) + x2;
x0 = RotateLeft32(x0, 10);
xp3 = RotateLeft32(xp3 + G00_15(xp4, xp0, xp1) + _block[3] + RMD160RoundPrime64To79, 13) + xp2;
xp0 = RotateLeft32(xp0, 10);
// Round 78
x2 = RotateLeft32(x2 + G64_79(x3, x4, x0) + _block[15] + RMD160Round64To79, 5) + x1;
x4 = RotateLeft32(x4, 10);
xp2 = RotateLeft32(xp2 + G00_15(xp3, xp4, xp0) + _block[9] + RMD160RoundPrime64To79, 11) + xp1;
xp4 = RotateLeft32(xp4, 10);
// Round 79
x1 = RotateLeft32(x1 + G64_79(x2, x3, x4) + _block[13] + RMD160Round64To79, 6) + x0;
x3 = RotateLeft32(x3, 10);
xp1 = RotateLeft32(xp1 + G00_15(xp2, xp3, xp4) + _block[11] + RMD160RoundPrime64To79, 11) + xp0;
xp3 = RotateLeft32(xp3, 10);
// Swap set 5
t = x4; x4 = xp4; xp4 = t;
#endregion
// Avalanche values
_state[0] += x0;
_state[1] += x1;
_state[2] += x2;
_state[3] += x3;
_state[4] += x4;
_state[5] += xp0;
_state[6] += xp1;
_state[7] += xp2;
_state[8] += xp3;
_state[9] += xp4;
}
/// <summary>
/// Round operation [0, 15]
/// </summary>
private static uint G00_15(uint x, uint y, uint z) => x ^ y ^ z;
/// <summary>
/// Round operation [16, 31]
/// </summary>
private static uint G16_31(uint x, uint y, uint z) => (x & y) | (~x & z);
/// <summary>
/// Round operation [32, 47]
/// </summary>
private static uint G32_47(uint x, uint y, uint z) => (x | ~y) ^ z;
/// <summary>
/// Round operation [48, 63]
/// </summary>
private static uint G48_63(uint x, uint y, uint z) => (x & z) | (y & ~z);
/// <summary>
/// Round operation [64, 79]
/// </summary>
private static uint G64_79(uint x, uint y, uint z) => x ^ (y | ~z);
}
}

View File

@@ -0,0 +1,28 @@
using System;
namespace SabreTools.Hashing.CryptographicHash
{
/// <summary>
/// 3-pass variant of Tiger-128
/// </summary>
public class Tiger128_3 : TigerHashBase
{
/// <inheritdoc/>
public override int HashSize => 128;
public Tiger128_3() : base()
{
_passes = 3;
_padStart = 0x01;
}
/// <inheritdoc/>
protected override byte[] HashFinal()
{
byte[] hash = base.HashFinal();
byte[] trimmedHash = new byte[16];
Array.Copy(hash, trimmedHash, 16);
return trimmedHash;
}
}
}

View File

@@ -0,0 +1,28 @@
using System;
namespace SabreTools.Hashing.CryptographicHash
{
/// <summary>
/// 4-pass variant of Tiger-128
/// </summary>
public class Tiger128_4 : TigerHashBase
{
/// <inheritdoc/>
public override int HashSize => 128;
public Tiger128_4() : base()
{
_passes = 4;
_padStart = 0x01;
}
/// <inheritdoc/>
protected override byte[] HashFinal()
{
byte[] hash = base.HashFinal();
byte[] trimmedHash = new byte[16];
Array.Copy(hash, trimmedHash, 16);
return trimmedHash;
}
}
}

View File

@@ -0,0 +1,28 @@
using System;
namespace SabreTools.Hashing.CryptographicHash
{
/// <summary>
/// 3-pass variant of Tiger-160
/// </summary>
public class Tiger160_3 : TigerHashBase
{
/// <inheritdoc/>
public override int HashSize => 160;
public Tiger160_3() : base()
{
_passes = 3;
_padStart = 0x01;
}
/// <inheritdoc/>
protected override byte[] HashFinal()
{
byte[] hash = base.HashFinal();
byte[] trimmedHash = new byte[20];
Array.Copy(hash, trimmedHash, 20);
return trimmedHash;
}
}
}

View File

@@ -0,0 +1,28 @@
using System;
namespace SabreTools.Hashing.CryptographicHash
{
/// <summary>
/// 4-pass variant of Tiger-160
/// </summary>
public class Tiger160_4 : TigerHashBase
{
/// <inheritdoc/>
public override int HashSize => 160;
public Tiger160_4() : base()
{
_passes = 4;
_padStart = 0x01;
}
/// <inheritdoc/>
protected override byte[] HashFinal()
{
byte[] hash = base.HashFinal();
byte[] trimmedHash = new byte[20];
Array.Copy(hash, trimmedHash, 20);
return trimmedHash;
}
}
}

View File

@@ -0,0 +1,17 @@
namespace SabreTools.Hashing.CryptographicHash
{
/// <summary>
/// 3-pass variant of Tiger-192
/// </summary>
public class Tiger192_3 : TigerHashBase
{
/// <inheritdoc/>
public override int HashSize => 192;
public Tiger192_3() : base()
{
_passes = 3;
_padStart = 0x01;
}
}
}

View File

@@ -0,0 +1,17 @@
namespace SabreTools.Hashing.CryptographicHash
{
/// <summary>
/// 4-pass variant of Tiger-192
/// </summary>
public class Tiger192_4 : TigerHashBase
{
/// <inheritdoc/>
public override int HashSize => 192;
public Tiger192_4() : base()
{
_passes = 4;
_padStart = 0x01;
}
}
}

View File

@@ -0,0 +1,28 @@
using System;
namespace SabreTools.Hashing.CryptographicHash
{
/// <summary>
/// 3-pass variant of Tiger2-128
/// </summary>
public class Tiger2_128_3 : TigerHashBase
{
/// <inheritdoc/>
public override int HashSize => 128;
public Tiger2_128_3() : base()
{
_passes = 3;
_padStart = 0x80;
}
/// <inheritdoc/>
protected override byte[] HashFinal()
{
byte[] hash = base.HashFinal();
byte[] trimmedHash = new byte[16];
Array.Copy(hash, trimmedHash, 16);
return trimmedHash;
}
}
}

View File

@@ -0,0 +1,28 @@
using System;
namespace SabreTools.Hashing.CryptographicHash
{
/// <summary>
/// 4-pass variant of Tiger2-128
/// </summary>
public class Tiger2_128_4 : TigerHashBase
{
/// <inheritdoc/>
public override int HashSize => 128;
public Tiger2_128_4() : base()
{
_passes = 4;
_padStart = 0x80;
}
/// <inheritdoc/>
protected override byte[] HashFinal()
{
byte[] hash = base.HashFinal();
byte[] trimmedHash = new byte[16];
Array.Copy(hash, trimmedHash, 16);
return trimmedHash;
}
}
}

View File

@@ -0,0 +1,28 @@
using System;
namespace SabreTools.Hashing.CryptographicHash
{
/// <summary>
/// 3-pass variant of Tiger2-160
/// </summary>
public class Tiger2_160_3 : TigerHashBase
{
/// <inheritdoc/>
public override int HashSize => 160;
public Tiger2_160_3() : base()
{
_passes = 3;
_padStart = 0x80;
}
/// <inheritdoc/>
protected override byte[] HashFinal()
{
byte[] hash = base.HashFinal();
byte[] trimmedHash = new byte[20];
Array.Copy(hash, trimmedHash, 20);
return trimmedHash;
}
}
}

View File

@@ -0,0 +1,28 @@
using System;
namespace SabreTools.Hashing.CryptographicHash
{
/// <summary>
/// 4-pass variant of Tiger2-160
/// </summary>
public class Tiger2_160_4 : TigerHashBase
{
/// <inheritdoc/>
public override int HashSize => 160;
public Tiger2_160_4() : base()
{
_passes = 4;
_padStart = 0x80;
}
/// <inheritdoc/>
protected override byte[] HashFinal()
{
byte[] hash = base.HashFinal();
byte[] trimmedHash = new byte[20];
Array.Copy(hash, trimmedHash, 20);
return trimmedHash;
}
}
}

View File

@@ -0,0 +1,17 @@
namespace SabreTools.Hashing.CryptographicHash
{
/// <summary>
/// 3-pass variant of Tiger2-192
/// </summary>
public class Tiger2_192_3 : TigerHashBase
{
/// <inheritdoc/>
public override int HashSize => 192;
public Tiger2_192_3() : base()
{
_passes = 3;
_padStart = 0x80;
}
}
}

View File

@@ -0,0 +1,17 @@
namespace SabreTools.Hashing.CryptographicHash
{
/// <summary>
/// 4-pass variant of Tiger2-192
/// </summary>
public class Tiger2_192_4 : TigerHashBase
{
/// <inheritdoc/>
public override int HashSize => 192;
public Tiger2_192_4() : base()
{
_passes = 4;
_padStart = 0x80;
}
}
}

View File

@@ -0,0 +1,237 @@
using System;
using static SabreTools.Hashing.CryptographicHash.Constants;
using static SabreTools.Hashing.HashOperations;
namespace SabreTools.Hashing.CryptographicHash
{
/// <see href="https://biham.cs.technion.ac.il/Reports/Tiger//>
public abstract class TigerHashBase : MessageDigestBase<ulong>
{
/// <summary>
/// Number of passes (minimum 3)
/// </summary>
protected int _passes;
/// <summary>
/// Byte to start padding with
/// </summary>
protected byte _padStart;
/// <summary>
/// Set of 3 64-bit numbers representing the hash state
/// </summary>
private readonly ulong[] _state = new ulong[3];
public TigerHashBase() : base()
{
}
/// <inheritdoc/>
protected override void ResetImpl()
{
_state[0] = TigerSeedA;
_state[1] = TigerSeedB;
_state[2] = TigerSeedC;
}
/// <inheritdoc/>
protected override void HashCore(byte[] data, int offset, int length)
{
// Figure out how much buffer is needed
int bufferLen = (int)(_totalBytes & 0x3f);
// Increment the processed byte count
_totalBytes += length;
// If there is buffer to fill and it will meet the limit
if (bufferLen > 0 && bufferLen + length >= 64)
{
// Fill the buffer from the input
Array.Copy(data, offset, _buffer, bufferLen, 64 - bufferLen);
// Set the new values
offset += 64 - bufferLen;
length -= 64 - bufferLen;
// Split the buffer for the round
for (int i = 0; i < 8; i++)
{
_block[i] = ReadLE64(_buffer, i * 8);
}
// Run the round
Compress();
bufferLen = 0;
}
/// Process any standalone blocks
while (length >= 64)
{
// Fill the buffer from the input
Array.Copy(data, offset, _buffer, 0, 64);
// Set the new values
offset += 64;
length -= 64;
// Split the buffer for the round
for (int i = 0; i < 8; i++)
{
_block[i] = ReadLE64(_buffer, i * 8);
}
// Run the round
Compress();
}
// Save the remainder in the buffer
if (length > 0)
Array.Copy(data, offset, _buffer, bufferLen, length);
}
/// <inheritdoc/>
protected override byte[] HashFinal()
{
// Determine the pad length
int padLength = 64 - (int)(_totalBytes & 0x3f);
if (padLength <= 8)
padLength += 64;
// Get the total byte count in bits
long totalBitCount = _totalBytes * 8;
// Prebuild the padding
var padding = new byte[padLength];
padding[0] = _padStart;
padding[padLength - 1] = (byte)((totalBitCount >> 56) & 0xff);
padding[padLength - 2] = (byte)((totalBitCount >> 48) & 0xff);
padding[padLength - 3] = (byte)((totalBitCount >> 40) & 0xff);
padding[padLength - 4] = (byte)((totalBitCount >> 32) & 0xff);
padding[padLength - 5] = (byte)((totalBitCount >> 24) & 0xff);
padding[padLength - 6] = (byte)((totalBitCount >> 16) & 0xff);
padding[padLength - 7] = (byte)((totalBitCount >> 8) & 0xff);
padding[padLength - 8] = (byte)((totalBitCount >> 0) & 0xff);
// Pad the block
HashCore(padding, 0, padding.Length);
// Get the hash
var hash = new byte[24];
int hashOffset = 0;
// Assemble the hash array
for (int i = 0; i < _state.Length; i++)
{
byte[] segment = BitConverter.GetBytes(_state[i]);
Array.Copy(segment, 0, hash, hashOffset, 8);
hashOffset += 8;
}
return hash;
}
/// <summary>
/// Perform one round of updates on the cached values
/// </summary>
private void Compress()
{
// Save current values [save_abc]
ulong aa = _state[0];
ulong bb = _state[1];
ulong cc = _state[2];
// Pass 1 [pass(a, b, c, 5)]
Pass(ref _state[0], ref _state[1], ref _state[2], 5);
// Avalanche [key_schedule]
KeySchedule();
// Pass 2 [pass(c, a, b, 7)]
Pass(ref _state[2], ref _state[0], ref _state[1], 7);
// Avalanche [key_schedule]
KeySchedule();
// Pass 3 [pass(b, c, a, 9)]
Pass(ref _state[1], ref _state[2], ref _state[0], 9);
// Perform correct set of extra passes
for (int pass_no = 3; pass_no < _passes; pass_no++)
{
// Avalanche [key_schedule]
KeySchedule();
// Pass N [pass(a, b, c, 9)]
Pass(ref _state[0], ref _state[1], ref _state[2], 9);
// Rotate
ulong tmpa = _state[0];
_state[0] = _state[2];
_state[2] = _state[1];
_state[1] = tmpa;
}
// Update stored values [feedforward]
_state[0] ^= aa;
_state[1] -= bb;
_state[2] += cc;
}
/// <summary>
/// pass(a,b,c,mul)
/// </summary>
private void Pass(ref ulong a, ref ulong b, ref ulong c, int mul)
{
Round(ref a, ref b, ref c, _block[0], mul);
Round(ref b, ref c, ref a, _block[1], mul);
Round(ref c, ref a, ref b, _block[2], mul);
Round(ref a, ref b, ref c, _block[3], mul);
Round(ref b, ref c, ref a, _block[4], mul);
Round(ref c, ref a, ref b, _block[5], mul);
Round(ref a, ref b, ref c, _block[6], mul);
Round(ref b, ref c, ref a, _block[7], mul);
}
/// <summary>
/// round(a,b,c,x,mul)
/// </summary>
private static void Round(ref ulong a, ref ulong b, ref ulong c, ulong x, int mul)
{
c ^= x;
a -= TigerSBox[((c >> (0 * 8)) & 0xFF) + (0 * 256)]
^ TigerSBox[((c >> (2 * 8)) & 0xFF) + (1 * 256)]
^ TigerSBox[((c >> (4 * 8)) & 0xFF) + (2 * 256)]
^ TigerSBox[((c >> (6 * 8)) & 0xFF) + (3 * 256)];
b += TigerSBox[((c >> (1 * 8)) & 0xFF) + (3 * 256)]
^ TigerSBox[((c >> (3 * 8)) & 0xFF) + (2 * 256)]
^ TigerSBox[((c >> (5 * 8)) & 0xFF) + (1 * 256)]
^ TigerSBox[((c >> (7 * 8)) & 0xFF) + (0 * 256)];
unchecked { b *= (ulong)mul; }
}
/// <summary>
/// key_schedule
/// </summary>
private void KeySchedule()
{
_block[0] -= _block[7] ^ 0xA5A5A5A5A5A5A5A5;
_block[1] ^= _block[0];
_block[2] += _block[1];
_block[3] -= _block[2] ^ ((~_block[1]) << 19);
_block[4] ^= _block[3];
_block[5] += _block[4];
_block[6] -= _block[5] ^ ((~_block[4]) >> 23);
_block[7] ^= _block[6];
_block[0] += _block[7];
_block[1] -= _block[0] ^ ((~_block[7]) << 19);
_block[2] ^= _block[1];
_block[3] += _block[2];
_block[4] -= _block[3] ^ ((~_block[2]) >> 23);
_block[5] ^= _block[4];
_block[6] += _block[5];
_block[7] -= _block[6] ^ 0x0123456789ABCDEF;
}
}
}

View File

@@ -0,0 +1,9 @@
#if NET20
namespace System.Runtime.CompilerServices
{
[AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Method)]
internal sealed class ExtensionAttribute : Attribute {}
}
#endif

View File

@@ -0,0 +1,447 @@
namespace SabreTools.Hashing
{
public static class Extensions
{
/// <summary>
/// Get the name of a given hash type, if possible
/// </summary>
/// TODO: This should be automated instead of hardcoded
public static string? GetHashName(this HashType hashType)
{
return hashType switch
{
HashType.Adler32 => "Mark Adler's 32-bit checksum",
#if NET7_0_OR_GREATER
HashType.BLAKE3 => "BLAKE3 512-bit digest",
#endif
HashType.CRC1_ZERO => "CRC-1/ZERO [Parity bit with 0 start]",
HashType.CRC1_ONE => "CRC-1/ONE [Parity bit with 1 start]",
HashType.CRC3_GSM => "CRC-3/GSM",
HashType.CRC3_ROHC => "CRC-3/ROHC",
HashType.CRC4_G704 => "CRC-4/G-704 [CRC-4/ITU]",
HashType.CRC4_INTERLAKEN => "CRC-4/INTERLAKEN",
HashType.CRC5_EPCC1G2 => "CRC-5/EPC-C1G2 [CRC-5/EPC]",
HashType.CRC5_G704 => "CRC-5/G-704 [CRC-5/ITU]",
HashType.CRC5_USB => "CRC-5/USB",
HashType.CRC6_CDMA2000A => "CRC-6/CDMA2000-A",
HashType.CRC6_CDMA2000B => "CRC-6/CDMA2000-B",
HashType.CRC6_DARC => "CRC-6/DARC",
HashType.CRC6_G704 => "CRC-6/G-704 [CRC-6/ITU]",
HashType.CRC6_GSM => "CRC-6/GSM",
HashType.CRC7_MMC => "CRC-7/MMC [CRC-7]",
HashType.CRC7_ROHC => "CRC-7/ROHC",
HashType.CRC7_UMTS => "CRC-7/UMTS",
HashType.CRC8 => "CRC-8",
HashType.CRC8_AUTOSAR => "CRC-8/AUTOSAR",
HashType.CRC8_BLUETOOTH => "CRC-8/BLUETOOTH",
HashType.CRC8_CDMA2000 => "CRC-8/CDMA2000",
HashType.CRC8_DARC => "CRC-8/DARC",
HashType.CRC8_DVBS2 => "CRC-8/DVB-S2",
HashType.CRC8_GSMA => "CRC-8/GSM-A",
HashType.CRC8_GSMB => "CRC-8/GSM-B",
HashType.CRC8_HITAG => "CRC-8/HITAG",
HashType.CRC8_I4321 => "CRC-8/I-432-1 [CRC-8/ITU]",
HashType.CRC8_ICODE => "CRC-8/I-CODE",
HashType.CRC8_LTE => "CRC-8/LTE",
HashType.CRC8_MAXIMDOW => "CRC-8/MAXIM-DOW [CRC-8/MAXIM, DOW-CRC]",
HashType.CRC8_MIFAREMAD => "CRC-8/MIFARE-MAD",
HashType.CRC8_NRSC5 => "CRC-8/NRSC-5",
HashType.CRC8_OPENSAFETY => "CRC-8/OPENSAFETY",
HashType.CRC8_ROHC => "CRC-8/ROHC",
HashType.CRC8_SAEJ1850 => "CRC-8/SAE-J1850",
HashType.CRC8_SMBUS => "CRC-8/SMBUS [CRC-8]",
HashType.CRC8_TECH3250 => "CRC-8/TECH-3250 [CRC-8/AES, CRC-8/EBU]",
HashType.CRC8_WCDMA => "CRC-8/WCDMA",
HashType.CRC10_ATM => "CRC-10/ATM [CRC-10, CRC-10/I-610]",
HashType.CRC10_CDMA2000 => "CRC-10/CDMA2000",
HashType.CRC10_GSM => "CRC-10/GSM",
HashType.CRC11_FLEXRAY => "CRC-11/FLEXRAY [CRC-11]",
HashType.CRC11_UMTS => "CRC-11/UMTS",
HashType.CRC12_CDMA2000 => "CRC-12/CDMA2000",
HashType.CRC12_DECT => "CRC-12/DECT [X-CRC-12]",
HashType.CRC12_GSM => "CRC-12/GSM",
HashType.CRC12_UMTS => "CRC-12/UMTS [CRC-12/3GPP]",
HashType.CRC13_BBC => "CRC-13/BBC",
HashType.CRC14_DARC => "CRC-14/DARC",
HashType.CRC14_GSM => "CRC-14/GSM",
HashType.CRC15_CAN => "CRC-15/CAN [CRC-15]",
HashType.CRC15_MPT1327 => "CRC-15/MPT1327",
HashType.CRC16 => "CRC-16",
HashType.CRC16_ARC => "CRC-16/ARC [ARC, CRC-16, CRC-16/LHA, CRC-IBM]",
HashType.CRC16_CDMA2000 => "CRC-16/CDMA2000",
HashType.CRC16_CMS => "CRC-16/CMS",
HashType.CRC16_DDS110 => "CRC-16/DDS-110",
HashType.CRC16_DECTR => "CRC-16/DECT-R [R-CRC-16]",
HashType.CRC16_DECTX => "CRC-16/DECT-X [X-CRC-16]",
HashType.CRC16_DNP => "CRC-16/DNP",
HashType.CRC16_EN13757 => "CRC-16/EN-13757",
HashType.CRC16_GENIBUS => "CRC-16/GENIBUS [CRC-16/DARC, CRC-16/EPC, CRC-16/EPC-C1G2, CRC-16/I-CODE]",
HashType.CRC16_GSM => "CRC-16/GSM",
HashType.CRC16_IBM3740 => "CRC-16/IBM-3740 [CRC-16/AUTOSAR, CRC-16/CCITT-FALSE]",
HashType.CRC16_IBMSDLC => "CRC-16/IBM-SDLC [CRC-16/ISO-HDLC, CRC-16/ISO-IEC-14443-3-B, CRC-16/X-25, CRC-B, X-25]",
HashType.CRC16_ISOIEC144433A => "CRC-16/ISO-IEC-14443-3-A [CRC-A]",
HashType.CRC16_KERMIT => "CRC-16/KERMIT [CRC-16/BLUETOOTH, CRC-16/CCITT, CRC-16/CCITT-TRUE, CRC-16/V-41-LSB, CRC-CCITT, KERMIT]",
HashType.CRC16_LJ1200 => "CRC-16/LJ1200",
HashType.CRC16_M17 => "CRC-16/M17",
HashType.CRC16_MAXIMDOW => "CRC-16/MAXIM-DOW [CRC-16/MAXIM]",
HashType.CRC16_MCRF4XX => "CRC-16/MCRF4XX",
HashType.CRC16_MODBUS => "CRC-16/MODBUS [MODBUS]",
HashType.CRC16_NRSC5 => "CRC-16/NRSC-5",
HashType.CRC16_OPENSAFETYA => "CRC-16/OPENSAFETY-A",
HashType.CRC16_OPENSAFETYB => "CRC-16/OPENSAFETY-B",
HashType.CRC16_PROFIBUS => "CRC-16/PROFIBUS [CRC-16/IEC-61158-2]",
HashType.CRC16_RIELLO => "CRC-16/RIELLO",
HashType.CRC16_SPIFUJITSU => "CRC-16/SPI-FUJITSU [CRC-16/AUG-CCITT]",
HashType.CRC16_T10DIF => "CRC-16/T10-DIF",
HashType.CRC16_TELEDISK => "CRC-16/TELEDISK",
HashType.CRC16_TMS37157 => "CRC-16/TMS37157",
HashType.CRC16_UMTS => "CRC-16/UMTS [CRC-16/BUYPASS, CRC-16/VERIFONE]",
HashType.CRC16_USB => "CRC-16/USB",
HashType.CRC16_XMODEM => "CRC-16/XMODEM [CRC-16/ACORN, CRC-16/LTE, CRC-16/V-41-MSB, XMODEM, ZMODEM]",
HashType.CRC17_CANFD => "CRC-17/CAN-FD",
HashType.CRC21_CANFD => "CRC-21/CAN-FD",
HashType.CRC24_BLE => "CRC-24/BLE",
HashType.CRC24_FLEXRAYA => "CRC-24/FLEXRAY-A",
HashType.CRC24_FLEXRAYB => "CRC-24/FLEXRAY-B",
HashType.CRC24_INTERLAKEN => "CRC-24/INTERLAKEN",
HashType.CRC24_LTEA => "CRC-24/LTE-A",
HashType.CRC24_LTEB => "CRC-24/LTE-B",
HashType.CRC24_OPENPGP => "CRC-24/OPENPGP",
HashType.CRC24_OS9 => "CRC-24/OS-9",
HashType.CRC30_CDMA => "CRC-30/CDMA",
HashType.CRC31_PHILIPS => "CRC-31/PHILIPS",
HashType.CRC32 => "CRC-32",
HashType.CRC32_AIXM => "CRC-32/AIXM",
HashType.CRC32_AUTOSAR => "CRC-32/AUTOSAR",
HashType.CRC32_BASE91D => "CRC-32/BASE91-D",
HashType.CRC32_BZIP2 => "BZIP2",
HashType.CRC32_CDROMEDC => "CRC-32/CD-ROM-EDC",
HashType.CRC32_CKSUM => "CRC-32/CKSUM",
HashType.CRC32_DVDROMEDC => "CRC-32/DVD-ROM-EDC",
HashType.CRC32_ISCSI => "CRC-32/ISCSI",
HashType.CRC32_ISOHDLC => "CRC-32/ISO-HDLC",
HashType.CRC32_JAMCRC => "CRC-32/JAMCRC",
HashType.CRC32_MEF => "CRC-32/MEF",
HashType.CRC32_MPEG2 => "CRC-32/MPEG-2",
HashType.CRC32_XFER => "CRC-32/XFER",
HashType.CRC40_GSM => "CRC-40/GSM",
HashType.CRC64 => "CRC-64",
HashType.CRC64_ECMA182 => "CRC-64/ECMA-182, Microsoft implementation",
HashType.CRC64_GOISO => "CRC-64/GO-ISO",
HashType.CRC64_MS => "CRC-64/MS",
HashType.CRC64_NVME => "CRC-64/NVME",
HashType.CRC64_REDIS => "CRC-64/REDIS",
HashType.CRC64_WE => "CRC-64/WE",
HashType.CRC64_XZ => "CRC-64/XZ",
HashType.Fletcher16 => "John G. Fletcher's 16-bit checksum",
HashType.Fletcher32 => "John G. Fletcher's 32-bit checksum",
HashType.Fletcher64 => "John G. Fletcher's 64-bit checksum",
HashType.FNV0_32 => "FNV hash (Variant 0, 32-bit)",
HashType.FNV0_64 => "FNV hash (Variant 0, 64-bit)",
HashType.FNV1_32 => "FNV hash (Variant 1, 32-bit)",
HashType.FNV1_64 => "FNV hash (Variant 1, 64-bit)",
HashType.FNV1a_32 => "FNV hash (Variant 1a, 32-bit)",
HashType.FNV1a_64 => "FNV hash (Variant 1a, 64-bit)",
HashType.MekaCrc => "Custom MEKA checksum",
HashType.MD2 => "MD2 message-digest algorithm",
HashType.MD4 => "MD4 message-digest algorithm",
HashType.MD5 => "MD5 message-digest algorithm",
HashType.RIPEMD128 => "RIPEMD-128 hash",
HashType.RIPEMD160 => "RIPEMD-160 hash",
HashType.RIPEMD256 => "RIPEMD-256 hash",
HashType.RIPEMD320 => "RIPEMD-320 hash",
HashType.SHA1 => "SHA-1 hash",
HashType.SHA256 => "SHA-256 hash",
HashType.SHA384 => "SHA-384 hash",
HashType.SHA512 => "SHA-512 hash",
#if NET8_0_OR_GREATER
HashType.SHA3_256 => "SHA3-256 hash",
HashType.SHA3_384 => "SHA3-384 hash",
HashType.SHA3_512 => "SHA3-512 hash",
HashType.SHAKE128 => "SHAKE128 SHA-3 family hash (256-bit)",
HashType.SHAKE256 => "SHAKE256 SHA-3 family hash (512-bit)",
#endif
HashType.SpamSum => "spamsum fuzzy hash",
HashType.Tiger128_3 => "Tiger 128-bit hash, 3 passes",
HashType.Tiger128_4 => "Tiger 128-bit hash, 4 passes",
HashType.Tiger160_3 => "Tiger 160-bit hash, 3 passes",
HashType.Tiger160_4 => "Tiger 160-bit hash, 4 passes",
HashType.Tiger192_3 => "Tiger 192-bit hash, 3 passes",
HashType.Tiger192_4 => "Tiger 192-bit hash, 4 passes",
HashType.Tiger2_128_3 => "Tiger2 128-bit hash, 3 passes",
HashType.Tiger2_128_4 => "Tiger2 128-bit hash, 4 passes",
HashType.Tiger2_160_3 => "Tiger2 160-bit hash, 3 passes",
HashType.Tiger2_160_4 => "Tiger2 160-bit hash, 4 passes",
HashType.Tiger2_192_3 => "Tiger2 192-bit hash, 3 passes",
HashType.Tiger2_192_4 => "Tiger2 192-bit hash, 4 passes",
HashType.XxHash32 => "xxHash32 hash",
HashType.XxHash64 => "xxHash64 hash",
#if NET462_OR_GREATER || NETCOREAPP
HashType.XxHash3 => "XXH3 64-bit hash",
HashType.XxHash128 => "XXH128 128-bit hash",
#endif
_ => $"{hashType}",
};
}
/// <summary>
/// Get the hash type associated to a string, if possible
/// </summary>
/// TODO: This should be automated instead of hardcoded
public static HashType? GetHashType(this string? str)
{
// Ignore invalid strings
if (string.IsNullOrEmpty(str))
return null;
// Normalize the string before matching
str = str!.Replace("-", string.Empty);
str = str.Replace(" ", string.Empty);
str = str.Replace("/", "_");
str = str.Replace("\\", "_");
str = str.ToLowerInvariant();
// Match based on potential names
return str switch
{
"adler" or "adler32" => HashType.Adler32,
#if NET7_0_OR_GREATER
"blake3" => HashType.BLAKE3,
#endif
"crc1_0" or "crc1_zero" => HashType.CRC1_ZERO,
"crc1_1" or "crc1_one" => HashType.CRC1_ONE,
"crc3_gsm" => HashType.CRC3_GSM,
"crc3_rohc" => HashType.CRC3_ROHC,
"crc4_g704" or "crc4_itu" => HashType.CRC4_G704,
"crc4_interlaken" => HashType.CRC4_INTERLAKEN,
"crc5_epc" or "crc5_epcc1g2" => HashType.CRC5_EPCC1G2,
"crc5_g704" or "crc5_itu" => HashType.CRC5_G704,
"crc5_usb" => HashType.CRC5_USB,
"crc6_cdma2000a" => HashType.CRC6_CDMA2000A,
"crc6_cdma2000b" => HashType.CRC6_CDMA2000B,
"crc6_darc" => HashType.CRC6_DARC,
"crc6_g704" or "crc6_itu" => HashType.CRC6_G704,
"crc6_gsm" => HashType.CRC6_GSM,
"crc7" or "crc7_mmc" => HashType.CRC7_MMC,
"crc7_rohc" => HashType.CRC7_ROHC,
"crc7_umts" => HashType.CRC7_UMTS,
"crc8" => HashType.CRC8,
"crc8_autosar" => HashType.CRC8_AUTOSAR,
"crc8_bluetooth" => HashType.CRC8_BLUETOOTH,
"crc8_cdma2000" => HashType.CRC8_CDMA2000,
"crc8_darc" => HashType.CRC8_DARC,
"crc8_dvbs2" => HashType.CRC8_DVBS2,
"crc8_gsma" => HashType.CRC8_GSMA,
"crc8_gsmb" => HashType.CRC8_GSMB,
"crc8_hitag" => HashType.CRC8_HITAG,
"crc8_i4321" or "crc8_itu" => HashType.CRC8_I4321,
"crc8_icode" => HashType.CRC8_ICODE,
"crc8_lte" => HashType.CRC8_LTE,
"crc8_maximdow" or "crc8_maxim" or "dowcrc" => HashType.CRC8_MAXIMDOW,
"crc8_mifaremad" => HashType.CRC8_MIFAREMAD,
"crc8_nrsc5" => HashType.CRC8_NRSC5,
"crc8_opensafety" => HashType.CRC8_OPENSAFETY,
"crc8_rohc" => HashType.CRC8_ROHC,
"crc8_saej1850" => HashType.CRC8_SAEJ1850,
"crc8_smbus" => HashType.CRC8_SMBUS,
"crc8_tech3250" or "crc8_aes" or "crc8_ebu" => HashType.CRC8_TECH3250,
"crc8_wcdma" => HashType.CRC8_WCDMA,
"crc10_atm" or "crc10" or "crc10_i610" => HashType.CRC10_ATM,
"crc10_cdma2000" => HashType.CRC10_CDMA2000,
"crc10_gsm" => HashType.CRC10_GSM,
"crc11_flexray" or "crc11" => HashType.CRC11_FLEXRAY,
"crc11_umts" => HashType.CRC11_UMTS,
"crc12_cdma2000" => HashType.CRC12_CDMA2000,
"crc12_dect" or "xcrc12" => HashType.CRC12_DECT,
"crc12_gsm" => HashType.CRC12_GSM,
"crc12_umts" or "crc12_3gpp" => HashType.CRC12_UMTS,
"crc13_bbc" => HashType.CRC13_BBC,
"crc14_darc" => HashType.CRC14_DARC,
"crc14_gsm" => HashType.CRC14_GSM,
"crc15_can" or "crc15" => HashType.CRC15_CAN,
"crc15_mpt1327" => HashType.CRC15_MPT1327,
"crc16" => HashType.CRC16,
"crc16_arc" or "arc" or "crc16_lha" or "crcibm" => HashType.CRC16_ARC,
"crc16_cdma2000" => HashType.CRC16_CDMA2000,
"crc16_cms" => HashType.CRC16_CMS,
"crc16_dds110" => HashType.CRC16_DDS110,
"crc16_dectr" or "rcrc16" => HashType.CRC16_DECTR,
"crc16_dectx" or "xcrc16" => HashType.CRC16_DECTX,
"crc16_dnp" => HashType.CRC16_DNP,
"crc16_en13757" => HashType.CRC16_EN13757,
"crc16_genibus" or "crc16_darc" or "crc16_epc" or "crc16_epcc1g2" or "crc16_icode" => HashType.CRC16_GENIBUS,
"crc16_gsm" => HashType.CRC16_GSM,
"crc16_ibm3740" or "crc16_autosar" or "crc16_cittfalse" => HashType.CRC16_IBM3740,
"crc16_ibmsdlc" or "crc16_isohdlc" or "crc16_isoiec144433b" or "crc16_x25" or "crcb" or "x25" => HashType.CRC16_IBMSDLC,
"crc16_isoiec144433a" or "crca" => HashType.CRC16_ISOIEC144433A,
"crc16_kermit" or "crc16_bluetooth" or "crc16_ccitt" or "crc16_ccitttrue" or "crc16_v41lsb" or "crcccitt" or "kermit" => HashType.CRC16_KERMIT,
"crc16_lj1200" => HashType.CRC16_LJ1200,
"crc16_m17" => HashType.CRC16_M17,
"crc16_maximdow" or "crc16_maxim" => HashType.CRC16_MAXIMDOW,
"crc16_mcrf4xx" => HashType.CRC16_MCRF4XX,
"crc16_modbus" or "modbus" => HashType.CRC16_MODBUS,
"crc16_nrsc5" => HashType.CRC16_NRSC5,
"crc16_opensafetya" => HashType.CRC16_OPENSAFETYA,
"crc16_opensafetyb" => HashType.CRC16_OPENSAFETYB,
"crc16_profibus" or "crc16_iec611582" => HashType.CRC16_PROFIBUS,
"crc16_riello" => HashType.CRC16_RIELLO,
"crc16_spifujitsu" or "crc16_augccitt" => HashType.CRC16_SPIFUJITSU,
"crc16_t10dif" => HashType.CRC16_T10DIF,
"crc16_teledisk" => HashType.CRC16_TELEDISK,
"crc16_tms37157" => HashType.CRC16_TMS37157,
"crc16_umts" or "crc16_buypass" or "crc16_verifone" => HashType.CRC16_UMTS,
"crc16_usb" => HashType.CRC16_USB,
"crc16_xmodem" or "crc16_acorn" or "crc16_lte" or "crc16_v41msb" or "xmodem" or "zmodem" => HashType.CRC16_XMODEM,
"crc17_canfd" => HashType.CRC17_CANFD,
"crc21_canfd" => HashType.CRC21_CANFD,
"crc24_ble" => HashType.CRC24_BLE,
"crc24_flexraya" => HashType.CRC24_FLEXRAYA,
"crc24_flexrayb" => HashType.CRC24_FLEXRAYB,
"crc24_interlaken" => HashType.CRC24_INTERLAKEN,
"crc24_ltea" => HashType.CRC24_LTEA,
"crc24_lteb" => HashType.CRC24_LTEB,
"crc24_openpgp" => HashType.CRC24_OPENPGP,
"crc24_os9" => HashType.CRC24_OS9,
"crc30_cdma" => HashType.CRC30_CDMA,
"crc31_philips" => HashType.CRC31_PHILIPS,
"crc32" => HashType.CRC32,
"crc32_aixm" => HashType.CRC32_AIXM,
"crc32_autosar" => HashType.CRC32_AUTOSAR,
"crc32_base91d" => HashType.CRC32_BASE91D,
"crc32_bzip2" => HashType.CRC32_BZIP2,
"crc32_cdromedc" => HashType.CRC32_CDROMEDC,
"crc32_cksum" => HashType.CRC32_CKSUM,
"crc32_dvdromedc" => HashType.CRC32_DVDROMEDC,
"crc32_iscsi" => HashType.CRC32_ISCSI,
"crc32_isohdlc" => HashType.CRC32_ISOHDLC,
"crc32_jamcrc" => HashType.CRC32_JAMCRC,
"crc32_mef" => HashType.CRC32_MEF,
"crc32_mpeg2" => HashType.CRC32_MPEG2,
"crc32_xfer" => HashType.CRC32_XFER,
"crc40_gsm" => HashType.CRC40_GSM,
"crc64" => HashType.CRC64,
"crc64_ecma182" => HashType.CRC64_ECMA182,
"crc64_goiso" => HashType.CRC64_GOISO,
"crc64_ms" => HashType.CRC64_MS,
"crc64_nvme" => HashType.CRC64_NVME,
"crc64_redis" => HashType.CRC64_REDIS,
"crc64_we" => HashType.CRC64_WE,
"crc64_xz" => HashType.CRC64_XZ,
"fletcher16" => HashType.Fletcher16,
"fletcher32" => HashType.Fletcher32,
"fletcher64" => HashType.Fletcher64,
"fnv0_32" => HashType.FNV0_32,
"fnv0_64" => HashType.FNV0_64,
"fnv1_32" => HashType.FNV1_32,
"fnv1_64" => HashType.FNV1_64,
"fnv1a_32" => HashType.FNV1a_32,
"fnv1a_64" => HashType.FNV1a_64,
"meka" or "mekacrc" or "meka_crc" => HashType.MekaCrc,
"md2" => HashType.MD2,
"md4" => HashType.MD4,
"md5" => HashType.MD5,
"ripemd128" => HashType.RIPEMD128,
"ripemd160" => HashType.RIPEMD160,
"ripemd256" => HashType.RIPEMD256,
"ripemd320" => HashType.RIPEMD320,
"sha1" => HashType.SHA1,
"sha256" => HashType.SHA256,
"sha384" => HashType.SHA384,
"sha512" => HashType.SHA512,
#if NET8_0_OR_GREATER
"sha3_256" => HashType.SHA3_256,
"sha3_384" => HashType.SHA3_384,
"sha3_512" => HashType.SHA3_512,
"shake128" => HashType.SHAKE128,
"shake256" => HashType.SHAKE256,
#endif
"spamsum" => HashType.SpamSum,
"tiger128_3" => HashType.Tiger128_3,
"tiger128_4" => HashType.Tiger128_4,
"tiger160_3" => HashType.Tiger160_3,
"tiger160_4" => HashType.Tiger160_4,
"tiger192_3" => HashType.Tiger192_3,
"tiger192_4" => HashType.Tiger192_4,
"tiger2_128_3" => HashType.Tiger2_128_3,
"tiger2_128_4" => HashType.Tiger2_128_4,
"tiger2_160_3" => HashType.Tiger2_160_3,
"tiger2_160_4" => HashType.Tiger2_160_4,
"tiger2_192_3" => HashType.Tiger2_192_3,
"tiger2_192_4" => HashType.Tiger2_192_4,
"xxh" or "xxh32" or "xxh_32" or "xxhash" or "xxhash32" or "xxhash_32" => HashType.XxHash32,
"xxh64" or "xxh_64" or "xxhash64" or "xxhash_64" => HashType.XxHash64,
#if NET462_OR_GREATER || NETCOREAPP
"xxh3" or "xxh3_64" or "xxhash3" or "xxhash_3" => HashType.XxHash3,
"xxh128" or "xxh_128" or "xxhash128" or "xxhash_128" => HashType.XxHash128,
#endif
_ => null,
};
}
}
}

View File

@@ -0,0 +1,181 @@
using System;
namespace SabreTools.Hashing
{
internal static class HashOperations
{
#region Conversions
/// <summary>
/// Convert a byte array to a hex string
/// </summary>
/// <param name="bytes">Byte array to convert</param>
/// <returns>Hex string representing the byte array</returns>
/// <link>http://stackoverflow.com/questions/311165/how-do-you-convert-byte-array-to-hexadecimal-string-and-vice-versa</link>
public static string? ByteArrayToString(byte[]? bytes)
{
// If we get null in, we send null out
if (bytes is null)
return null;
try
{
string hex = BitConverter.ToString(bytes);
return hex.Replace("-", string.Empty).ToLowerInvariant();
}
catch
{
return null;
}
}
/// <summary>
/// Convert a byte array to a UInt64
/// </summary>
/// <param name="bytes">Byte array to convert</param>
/// <returns>UInt64 representing the byte array</returns>
/// <link>https://stackoverflow.com/questions/66750224/how-to-convert-a-byte-array-of-any-size-to-ulong-in-c</link>
public static ulong BytesToUInt64(byte[]? bytes)
{
// If we get null in, we send 0 out
if (bytes is null)
return default;
ulong result = 0;
for (int i = 0; i < bytes.Length; i++)
{
result |= (ulong)bytes[i] << (i * 8);
}
return result;
}
#endregion
#region Read Big-Endian
/// <summary>
/// 32-bit big-endian read
/// </summary>
public static uint ReadBE32(byte[] data, int offset)
{
return (uint)(data[offset + 3]
| (data[offset + 2] << 8)
| (data[offset + 1] << 16)
| (data[offset + 0] << 24));
}
/// <summary>
/// 64-bit big-endian read
/// </summary>
public static ulong ReadBE64(byte[] data, int offset)
{
return data[offset + 7]
| ((ulong)data[offset + 6] << 8)
| ((ulong)data[offset + 5] << 16)
| ((ulong)data[offset + 4] << 24)
| ((ulong)data[offset + 3] << 32)
| ((ulong)data[offset + 2] << 40)
| ((ulong)data[offset + 1] << 48)
| ((ulong)data[offset + 0] << 56);
}
#endregion
#region Read Litte-Endian
/// <summary>
/// 32-bit little-endian read
/// </summary>
public static uint ReadLE32(byte[] data, int offset)
{
return (uint)(data[offset + 0]
| (data[offset + 1] << 8)
| (data[offset + 2] << 16)
| (data[offset + 3] << 24));
}
/// <summary>
/// 64-bit little-endian read
/// </summary>
public static ulong ReadLE64(byte[] data, int offset)
{
return data[offset + 0]
| ((ulong)data[offset + 1] << 8)
| ((ulong)data[offset + 2] << 16)
| ((ulong)data[offset + 3] << 24)
| ((ulong)data[offset + 4] << 32)
| ((ulong)data[offset + 5] << 40)
| ((ulong)data[offset + 6] << 48)
| ((ulong)data[offset + 7] << 56);
}
#endregion
#region Reverse
/// <summary>
/// Reverse the endianness of a value
/// </summary>
public static ulong ReverseBits(ulong value, int bitWidth)
{
ulong reverse = 0;
for (int i = 0; i < bitWidth; i++)
{
reverse <<= 1;
reverse |= value & 1;
value >>= 1;
}
return reverse;
}
#endregion
#region Rotate
/// <summary>
/// 32-bit rotate left.
/// </summary>
public static uint RotateLeft32(uint x, int r)
=> (x << r) | (x >> (32 - r));
/// <summary>
/// 64-bit rotate left.
/// </summary>
public static ulong RotateLeft64(ulong x, int r)
=> (x << r) | (x >> (64 - r));
#endregion
#region Swap
/// <summary>
/// A 32-bit byteswap.
/// </summary>
public static uint Swap32(uint x)
{
return ((x << 24) & 0xff000000)
| ((x << 8) & 0x00ff0000)
| ((x >> 8) & 0x0000ff00)
| ((x >> 24) & 0x000000ff);
}
/// <summary>
/// A 64-bit byteswap.
/// </summary>
public static ulong Swap64(ulong x)
{
return ((x << 56) & 0xff00000000000000)
| ((x << 40) & 0x00ff000000000000)
| ((x << 24) & 0x0000ff0000000000)
| ((x << 8) & 0x000000ff00000000)
| ((x >> 8) & 0x00000000ff000000)
| ((x >> 24) & 0x0000000000ff0000)
| ((x >> 40) & 0x000000000000ff00)
| ((x >> 56) & 0x00000000000000ff);
}
#endregion
}
}

View File

@@ -1,7 +1,7 @@
using System;
using System.Collections.Generic;
using System.IO;
#if NET40_OR_GREATER || NETCOREAPP
#if NET40_OR_GREATER || NETCOREAPP || NETSTANDARD2_0_OR_GREATER
using System.Threading.Tasks;
#endif
@@ -12,10 +12,16 @@ namespace SabreTools.Hashing
/// </summary>
public static class HashTool
{
#region Standard Hashes
/// <summary>
/// Get CRC-32, MD5, and SHA-1 hashes from an input file path
/// </summary>
/// <param name="filename">Path to the input file</param>
/// <param name="size">Calculated file size on success, -1 on error</param>
/// <param name="crc32">CRC-32 for the input file</param>
/// <param name="md5">MD5 for the input file</param>
/// <param name="sha1">SHA-1 for the input file</param>
/// <returns>True if hashing was successful, false otherwise</returns>
public static bool GetStandardHashes(string filename, out long size, out string? crc32, out string? md5, out string? sha1)
{
@@ -25,7 +31,7 @@ namespace SabreTools.Hashing
// Get all file hashes
HashType[] standardHashTypes = [HashType.CRC32, HashType.MD5, HashType.SHA1];
var fileHashes = GetFileHashesAndSize(filename, standardHashTypes, out size);
if (fileHashes == null)
if (fileHashes is null)
return false;
// Assign the file hashes and return
@@ -35,6 +41,62 @@ namespace SabreTools.Hashing
return true;
}
/// <summary>
/// Get CRC-32, MD5, and SHA-1 hashes from an input byte array
/// </summary>
/// <param name="array">Input byte array</param>
/// <param name="size">Calculated file size on success, -1 on error</param>
/// <param name="crc32">CRC-32 for the input file</param>
/// <param name="md5">MD5 for the input file</param>
/// <param name="sha1">SHA-1 for the input file</param>
/// <returns>True if hashing was successful, false otherwise</returns>
public static bool GetStandardHashes(byte[] array, out long size, out string? crc32, out string? md5, out string? sha1)
{
// Set all initial values
crc32 = null; md5 = null; sha1 = null;
// Get all file hashes
HashType[] standardHashTypes = [HashType.CRC32, HashType.MD5, HashType.SHA1];
var fileHashes = GetByteArrayHashesAndSize(array, standardHashTypes, out size);
if (fileHashes is null)
return false;
// Assign the file hashes and return
crc32 = fileHashes[HashType.CRC32];
md5 = fileHashes[HashType.MD5];
sha1 = fileHashes[HashType.SHA1];
return true;
}
/// <summary>
/// Get CRC-32, MD5, and SHA-1 hashes from an input stream
/// </summary>
/// <param name="stream">Input stream</param>
/// <param name="size">Calculated file size on success, -1 on error</param>
/// <param name="crc32">CRC-32 for the input file</param>
/// <param name="md5">MD5 for the input file</param>
/// <param name="sha1">SHA-1 for the input file</param>
/// <returns>True if hashing was successful, false otherwise</returns>
public static bool GetStandardHashes(Stream stream, out long size, out string? crc32, out string? md5, out string? sha1)
{
// Set all initial values
crc32 = null; md5 = null; sha1 = null;
// Get all file hashes
HashType[] standardHashTypes = [HashType.CRC32, HashType.MD5, HashType.SHA1];
var fileHashes = GetStreamHashesAndSize(stream, standardHashTypes, out size);
if (fileHashes is null)
return false;
// Assign the file hashes and return
crc32 = fileHashes[HashType.CRC32];
md5 = fileHashes[HashType.MD5];
sha1 = fileHashes[HashType.SHA1];
return true;
}
#endregion
#region File Hashes Without Size
/// <summary>
@@ -60,10 +122,7 @@ namespace SabreTools.Hashing
/// <param name="hashType">Hash type to get from the file</param>
/// <returns>Hash on success, null on error</returns>
public static string? GetFileHash(string filename, HashType hashType)
{
var hashes = GetFileHashes(filename, [hashType]);
return hashes?[hashType];
}
=> GetFileHashAndSize(filename, hashType, out _);
/// <summary>
/// Get a hash from an input file path
@@ -72,10 +131,7 @@ namespace SabreTools.Hashing
/// <param name="hashType">Hash type to get from the file</param>
/// <returns>Hash on success, null on error</returns>
public static byte[]? GetFileHashArray(string filename, HashType hashType)
{
var hashes = GetFileHashArrays(filename, [hashType]);
return hashes?[hashType];
}
=> GetFileHashArrayAndSize(filename, hashType, out _);
/// <summary>
/// Get hashes from an input file path
@@ -103,6 +159,7 @@ namespace SabreTools.Hashing
/// Get hashes and size from an input file path
/// </summary>
/// <param name="filename">Path to the input file</param>
/// <param name="size">Amount of bytes read during hashing</param>
/// <returns>Dictionary containing hashes on success, null on error</returns>
public static Dictionary<HashType, string?>? GetFileHashesAndSize(string filename, out long size)
{
@@ -117,6 +174,7 @@ namespace SabreTools.Hashing
/// Get hashes and size from an input file path
/// </summary>
/// <param name="filename">Path to the input file</param>
/// <param name="size">Amount of bytes read during hashing</param>
/// <returns>Dictionary containing hashes on success, null on error</returns>
public static Dictionary<HashType, byte[]?>? GetFileHashArraysAndSize(string filename, out long size)
{
@@ -132,6 +190,7 @@ namespace SabreTools.Hashing
/// </summary>
/// <param name="filename">Path to the input file</param>
/// <param name="hashType">Hash type to get from the file</param>
/// <param name="size">Amount of bytes read during hashing</param>
/// <returns>Hash and size on success, null on error</returns>
public static string? GetFileHashAndSize(string filename, HashType hashType, out long size)
{
@@ -144,6 +203,7 @@ namespace SabreTools.Hashing
/// </summary>
/// <param name="filename">Path to the input file</param>
/// <param name="hashType">Hash type to get from the file</param>
/// <param name="size">Amount of bytes read during hashing</param>
/// <returns>Hash and size on success, null on error</returns>
public static byte[]? GetFileHashArrayAndSize(string filename, HashType hashType, out long size)
{
@@ -156,6 +216,7 @@ namespace SabreTools.Hashing
/// </summary>
/// <param name="filename">Path to the input file</param>
/// <param name="hashTypes">Array of hash types to get from the file</param>
/// <param name="size">Amount of bytes read during hashing</param>
/// <returns>Dictionary containing hashes on success, null on error</returns>
public static Dictionary<HashType, string?>? GetFileHashesAndSize(string filename, HashType[] hashTypes, out long size)
{
@@ -166,14 +227,11 @@ namespace SabreTools.Hashing
return null;
}
// Set the file size
size = new FileInfo(filename).Length;
// Open the input file
var input = File.OpenRead(filename);
// Return the hashes from the stream
return GetStreamHashes(input, hashTypes);
return GetStreamHashesAndSize(input, hashTypes, out size);
}
/// <summary>
@@ -181,6 +239,7 @@ namespace SabreTools.Hashing
/// </summary>
/// <param name="filename">Path to the input file</param>
/// <param name="hashTypes">Array of hash types to get from the file</param>
/// <param name="size">Amount of bytes read during hashing</param>
/// <returns>Dictionary containing hashes on success, null on error</returns>
public static Dictionary<HashType, byte[]?>? GetFileHashArraysAndSize(string filename, HashType[] hashTypes, out long size)
{
@@ -191,19 +250,16 @@ namespace SabreTools.Hashing
return null;
}
// Set the file size
size = new FileInfo(filename).Length;
// Open the input file
var input = File.OpenRead(filename);
// Return the hashes from the stream
return GetStreamHashArrays(input, hashTypes);
return GetStreamHashArraysAndSize(input, hashTypes, out size);
}
#endregion
#region Byte Array Hashes
#region Byte Array Hashes Without Size
/// <summary>
/// Get hashes from an input byte array
@@ -211,13 +267,7 @@ namespace SabreTools.Hashing
/// <param name="input">Byte array to hash</param>
/// <returns>Dictionary containing hashes on success, null on error</returns>
public static Dictionary<HashType, string?>? GetByteArrayHashes(byte[] input)
{
// Create a hash array for all entries
HashType[] hashTypes = (HashType[])Enum.GetValues(typeof(HashType));
// Return the hashes from the stream
return GetStreamHashes(new MemoryStream(input), hashTypes);
}
=> GetByteArrayHashesAndSize(input, out _);
/// <summary>
/// Get hashes from an input byte array
@@ -225,13 +275,7 @@ namespace SabreTools.Hashing
/// <param name="input">Byte array to hash</param>
/// <returns>Dictionary containing hashes on success, null on error</returns>
public static Dictionary<HashType, byte[]?>? GetByteArrayHashArrays(byte[] input)
{
// Create a hash array for all entries
HashType[] hashTypes = (HashType[])Enum.GetValues(typeof(HashType));
// Return the hashes from the stream
return GetStreamHashArrays(new MemoryStream(input), hashTypes);
}
=> GetByteArrayHashArraysAndSize(input, out _);
/// <summary>
/// Get a hash from an input byte array
@@ -240,10 +284,7 @@ namespace SabreTools.Hashing
/// <param name="hashType">Hash type to get from the file</param>
/// <returns>Hash on success, null on error</returns>
public static string? GetByteArrayHash(byte[] input, HashType hashType)
{
var hashes = GetStreamHashes(new MemoryStream(input), [hashType]);
return hashes?[hashType];
}
=> GetByteArrayHashAndSize(input, hashType, out _);
/// <summary>
/// Get a hash from an input byte array
@@ -252,10 +293,7 @@ namespace SabreTools.Hashing
/// <param name="hashType">Hash type to get from the file</param>
/// <returns>Hash on success, null on error</returns>
public static byte[]? GetByteArrayHashArray(byte[] input, HashType hashType)
{
var hashes = GetStreamHashArrays(new MemoryStream(input), [hashType]);
return hashes?[hashType];
}
=> GetByteArrayHashArrayAndSize(input, hashType, out _);
/// <summary>
/// Get hashes from an input byte array
@@ -264,7 +302,7 @@ namespace SabreTools.Hashing
/// <param name="hashTypes">Array of hash types to get from the file</param>
/// <returns>Dictionary containing hashes on success, null on error</returns>
public static Dictionary<HashType, string?>? GetByteArrayHashes(byte[] input, HashType[] hashTypes)
=> GetStreamHashes(new MemoryStream(input), hashTypes);
=> GetByteArrayHashesAndSize(input, hashTypes, out _);
/// <summary>
/// Get hashes from an input byte array
@@ -273,78 +311,294 @@ namespace SabreTools.Hashing
/// <param name="hashTypes">Array of hash types to get from the file</param>
/// <returns>Dictionary containing hashes on success, null on error</returns>
public static Dictionary<HashType, byte[]?>? GetByteArrayHashArrays(byte[] input, HashType[] hashTypes)
=> GetStreamHashArrays(new MemoryStream(input), hashTypes);
=> GetByteArrayHashArraysAndSize(input, hashTypes, out _);
#endregion
#region Stream Hashes
#region Byte Array Hashes With Size
/// <summary>
/// Get hashes from an input byte array
/// </summary>
/// <param name="input">Byte array to hash</param>
/// <param name="size">Amount of bytes read during hashing</param>
/// <returns>Dictionary containing hashes on success, null on error</returns>
public static Dictionary<HashType, string?>? GetByteArrayHashesAndSize(byte[] input, out long size)
{
// Create a hash array for all entries
HashType[] hashTypes = (HashType[])Enum.GetValues(typeof(HashType));
// Return the hashes from the stream
return GetStreamHashesAndSize(new MemoryStream(input), hashTypes, out size);
}
/// <summary>
/// Get hashes from an input byte array
/// </summary>
/// <param name="input">Byte array to hash</param>
/// <param name="size">Amount of bytes read during hashing</param>
/// <returns>Dictionary containing hashes on success, null on error</returns>
public static Dictionary<HashType, byte[]?>? GetByteArrayHashArraysAndSize(byte[] input, out long size)
{
// Create a hash array for all entries
HashType[] hashTypes = (HashType[])Enum.GetValues(typeof(HashType));
// Return the hashes from the stream
return GetStreamHashArraysAndSize(new MemoryStream(input), hashTypes, out size);
}
/// <summary>
/// Get a hash from an input byte array
/// </summary>
/// <param name="input">Byte array to hash</param>
/// <param name="hashType">Hash type to get from the file</param>
/// <param name="size">Amount of bytes read during hashing</param>
/// <returns>Hash on success, null on error</returns>
public static string? GetByteArrayHashAndSize(byte[] input, HashType hashType, out long size)
{
var hashes = GetStreamHashesAndSize(new MemoryStream(input), [hashType], out size);
return hashes?[hashType];
}
/// <summary>
/// Get a hash from an input byte array
/// </summary>
/// <param name="input">Byte array to hash</param>
/// <param name="hashType">Hash type to get from the file</param>
/// <param name="size">Amount of bytes read during hashing</param>
/// <returns>Hash on success, null on error</returns>
public static byte[]? GetByteArrayHashArrayAndSize(byte[] input, HashType hashType, out long size)
{
var hashes = GetStreamHashArraysAndSize(new MemoryStream(input), [hashType], out size);
return hashes?[hashType];
}
/// <summary>
/// Get hashes from an input byte array
/// </summary>
/// <param name="input">Byte array to hash</param>
/// <param name="hashTypes">Array of hash types to get from the file</param>
/// <param name="size">Amount of bytes read during hashing</param>
/// <returns>Dictionary containing hashes on success, null on error</returns>
public static Dictionary<HashType, string?>? GetByteArrayHashesAndSize(byte[] input, HashType[] hashTypes, out long size)
=> GetStreamHashesAndSize(new MemoryStream(input), hashTypes, out size);
/// <summary>
/// Get hashes from an input byte array
/// </summary>
/// <param name="input">Byte array to hash</param>
/// <param name="hashTypes">Array of hash types to get from the file</param>
/// <param name="size">Amount of bytes read during hashing</param>
/// <returns>Dictionary containing hashes on success, null on error</returns>
public static Dictionary<HashType, byte[]?>? GetByteArrayHashArraysAndSize(byte[] input, HashType[] hashTypes, out long size)
=> GetStreamHashArraysAndSize(new MemoryStream(input), hashTypes, out size);
#endregion
#region Stream Hashes Without Size
/// <summary>
/// Get hashes from an input Stream
/// </summary>
/// <param name="input">Stream to hash</param>
/// <param name="leaveOpen">Indicates if the source stream should be left open after hashing</param>
/// <returns>Dictionary containing hashes on success, null on error</returns>
public static Dictionary<HashType, string?>? GetStreamHashes(Stream input, bool leaveOpen = false)
{
// Create a hash array for all entries
HashType[] hashTypes = (HashType[])Enum.GetValues(typeof(HashType));
// Get the output hashes
return GetStreamHashes(input, hashTypes, leaveOpen);
}
=> GetStreamHashesAndSize(input, leaveOpen, out _);
/// <summary>
/// Get hashes from an input Stream
/// </summary>
/// <param name="input">Stream to hash</param>
/// <param name="leaveOpen">Indicates if the source stream should be left open after hashing</param>
/// <returns>Dictionary containing hashes on success, null on error</returns>
public static Dictionary<HashType, byte[]?>? GetStreamHashArrays(Stream input, bool leaveOpen = false)
{
// Create a hash array for all entries
HashType[] hashTypes = (HashType[])Enum.GetValues(typeof(HashType));
// Get the output hashes
return GetStreamHashArrays(input, hashTypes, leaveOpen);
}
=> GetStreamHashArraysAndSize(input, leaveOpen, out _);
/// <summary>
/// Get a hash and size from an input Stream
/// Get a hash from an input Stream
/// </summary>
/// <param name="input">Stream to hash</param>
/// <param name="hashType">Hash type to get from the file</param>
/// <param name="leaveOpen">Indicates if the source stream should be left open after hashing</param>
/// <returns>Hash on success, null on error</returns>
public static string? GetStreamHash(Stream input, HashType hashType, bool leaveOpen = false)
{
var hashes = GetStreamHashes(input, [hashType], leaveOpen);
return hashes?[hashType];
}
=> GetStreamHashAndSize(input, hashType, leaveOpen, out _);
/// <summary>
/// Get a hash and size from an input Stream
/// Get a hash from an input Stream
/// </summary>
/// <param name="input">Stream to hash</param>
/// <param name="hashType">Hash type to get from the file</param>
/// <param name="leaveOpen">Indicates if the source stream should be left open after hashing</param>
/// <returns>Hash on success, null on error</returns>
public static byte[]? GetStreamHashArray(Stream input, HashType hashType, bool leaveOpen = false)
{
var hashes = GetStreamHashArrays(input, [hashType], leaveOpen);
return hashes?[hashType];
}
=> GetStreamHashArrayAndSize(input, hashType, leaveOpen, out _);
/// <summary>
/// Get hashes from an input Stream
/// </summary>
/// <param name="input">Stream to hash</param>
/// <param name="hashTypes">Array of hash types to get from the file</param>
/// <param name="leaveOpen">Indicates if the source stream should be left open after hashing</param>
/// <returns>Dictionary containing hashes on success, null on error</returns>
public static Dictionary<HashType, string?>? GetStreamHashes(Stream input, HashType[] hashTypes, bool leaveOpen = false)
=> GetStreamHashesAndSize(input, hashTypes, leaveOpen, out _);
/// <summary>
/// Get hashes from an input Stream
/// </summary>
/// <param name="input">Stream to hash</param>
/// <param name="hashTypes">Array of hash types to get from the file</param>
/// <param name="leaveOpen">Indicates if the source stream should be left open after hashing</param>
/// <returns>Dictionary containing hashes on success, null on error</returns>
public static Dictionary<HashType, byte[]?>? GetStreamHashArrays(Stream input, HashType[] hashTypes, bool leaveOpen = false)
=> GetStreamHashArraysAndSize(input, hashTypes, leaveOpen, out _);
#endregion
#region Stream Hashes With Size
/// <summary>
/// Get hashes and size from an input Stream
/// </summary>
/// <param name="input">Stream to hash</param>
/// <param name="size">Amount of bytes read during hashing</param>
/// <returns>Dictionary containing hashes on success, null on error</returns>
public static Dictionary<HashType, string?>? GetStreamHashesAndSize(Stream input, out long size)
=> GetStreamHashesAndSize(input, leaveOpen: false, out size);
/// <summary>
/// Get hashes and size from an input Stream
/// </summary>
/// <param name="input">Stream to hash</param>
/// <param name="leaveOpen">Indicates if the source stream should be left open after hashing</param>
/// <param name="size">Amount of bytes read during hashing</param>
/// <returns>Dictionary containing hashes on success, null on error</returns>
public static Dictionary<HashType, string?>? GetStreamHashesAndSize(Stream input, bool leaveOpen, out long size)
{
// Create a hash array for all entries
HashType[] hashTypes = (HashType[])Enum.GetValues(typeof(HashType));
// Get the output hashes
return GetStreamHashesAndSize(input, hashTypes, leaveOpen, out size);
}
/// <summary>
/// Get hashes and size from an input Stream
/// </summary>
/// <param name="input">Stream to hash</param>
/// <param name="size">Amount of bytes read during hashing</param>
/// <returns>Dictionary containing hashes on success, null on error</returns>
public static Dictionary<HashType, byte[]?>? GetStreamHashArraysAndSize(Stream input, out long size)
=> GetStreamHashArraysAndSize(input, leaveOpen: false, out size);
/// <summary>
/// Get hashes and size from an input Stream
/// </summary>
/// <param name="input">Stream to hash</param>
/// <param name="leaveOpen">Indicates if the source stream should be left open after hashing</param>
/// <param name="size">Amount of bytes read during hashing</param>
/// <returns>Dictionary containing hashes on success, null on error</returns>
public static Dictionary<HashType, byte[]?>? GetStreamHashArraysAndSize(Stream input, bool leaveOpen, out long size)
{
// Create a hash array for all entries
HashType[] hashTypes = (HashType[])Enum.GetValues(typeof(HashType));
// Get the output hashes
return GetStreamHashArraysAndSize(input, hashTypes, leaveOpen, out size);
}
/// <summary>
/// Get a hash and size from an input Stream
/// </summary>
/// <param name="input">Stream to hash</param>
/// <param name="hashType">Hash type to get from the file</param>
/// <param name="size">Amount of bytes read during hashing</param>
/// <returns>Hash on success, null on error</returns>
public static string? GetStreamHashAndSize(Stream input, HashType hashType, out long size)
=> GetStreamHashAndSize(input, hashType, leaveOpen: false, out size);
/// <summary>
/// Get a hash and size from an input Stream
/// </summary>
/// <param name="input">Stream to hash</param>
/// <param name="hashType">Hash type to get from the file</param>
/// <param name="leaveOpen">Indicates if the source stream should be left open after hashing</param>
/// <param name="size">Amount of bytes read during hashing</param>
/// <returns>Hash on success, null on error</returns>
public static string? GetStreamHashAndSize(Stream input, HashType hashType, bool leaveOpen, out long size)
{
var hashes = GetStreamHashesAndSize(input, [hashType], leaveOpen, out size);
return hashes?[hashType];
}
/// <summary>
/// Get a hash and size from an input Stream
/// </summary>
/// <param name="input">Stream to hash</param>
/// <param name="hashType">Hash type to get from the file</param>
/// <param name="size">Amount of bytes read during hashing</param>
/// <returns>Hash on success, null on error</returns>
public static byte[]? GetStreamHashArrayAndSize(Stream input, HashType hashType, out long size)
=> GetStreamHashArrayAndSize(input, hashType, leaveOpen: false, out size);
/// <summary>
/// Get a hash and size from an input Stream
/// </summary>
/// <param name="input">Stream to hash</param>
/// <param name="hashType">Hash type to get from the file</param>
/// <param name="leaveOpen">Indicates if the source stream should be left open after hashing</param>
/// <param name="size">Amount of bytes read during hashing</param>
/// <returns>Hash on success, null on error</returns>
public static byte[]? GetStreamHashArrayAndSize(Stream input, HashType hashType, bool leaveOpen, out long size)
{
var hashes = GetStreamHashArraysAndSize(input, [hashType], leaveOpen, out size);
return hashes?[hashType];
}
/// <summary>
/// Get hashes and size from an input Stream
/// </summary>
/// <param name="input">Stream to hash</param>
/// <param name="hashTypes">Array of hash types to get from the file</param>
/// <param name="size">Amount of bytes read during hashing</param>
/// <returns>Dictionary containing hashes on success, null on error</returns>
public static Dictionary<HashType, string?>? GetStreamHashesAndSize(Stream input, HashType[] hashTypes, out long size)
=> GetStreamHashesAndSize(input, hashTypes, leaveOpen: false, out size);
/// <summary>
/// Get hashes and size from an input Stream
/// </summary>
/// <param name="input">Stream to hash</param>
/// <param name="hashTypes">Array of hash types to get from the file</param>
/// <param name="leaveOpen">Indicates if the source stream should be left open after hashing</param>
/// <param name="size">Amount of bytes read during hashing</param>
/// <returns>Dictionary containing hashes on success, null on error</returns>
public static Dictionary<HashType, string?>? GetStreamHashesAndSize(Stream input, HashType[] hashTypes, bool leaveOpen, out long size)
{
// Create the output dictionary
var hashDict = new Dictionary<HashType, string?>();
try
{
// Shortcut if we have a 0-byte input
if (input.Length == 0)
{
foreach (var hashType in hashTypes)
{
hashDict[hashType] = ZeroHash.GetString(hashType);
}
size = 0;
return hashDict;
}
}
catch { }
// Run the hashing
var hashers = GetStreamHashesInternal(input, hashTypes, leaveOpen);
if (hashers == null)
var hashers = GetStreamHashesInternal(input, hashTypes, leaveOpen, out size);
if (hashers is null)
return null;
// Get the results
@@ -363,19 +617,47 @@ namespace SabreTools.Hashing
}
/// <summary>
/// Get hashes from an input Stream
/// Get hashes and size from an input Stream
/// </summary>
/// <param name="input">Stream to hash</param>
/// <param name="hashTypes">Array of hash types to get from the file</param>
/// <param name="size">Amount of bytes read during hashing</param>
/// <returns>Dictionary containing hashes on success, null on error</returns>
public static Dictionary<HashType, byte[]?>? GetStreamHashArrays(Stream input, HashType[] hashTypes, bool leaveOpen = false)
public static Dictionary<HashType, byte[]?>? GetStreamHashArraysAndSize(Stream input, HashType[] hashTypes, out long size)
=> GetStreamHashArraysAndSize(input, hashTypes, leaveOpen: false, out size);
/// <summary>
/// Get hashes and size from an input Stream
/// </summary>
/// <param name="input">Stream to hash</param>
/// <param name="hashTypes">Array of hash types to get from the file</param>
/// <param name="leaveOpen">Indicates if the source stream should be left open after hashing</param>
/// <param name="size">Amount of bytes read during hashing</param>
/// <returns>Dictionary containing hashes on success, null on error</returns>
public static Dictionary<HashType, byte[]?>? GetStreamHashArraysAndSize(Stream input, HashType[] hashTypes, bool leaveOpen, out long size)
{
// Create the output dictionary
var hashDict = new Dictionary<HashType, byte[]?>();
try
{
// Shortcut if we have a 0-byte input
if (input.Length == 0)
{
foreach (var hashType in hashTypes)
{
hashDict[hashType] = ZeroHash.GetBytes(hashType);
}
size = 0;
return hashDict;
}
}
catch { }
// Run the hashing
var hashers = GetStreamHashesInternal(input, hashTypes, leaveOpen);
if (hashers == null)
var hashers = GetStreamHashesInternal(input, hashTypes, leaveOpen, out size);
if (hashers is null)
return null;
// Get the results
@@ -394,16 +676,18 @@ namespace SabreTools.Hashing
}
/// <summary>
/// Get hashes from an input stream
/// Get hashes and size from an input Stream
/// </summary>
/// <param name="input"></param>
/// <param name="hashTypes"></param>
/// <param name="leaveOpen"></param>
/// <param name="input">Stream to hash</param>
/// <param name="hashTypes">Array of hash types to get from the file</param>
/// <param name="leaveOpen">Indicates if the source stream should be left open after hashing</param>
/// <param name="size">Amount of bytes read during hashing</param>
/// <returns></returns>
private static Dictionary<HashType, HashWrapper>? GetStreamHashesInternal(Stream input, HashType[] hashTypes, bool leaveOpen)
private static Dictionary<HashType, HashWrapper>? GetStreamHashesInternal(Stream input, HashType[] hashTypes, bool leaveOpen, out long size)
{
// Create the output dictionary
// Create the output dictionary and size counter
var hashDict = new Dictionary<HashType, string?>();
size = 0;
try
{
@@ -426,6 +710,7 @@ namespace SabreTools.Hashing
{
// Load the buffer and hold the number of bytes read
lastRead = input.Read(buffer, 0, buffersize);
size += lastRead;
if (lastRead == 0)
break;
@@ -468,4 +753,4 @@ namespace SabreTools.Hashing
#endregion
}
}
}

View File

@@ -17,10 +17,327 @@ namespace SabreTools.Hashing
BLAKE3,
#endif
#region CRC
#region CRC-1
/// <summary>
/// CRC 1-bit checksum (CRC-1/ZERO [Parity bit with 0 start])
/// </summary>
CRC1_ZERO,
/// <summary>
/// CRC 1-bit checksum (CRC-1/ONE [Parity bit with 1 start])
/// </summary>
CRC1_ONE,
#endregion
#region CRC-3
/// <summary>
/// CRC 3-bit checksum (CRC-3/GSM)
/// </summary>
CRC3_GSM,
/// <summary>
/// CRC 3-bit checksum (CRC-3/ROHC)
/// </summary>
CRC3_ROHC,
#endregion
#region CRC-4
/// <summary>
/// CRC 4-bit checksum (CRC-4/G-704 [CRC-4/ITU])
/// </summary>
CRC4_G704,
/// <summary>
/// CRC 4-bit checksum (CRC-4/INTERLAKEN)
/// </summary>
CRC4_INTERLAKEN,
#endregion
#region CRC-5
/// <summary>
/// CRC 5-bit checksum (CRC-5/EPC-C1G2 [CRC-5/EPC])
/// </summary>
CRC5_EPCC1G2,
/// <summary>
/// CRC 5-bit checksum (CRC-5/G-704 [CRC-5/ITU])
/// </summary>
CRC5_G704,
/// <summary>
/// CRC 5-bit checksum (CRC-5/USB)
/// </summary>
CRC5_USB,
#endregion
#region CRC-6
/// <summary>
/// CRC 6-bit checksum (CRC-6/CDMA2000-A)
/// </summary>
CRC6_CDMA2000A,
/// <summary>
/// CRC 6-bit checksum (CRC-6/CDMA2000-B)
/// </summary>
CRC6_CDMA2000B,
/// <summary>
/// CRC 6-bit checksum (CRC-6/DARC)
/// </summary>
CRC6_DARC,
/// <summary>
/// CRC 6-bit checksum (CRC-6/G-704 [CRC-6/ITU])
/// </summary>
CRC6_G704,
/// <summary>
/// CRC 6-bit checksum (CRC-6/GSM)
/// </summary>
CRC6_GSM,
#endregion
#region CRC-7
/// <summary>
/// CRC 7-bit checksum (CRC-7/MMC [CRC-7])
/// </summary>
CRC7_MMC,
/// <summary>
/// CRC 7-bit checksum (CRC-7/ROHC)
/// </summary>
CRC7_ROHC,
/// <summary>
/// CRC 7-bit checksum (CRC-7/UMTS)
/// </summary>
CRC7_UMTS,
#endregion
#region CRC-8
/// <summary>
/// CRC 8-bit checksum
/// </summary>
/// <remarks>Identical to <see cref="CRC8_SMBUS"/>
CRC8,
/// <summary>
/// CRC 8-bit checksum (CRC-8/AUTOSAR)
/// </summary>
CRC8_AUTOSAR,
/// <summary>
/// CRC 8-bit checksum (CRC-8/BLUETOOTH)
/// </summary>
CRC8_BLUETOOTH,
/// <summary>
/// CRC 8-bit checksum (CRC-8/CDMA2000)
/// </summary>
CRC8_CDMA2000,
/// <summary>
/// CRC 8-bit checksum (CRC-8/DARC)
/// </summary>
CRC8_DARC,
/// <summary>
/// CRC 8-bit checksum (CRC-8/DVB-S2)
/// </summary>
CRC8_DVBS2,
/// <summary>
/// CRC 8-bit checksum (CRC-8/GSM-A)
/// </summary>
CRC8_GSMA,
/// <summary>
/// CRC 8-bit checksum (CRC-8/GSM-B)
/// </summary>
CRC8_GSMB,
/// <summary>
/// CRC 8-bit checksum (CRC-8/HITAG)
/// </summary>
CRC8_HITAG,
/// <summary>
/// CRC 8-bit checksum (CRC-8/I-432-1 [CRC-8/ITU])
/// </summary>
CRC8_I4321,
/// <summary>
/// CRC 8-bit checksum (CRC-8/I-CODE)
/// </summary>
CRC8_ICODE,
/// <summary>
/// CRC 8-bit checksum (CRC-8/LTE)
/// </summary>
CRC8_LTE,
/// <summary>
/// CRC 8-bit checksum (CRC-8/MAXIM-DOW [CRC-8/MAXIM, DOW-CRC])
/// </summary>
CRC8_MAXIMDOW,
/// <summary>
/// CRC 8-bit checksum (CRC-8/MIFARE-MAD)
/// </summary>
CRC8_MIFAREMAD,
/// <summary>
/// CRC 8-bit checksum (CRC-8/NRSC-5)
/// </summary>
CRC8_NRSC5,
/// <summary>
/// CRC 8-bit checksum (CRC-8/OPENSAFETY)
/// </summary>
CRC8_OPENSAFETY,
/// <summary>
/// CRC 8-bit checksum (CRC-8/ROHC)
/// </summary>
CRC8_ROHC,
/// <summary>
/// CRC 8-bit checksum (CRC-8/SAE-J1850)
/// </summary>
CRC8_SAEJ1850,
/// <summary>
/// CRC 8-bit checksum (CRC-8/SMBUS [CRC-8])
/// </summary>
CRC8_SMBUS,
/// <summary>
/// CRC 8-bit checksum (CRC-8/TECH-3250 [CRC-8/AES, CRC-8/EBU])
/// </summary>
CRC8_TECH3250,
/// <summary>
/// CRC 8-bit checksum (CRC-8/WCDMA)
/// </summary>
CRC8_WCDMA,
#endregion
#region CRC-10
/// <summary>
/// CRC 10-bit checksum (CRC-10/ATM [CRC-10, CRC-10/I-610])
/// </summary>
CRC10_ATM,
/// <summary>
/// CRC 10-bit checksum (CRC-10/CDMA2000)
/// </summary>
CRC10_CDMA2000,
/// <summary>
/// CRC 10-bit checksum (CRC-10/GSM)
/// </summary>
CRC10_GSM,
#endregion
#region CRC-11
/// <summary>
/// CRC 11-bit checksum (CRC-11/FLEXRAY [CRC-11])
/// </summary>
CRC11_FLEXRAY,
/// <summary>
/// CRC 11-bit checksum (CRC-11/UMTS)
/// </summary>
CRC11_UMTS,
#endregion
#region CRC-12
/// <summary>
/// CRC 12-bit checksum (CRC-12/CDMA2000)
/// </summary>
CRC12_CDMA2000,
/// <summary>
/// CRC 12-bit checksum (CRC-12/DECT [X-CRC-12])
/// </summary>
CRC12_DECT,
/// <summary>
/// CRC 12-bit checksum (CRC-12/GSM)
/// </summary>
CRC12_GSM,
/// <summary>
/// CRC 12-bit checksum (CRC-12/UMTS [CRC-12/3GPP])
/// </summary>
CRC12_UMTS,
#endregion
#region CRC-13
/// <summary>
/// CRC 13-bit checksum (CRC-13/BBC)
/// </summary>
CRC13_BBC,
#endregion
#region CRC-14
/// <summary>
/// CRC 14-bit checksum (CRC-14/DARC)
/// </summary>
CRC14_DARC,
/// <summary>
/// CRC 14-bit checksum (CRC-14/GSM)
/// </summary>
CRC14_GSM,
#endregion
#region CRC-15
/// <summary>
/// CRC 15-bit checksum (CRC-15/CAN [CRC-15])
/// </summary>
CRC15_CAN,
/// <summary>
/// CRC 15-bit checksum (CRC-15/MPT1327)
/// </summary>
CRC15_MPT1327,
#endregion
#region CRC-16
/// <summary>
/// CRC 16-bit checksum
/// </summary>
/// <remarks>Identical to <see cref="CRC16_ARC"/>
/// <remarks>Identical to <see cref="CRC16_ARC"/>
CRC16,
/// <summary>
@@ -86,7 +403,7 @@ namespace SabreTools.Hashing
/// <summary>
/// CRC 16-bit checksum (CRC-16/ISO-IEC-14443-3-A [CRC-A])
/// </summary>
//CRC16_ISOIEC144433A, // Disabled until incorrect hashes can be fixed
CRC16_ISOIEC144433A,
/// <summary>
/// CRC 16-bit checksum (CRC-16/KERMIT [CRC-16/BLUETOOTH, CRC-16/CCITT, CRC-16/CCITT-TRUE, CRC-16/V-41-LSB, CRC-CCITT, KERMIT])
@@ -141,7 +458,7 @@ namespace SabreTools.Hashing
/// <summary>
/// CRC 16-bit checksum (CRC-16/RIELLO)
/// </summary>
//CRC16_RIELLO, // Disabled until incorrect hashes can be fixed
CRC16_RIELLO,
/// <summary>
/// CRC 16-bit checksum (CRC-16/SPI-FUJITSU [CRC-16/AUG-CCITT])
@@ -161,7 +478,7 @@ namespace SabreTools.Hashing
/// <summary>
/// CRC 16-bit checksum (CRC-16/TMS37157)
/// </summary>
//CRC16_TMS37157, // Disabled until incorrect hashes can be fixed
CRC16_TMS37157,
/// <summary>
/// CRC 16-bit checksum (CRC-16/UMTS [CRC-16/BUYPASS, CRC-16/VERIFONE])
@@ -178,10 +495,32 @@ namespace SabreTools.Hashing
/// </summary>
CRC16_XMODEM,
#endregion
#region CRC-17
/// <summary>
/// CRC 17-bit checksum (CRC-17/CAN-FD)
/// </summary>
CRC17_CANFD,
#endregion
#region CRC-21
/// <summary>
/// CRC 21-bit checksum (CRC-21/CAN-FD)
/// </summary>
CRC21_CANFD,
#endregion
#region CRC-24
/// <summary>
/// CRC 24-bit checksum (CRC-24/BLE)
/// </summary>
//CRC24_BLE, // Disabled until incorrect hashes can be fixed
CRC24_BLE,
/// <summary>
/// CRC 24-bit checksum (CRC-24/FLEXRAY-A)
@@ -218,10 +557,32 @@ namespace SabreTools.Hashing
/// </summary>
CRC24_OS9,
#endregion
#region CRC-30
/// <summary>
/// CRC 30-bit checksum (CRC-30/CDMA)
/// </summary>
CRC30_CDMA,
#endregion
#region CRC-31
/// <summary>
/// CRC 31-bit checksum (CRC-31/PHILIPS)
/// </summary>
CRC31_PHILIPS,
#endregion
#region CRC-32
/// <summary>
/// CRC 32-bit checksum
/// </summary>
/// <remarks>Identical to <see cref="CRC32_ISOHDLC"/>
/// <remarks>Identical to <see cref="CRC32_ISOHDLC"/>
CRC32,
/// <summary>
@@ -254,6 +615,11 @@ namespace SabreTools.Hashing
/// </summary>
CRC32_CKSUM,
/// <summary>
/// CRC 32-bit checksum (CRC-32/DVD-ROM-EDC)
/// </summary>
CRC32_DVDROMEDC,
/// <summary>
/// CRC 32-bit checksum (CRC-32/ISCSI)
/// </summary>
@@ -284,15 +650,23 @@ namespace SabreTools.Hashing
/// </summary>
CRC32_XFER,
#endregion
#region CRC-40
/// <summary>
/// CRC 40-bit checksum (CRC-40/GSM)
/// </summary>
CRC40_GSM,
#endregion
#region CRC-64
/// <summary>
/// CRC 64-bit checksum
/// </summary>
/// <remarks>Identical to <see cref="CRC64_ECMA182"/>
/// <remarks>Identical to <see cref="CRC64_ECMA182"/>
CRC64,
/// <summary>
@@ -330,6 +704,12 @@ namespace SabreTools.Hashing
/// </summary>
CRC64_XZ,
#endregion
#endregion
#region Fletcher
/// <summary>
/// John G. Fletcher's 16-bit checksum
/// </summary>
@@ -341,16 +721,95 @@ namespace SabreTools.Hashing
Fletcher32,
/// <summary>
/// MD5 hash
/// John G. Fletcher's 64-bit checksum
/// </summary>
Fletcher64,
#endregion
#region FNV
/// <summary>
/// FNV hash (Variant 0, 32-bit)
/// </summary>
FNV0_32,
/// <summary>
/// FNV hash (Variant 0, 64-bit)
/// </summary>
FNV0_64,
/// <summary>
/// FNV hash (Variant 1, 32-bit)
/// </summary>
FNV1_32,
/// <summary>
/// FNV hash (Variant 1, 64-bit)
/// </summary>
FNV1_64,
/// <summary>
/// FNV hash (Variant 1a, 32-bit)
/// </summary>
FNV1a_32,
/// <summary>
/// FNV hash (Variant 1a, 64-bit)
/// </summary>
FNV1a_64,
#endregion
/// <summary>
/// Custom checksum used by MEKA
/// </summary>
MekaCrc,
#region Message Digest
/// <summary>
/// MD2 message-digest algorithm
/// </summary>
MD2,
/// <summary>
/// MD4 message-digest algorithm
/// </summary>
MD4,
/// <summary>
/// MD5 message-digest algorithm
/// </summary>
MD5,
#if NETFRAMEWORK
#endregion
#region RIPEMD
/// <summary>
/// RIPEMD160 hash
/// RIPEMD-128 hash
/// </summary>
RIPEMD128,
/// <summary>
/// RIPEMD-160 hash
/// </summary>
RIPEMD160,
#endif
/// <summary>
/// RIPEMD-256 hash
/// </summary>
RIPEMD256,
/// <summary>
/// RIPEMD-320 hash
/// </summary>
RIPEMD320,
#endregion
#region SHA
/// <summary>
/// SHA-1 hash
@@ -386,7 +845,7 @@ namespace SabreTools.Hashing
/// <summary>
/// SHA3-512 hash
/// </summary>
SHA3_512,
SHA3_512,
/// <summary>
/// SHAKE128 SHA-3 family hash
@@ -401,12 +860,79 @@ namespace SabreTools.Hashing
SHAKE256,
#endif
#endregion
/// <summary>
/// spamsum fuzzy hash
/// </summary>
SpamSum,
#if NET462_OR_GREATER || NETCOREAPP
#region Tiger
/// <summary>
/// Tiger 128-bit hash, 3 passes
/// </summary>
Tiger128_3,
/// <summary>
/// Tiger 128-bit hash, 4 passes
/// </summary>
Tiger128_4,
/// <summary>
/// Tiger 160-bit hash, 3 passes
/// </summary>
Tiger160_3,
/// <summary>
/// Tiger 160-bit hash, 4 passes
/// </summary>
Tiger160_4,
/// <summary>
/// Tiger 192-bit hash, 3 passes
/// </summary>
Tiger192_3,
/// <summary>
/// Tiger 192-bit hash, 4 passes
/// </summary>
Tiger192_4,
/// <summary>
/// Tiger2 128-bit hash, 3 passes
/// </summary>
Tiger2_128_3,
/// <summary>
/// Tiger2 128-bit hash, 4 passes
/// </summary>
Tiger2_128_4,
/// <summary>
/// Tiger2 160-bit hash, 3 passes
/// </summary>
Tiger2_160_3,
/// <summary>
/// Tiger2 160-bit hash, 4 passes
/// </summary>
Tiger2_160_4,
/// <summary>
/// Tiger2 192-bit hash, 3 passes
/// </summary>
Tiger2_192_3,
/// <summary>
/// Tiger2 192-bit hash, 4 passes
/// </summary>
Tiger2_192_4,
#endregion
#region xxHash
/// <summary>
/// xxHash32 hash
/// </summary>
@@ -417,6 +943,7 @@ namespace SabreTools.Hashing
/// </summary>
XxHash64,
#if NET462_OR_GREATER || NETCOREAPP
/// <summary>
/// XXH3 64-bit hash
/// </summary>
@@ -427,5 +954,7 @@ namespace SabreTools.Hashing
/// </summary>
XxHash128,
#endif
#endregion
}
}
}

View File

@@ -1,14 +1,9 @@
using System;
#if NET462_OR_GREATER || NETCOREAPP
using System.IO.Hashing;
#endif
using System.Security.Cryptography;
using Aaru.Checksums;
using Aaru.CommonTypes.Interfaces;
#if NET7_0_OR_GREATER
using Blake3;
#endif
using SabreTools.Hashing.Crc;
using SabreTools.Hashing.Checksum;
using SabreTools.Hashing.CryptographicHash;
using SabreTools.Hashing.NonCryptographicHash;
using static SabreTools.Hashing.HashOperations;
namespace SabreTools.Hashing
{
@@ -27,52 +22,33 @@ namespace SabreTools.Hashing
/// <summary>
/// Current hash in bytes
/// </summary>
public byte[]? CurrentHashBytes
public byte[]? CurrentHashBytes => _hasher switch
{
get
{
switch (_hasher)
{
case CrcRunner cr:
var crArr = cr.Finalize();
Array.Reverse(crArr);
return crArr;
case HashAlgorithm ha:
return ha.Hash;
case IChecksum ic:
return ic.Final();
HashAlgorithm ha => ha.Hash,
#if NET462_OR_GREATER || NETCOREAPP
case NonCryptographicHashAlgorithm ncha:
var nchaArr = ncha.GetCurrentHash();
Array.Reverse(nchaArr);
return nchaArr;
System.IO.Hashing.NonCryptographicHashAlgorithm ncha => ncha.GetCurrentHash(),
#endif
#if NET8_0_OR_GREATER
case Shake128 s128:
return s128.GetCurrentHash(32);
case Shake256 s256:
return s256.GetCurrentHash(64);
Shake128 s128 => s128.GetCurrentHash(32),
Shake256 s256 => s256.GetCurrentHash(64),
#endif
default:
return null;
}
}
}
_ => null,
};
/// <summary>
/// Current hash as a string
/// </summary>
public string? CurrentHashString
public string? CurrentHashString => _hasher switch
{
get
{
return _hasher switch
{
IChecksum ic => ic.End(),
_ => ByteArrayToString(CurrentHashBytes),
};
}
}
// Needed due to variable bit widths
Crc cr => GetCRCVariableLengthString(cr),
// Needed due to Base64 text output
SpamSum.SpamSum ss => GetSpamSumBase64String(ss),
// Everything else are direct conversions
_ => ByteArrayToString(CurrentHashBytes),
};
#endregion
@@ -81,7 +57,6 @@ namespace SabreTools.Hashing
/// <summary>
/// Internal hasher being used for processing
/// </summary>
/// <remarks>May be either a HashAlgorithm or NonCryptographicHashAlgorithm</remarks>
private object? _hasher;
#endregion
@@ -105,87 +80,174 @@ namespace SabreTools.Hashing
{
_hasher = HashType switch
{
HashType.Adler32 => new Adler32Context(),
HashType.Adler32 => new Adler32(),
#if NET7_0_OR_GREATER
HashType.BLAKE3 => new Blake3HashAlgorithm(),
HashType.BLAKE3 => new Blake3.Blake3HashAlgorithm(),
#endif
HashType.CRC16 => new CrcRunner(StandardDefinitions.CRC16_ARC),
HashType.CRC16_ARC => new CrcRunner(StandardDefinitions.CRC16_ARC),
HashType.CRC16_CDMA2000 => new CrcRunner(StandardDefinitions.CRC16_CDMA2000),
HashType.CRC16_CMS => new CrcRunner(StandardDefinitions.CRC16_CMS),
HashType.CRC16_DDS110 => new CrcRunner(StandardDefinitions.CRC16_DDS110),
HashType.CRC16_DECTR => new CrcRunner(StandardDefinitions.CRC16_DECTR),
HashType.CRC16_DECTX => new CrcRunner(StandardDefinitions.CRC16_DECTX),
HashType.CRC16_DNP => new CrcRunner(StandardDefinitions.CRC16_DNP),
HashType.CRC16_EN13757 => new CrcRunner(StandardDefinitions.CRC16_EN13757),
HashType.CRC16_GENIBUS => new CrcRunner(StandardDefinitions.CRC16_GENIBUS),
HashType.CRC16_GSM => new CrcRunner(StandardDefinitions.CRC16_GSM),
HashType.CRC16_IBM3740 => new CrcRunner(StandardDefinitions.CRC16_IBM3740),
HashType.CRC16_IBMSDLC => new CrcRunner(StandardDefinitions.CRC16_IBMSDLC),
//HashType.CRC16_ISOIEC144433A => new CrcRunner(StandardDefinitions.CRC16_ISOIEC144433A),
HashType.CRC16_KERMIT => new CrcRunner(StandardDefinitions.CRC16_KERMIT),
HashType.CRC16_LJ1200 => new CrcRunner(StandardDefinitions.CRC16_LJ1200),
HashType.CRC16_M17 => new CrcRunner(StandardDefinitions.CRC16_M17),
HashType.CRC16_MAXIMDOW => new CrcRunner(StandardDefinitions.CRC16_MAXIMDOW),
HashType.CRC16_MCRF4XX => new CrcRunner(StandardDefinitions.CRC16_MCRF4XX),
HashType.CRC16_MODBUS => new CrcRunner(StandardDefinitions.CRC16_MODBUS),
HashType.CRC16_NRSC5 => new CrcRunner(StandardDefinitions.CRC16_NRSC5),
HashType.CRC16_OPENSAFETYA => new CrcRunner(StandardDefinitions.CRC16_OPENSAFETYA),
HashType.CRC16_OPENSAFETYB => new CrcRunner(StandardDefinitions.CRC16_OPENSAFETYB),
HashType.CRC16_PROFIBUS => new CrcRunner(StandardDefinitions.CRC16_PROFIBUS),
//HashType.CRC16_RIELLO => new CrcRunner(StandardDefinitions.CRC16_RIELLO),
HashType.CRC16_SPIFUJITSU => new CrcRunner(StandardDefinitions.CRC16_SPIFUJITSU),
HashType.CRC16_T10DIF => new CrcRunner(StandardDefinitions.CRC16_T10DIF),
HashType.CRC16_TELEDISK => new CrcRunner(StandardDefinitions.CRC16_TELEDISK),
//HashType.CRC16_TMS37157 => new CrcRunner(StandardDefinitions.CRC16_TMS37157),
HashType.CRC16_UMTS => new CrcRunner(StandardDefinitions.CRC16_UMTS),
HashType.CRC16_USB => new CrcRunner(StandardDefinitions.CRC16_USB),
HashType.CRC16_XMODEM => new CrcRunner(StandardDefinitions.CRC16_XMODEM),
HashType.CRC1_ZERO => new Crc(StandardDefinitions.CRC1_ZERO),
HashType.CRC1_ONE => new Crc(StandardDefinitions.CRC1_ONE),
//HashType.CRC24_BLE => new CrcRunner(StandardDefinitions.CRC24_BLE),
HashType.CRC24_FLEXRAYA => new CrcRunner(StandardDefinitions.CRC24_FLEXRAYA),
HashType.CRC24_FLEXRAYB => new CrcRunner(StandardDefinitions.CRC24_FLEXRAYB),
HashType.CRC24_INTERLAKEN => new CrcRunner(StandardDefinitions.CRC24_INTERLAKEN),
HashType.CRC24_LTEA => new CrcRunner(StandardDefinitions.CRC24_LTEA),
HashType.CRC24_LTEB => new CrcRunner(StandardDefinitions.CRC24_LTEB),
HashType.CRC24_OPENPGP => new CrcRunner(StandardDefinitions.CRC24_OPENPGP),
HashType.CRC24_OS9 => new CrcRunner(StandardDefinitions.CRC24_OS9),
HashType.CRC3_GSM => new Crc(StandardDefinitions.CRC3_GSM),
HashType.CRC3_ROHC => new Crc(StandardDefinitions.CRC3_ROHC),
HashType.CRC32 => new CrcRunner(StandardDefinitions.CRC32_ISOHDLC),
HashType.CRC32_AIXM => new CrcRunner(StandardDefinitions.CRC32_AIXM),
HashType.CRC32_AUTOSAR => new CrcRunner(StandardDefinitions.CRC32_AUTOSAR),
HashType.CRC32_BASE91D => new CrcRunner(StandardDefinitions.CRC32_BASE91D),
HashType.CRC32_BZIP2 => new CrcRunner(StandardDefinitions.CRC32_BZIP2),
HashType.CRC32_CDROMEDC => new CrcRunner(StandardDefinitions.CRC32_CDROMEDC),
HashType.CRC32_CKSUM => new CrcRunner(StandardDefinitions.CRC32_CKSUM),
HashType.CRC32_ISCSI => new CrcRunner(StandardDefinitions.CRC32_ISCSI),
HashType.CRC32_ISOHDLC => new CrcRunner(StandardDefinitions.CRC32_ISOHDLC),
HashType.CRC32_JAMCRC => new CrcRunner(StandardDefinitions.CRC32_JAMCRC),
HashType.CRC32_MEF => new CrcRunner(StandardDefinitions.CRC32_MEF),
HashType.CRC32_MPEG2 => new CrcRunner(StandardDefinitions.CRC32_MPEG2),
HashType.CRC32_XFER => new CrcRunner(StandardDefinitions.CRC32_XFER),
HashType.CRC4_G704 => new Crc(StandardDefinitions.CRC4_G704),
HashType.CRC4_INTERLAKEN => new Crc(StandardDefinitions.CRC4_INTERLAKEN),
HashType.CRC40_GSM => new CrcRunner(StandardDefinitions.CRC40_GSM),
HashType.CRC5_EPCC1G2 => new Crc(StandardDefinitions.CRC5_EPCC1G2),
HashType.CRC5_G704 => new Crc(StandardDefinitions.CRC5_G704),
HashType.CRC5_USB => new Crc(StandardDefinitions.CRC5_USB),
HashType.CRC64 => new CrcRunner(StandardDefinitions.CRC64_ECMA182),
HashType.CRC64_ECMA182 => new CrcRunner(StandardDefinitions.CRC64_ECMA182),
HashType.CRC64_GOISO => new CrcRunner(StandardDefinitions.CRC64_GOISO),
HashType.CRC64_MS => new CrcRunner(StandardDefinitions.CRC64_MS),
HashType.CRC64_NVME => new CrcRunner(StandardDefinitions.CRC64_NVME),
HashType.CRC64_REDIS => new CrcRunner(StandardDefinitions.CRC64_REDIS),
HashType.CRC64_WE => new CrcRunner(StandardDefinitions.CRC64_WE),
HashType.CRC64_XZ => new CrcRunner(StandardDefinitions.CRC64_XZ),
HashType.CRC6_CDMA2000A => new Crc(StandardDefinitions.CRC6_CDMA2000A),
HashType.CRC6_CDMA2000B => new Crc(StandardDefinitions.CRC6_CDMA2000B),
HashType.CRC6_DARC => new Crc(StandardDefinitions.CRC6_DARC),
HashType.CRC6_G704 => new Crc(StandardDefinitions.CRC6_G704),
HashType.CRC6_GSM => new Crc(StandardDefinitions.CRC6_GSM),
HashType.Fletcher16 => new Fletcher16Context(),
HashType.Fletcher32 => new Fletcher32Context(),
HashType.CRC7_MMC => new Crc(StandardDefinitions.CRC7_MMC),
HashType.CRC7_ROHC => new Crc(StandardDefinitions.CRC7_ROHC),
HashType.CRC7_UMTS => new Crc(StandardDefinitions.CRC7_UMTS),
HashType.CRC8 => new Crc(StandardDefinitions.CRC8_SMBUS),
HashType.CRC8_AUTOSAR => new Crc(StandardDefinitions.CRC8_AUTOSAR),
HashType.CRC8_BLUETOOTH => new Crc(StandardDefinitions.CRC8_BLUETOOTH),
HashType.CRC8_CDMA2000 => new Crc(StandardDefinitions.CRC8_CDMA2000),
HashType.CRC8_DARC => new Crc(StandardDefinitions.CRC8_DARC),
HashType.CRC8_DVBS2 => new Crc(StandardDefinitions.CRC8_DVBS2),
HashType.CRC8_GSMA => new Crc(StandardDefinitions.CRC8_GSMA),
HashType.CRC8_GSMB => new Crc(StandardDefinitions.CRC8_GSMB),
HashType.CRC8_HITAG => new Crc(StandardDefinitions.CRC8_HITAG),
HashType.CRC8_I4321 => new Crc(StandardDefinitions.CRC8_I4321),
HashType.CRC8_ICODE => new Crc(StandardDefinitions.CRC8_ICODE),
HashType.CRC8_LTE => new Crc(StandardDefinitions.CRC8_LTE),
HashType.CRC8_MAXIMDOW => new Crc(StandardDefinitions.CRC8_MAXIMDOW),
HashType.CRC8_MIFAREMAD => new Crc(StandardDefinitions.CRC8_MIFAREMAD),
HashType.CRC8_NRSC5 => new Crc(StandardDefinitions.CRC8_NRSC5),
HashType.CRC8_OPENSAFETY => new Crc(StandardDefinitions.CRC8_OPENSAFETY),
HashType.CRC8_ROHC => new Crc(StandardDefinitions.CRC8_ROHC),
HashType.CRC8_SAEJ1850 => new Crc(StandardDefinitions.CRC8_SAEJ1850),
HashType.CRC8_SMBUS => new Crc(StandardDefinitions.CRC8_SMBUS),
HashType.CRC8_TECH3250 => new Crc(StandardDefinitions.CRC8_TECH3250),
HashType.CRC8_WCDMA => new Crc(StandardDefinitions.CRC8_WCDMA),
HashType.CRC10_ATM => new Crc(StandardDefinitions.CRC10_ATM),
HashType.CRC10_CDMA2000 => new Crc(StandardDefinitions.CRC10_CDMA2000),
HashType.CRC10_GSM => new Crc(StandardDefinitions.CRC10_GSM),
HashType.CRC11_FLEXRAY => new Crc(StandardDefinitions.CRC11_FLEXRAY),
HashType.CRC11_UMTS => new Crc(StandardDefinitions.CRC11_UMTS),
HashType.CRC12_CDMA2000 => new Crc(StandardDefinitions.CRC12_CDMA2000),
HashType.CRC12_DECT => new Crc(StandardDefinitions.CRC12_DECT),
HashType.CRC12_GSM => new Crc(StandardDefinitions.CRC12_GSM),
HashType.CRC12_UMTS => new Crc(StandardDefinitions.CRC12_UMTS),
HashType.CRC13_BBC => new Crc(StandardDefinitions.CRC13_BBC),
HashType.CRC14_DARC => new Crc(StandardDefinitions.CRC14_DARC),
HashType.CRC14_GSM => new Crc(StandardDefinitions.CRC14_GSM),
HashType.CRC15_CAN => new Crc(StandardDefinitions.CRC15_CAN),
HashType.CRC15_MPT1327 => new Crc(StandardDefinitions.CRC15_MPT1327),
HashType.CRC16 => new Crc(StandardDefinitions.CRC16_ARC),
HashType.CRC16_ARC => new Crc(StandardDefinitions.CRC16_ARC),
HashType.CRC16_CDMA2000 => new Crc(StandardDefinitions.CRC16_CDMA2000),
HashType.CRC16_CMS => new Crc(StandardDefinitions.CRC16_CMS),
HashType.CRC16_DDS110 => new Crc(StandardDefinitions.CRC16_DDS110),
HashType.CRC16_DECTR => new Crc(StandardDefinitions.CRC16_DECTR),
HashType.CRC16_DECTX => new Crc(StandardDefinitions.CRC16_DECTX),
HashType.CRC16_DNP => new Crc(StandardDefinitions.CRC16_DNP),
HashType.CRC16_EN13757 => new Crc(StandardDefinitions.CRC16_EN13757),
HashType.CRC16_GENIBUS => new Crc(StandardDefinitions.CRC16_GENIBUS),
HashType.CRC16_GSM => new Crc(StandardDefinitions.CRC16_GSM),
HashType.CRC16_IBM3740 => new Crc(StandardDefinitions.CRC16_IBM3740),
HashType.CRC16_IBMSDLC => new Crc(StandardDefinitions.CRC16_IBMSDLC),
HashType.CRC16_ISOIEC144433A => new Crc(StandardDefinitions.CRC16_ISOIEC144433A),
HashType.CRC16_KERMIT => new Crc(StandardDefinitions.CRC16_KERMIT),
HashType.CRC16_LJ1200 => new Crc(StandardDefinitions.CRC16_LJ1200),
HashType.CRC16_M17 => new Crc(StandardDefinitions.CRC16_M17),
HashType.CRC16_MAXIMDOW => new Crc(StandardDefinitions.CRC16_MAXIMDOW),
HashType.CRC16_MCRF4XX => new Crc(StandardDefinitions.CRC16_MCRF4XX),
HashType.CRC16_MODBUS => new Crc(StandardDefinitions.CRC16_MODBUS),
HashType.CRC16_NRSC5 => new Crc(StandardDefinitions.CRC16_NRSC5),
HashType.CRC16_OPENSAFETYA => new Crc(StandardDefinitions.CRC16_OPENSAFETYA),
HashType.CRC16_OPENSAFETYB => new Crc(StandardDefinitions.CRC16_OPENSAFETYB),
HashType.CRC16_PROFIBUS => new Crc(StandardDefinitions.CRC16_PROFIBUS),
HashType.CRC16_RIELLO => new Crc(StandardDefinitions.CRC16_RIELLO),
HashType.CRC16_SPIFUJITSU => new Crc(StandardDefinitions.CRC16_SPIFUJITSU),
HashType.CRC16_T10DIF => new Crc(StandardDefinitions.CRC16_T10DIF),
HashType.CRC16_TELEDISK => new Crc(StandardDefinitions.CRC16_TELEDISK),
HashType.CRC16_TMS37157 => new Crc(StandardDefinitions.CRC16_TMS37157),
HashType.CRC16_UMTS => new Crc(StandardDefinitions.CRC16_UMTS),
HashType.CRC16_USB => new Crc(StandardDefinitions.CRC16_USB),
HashType.CRC16_XMODEM => new Crc(StandardDefinitions.CRC16_XMODEM),
HashType.CRC17_CANFD => new Crc(StandardDefinitions.CRC17_CANFD),
HashType.CRC21_CANFD => new Crc(StandardDefinitions.CRC21_CANFD),
HashType.CRC24_BLE => new Crc(StandardDefinitions.CRC24_BLE),
HashType.CRC24_FLEXRAYA => new Crc(StandardDefinitions.CRC24_FLEXRAYA),
HashType.CRC24_FLEXRAYB => new Crc(StandardDefinitions.CRC24_FLEXRAYB),
HashType.CRC24_INTERLAKEN => new Crc(StandardDefinitions.CRC24_INTERLAKEN),
HashType.CRC24_LTEA => new Crc(StandardDefinitions.CRC24_LTEA),
HashType.CRC24_LTEB => new Crc(StandardDefinitions.CRC24_LTEB),
HashType.CRC24_OPENPGP => new Crc(StandardDefinitions.CRC24_OPENPGP),
HashType.CRC24_OS9 => new Crc(StandardDefinitions.CRC24_OS9),
HashType.CRC30_CDMA => new Crc(StandardDefinitions.CRC30_CDMA),
HashType.CRC31_PHILIPS => new Crc(StandardDefinitions.CRC31_PHILIPS),
HashType.CRC32 => new Crc(StandardDefinitions.CRC32_ISOHDLC),
HashType.CRC32_AIXM => new Crc(StandardDefinitions.CRC32_AIXM),
HashType.CRC32_AUTOSAR => new Crc(StandardDefinitions.CRC32_AUTOSAR),
HashType.CRC32_BASE91D => new Crc(StandardDefinitions.CRC32_BASE91D),
HashType.CRC32_BZIP2 => new Crc(StandardDefinitions.CRC32_BZIP2),
HashType.CRC32_CDROMEDC => new Crc(StandardDefinitions.CRC32_CDROMEDC),
HashType.CRC32_CKSUM => new Crc(StandardDefinitions.CRC32_CKSUM),
HashType.CRC32_DVDROMEDC => new Crc(StandardDefinitions.CRC32_DVDROMEDC),
HashType.CRC32_ISCSI => new Crc(StandardDefinitions.CRC32_ISCSI),
HashType.CRC32_ISOHDLC => new Crc(StandardDefinitions.CRC32_ISOHDLC),
HashType.CRC32_JAMCRC => new Crc(StandardDefinitions.CRC32_JAMCRC),
HashType.CRC32_MEF => new Crc(StandardDefinitions.CRC32_MEF),
HashType.CRC32_MPEG2 => new Crc(StandardDefinitions.CRC32_MPEG2),
HashType.CRC32_XFER => new Crc(StandardDefinitions.CRC32_XFER),
HashType.CRC40_GSM => new Crc(StandardDefinitions.CRC40_GSM),
HashType.CRC64 => new Crc(StandardDefinitions.CRC64_ECMA182),
HashType.CRC64_ECMA182 => new Crc(StandardDefinitions.CRC64_ECMA182),
HashType.CRC64_GOISO => new Crc(StandardDefinitions.CRC64_GOISO),
HashType.CRC64_MS => new Crc(StandardDefinitions.CRC64_MS),
HashType.CRC64_NVME => new Crc(StandardDefinitions.CRC64_NVME),
HashType.CRC64_REDIS => new Crc(StandardDefinitions.CRC64_REDIS),
HashType.CRC64_WE => new Crc(StandardDefinitions.CRC64_WE),
HashType.CRC64_XZ => new Crc(StandardDefinitions.CRC64_XZ),
HashType.Fletcher16 => new Fletcher16(),
HashType.Fletcher32 => new Fletcher32(),
HashType.Fletcher64 => new Fletcher64(),
HashType.FNV0_32 => new FNV0_32(),
HashType.FNV0_64 => new FNV0_64(),
HashType.FNV1_32 => new FNV1_32(),
HashType.FNV1_64 => new FNV1_64(),
HashType.FNV1a_32 => new FNV1a_32(),
HashType.FNV1a_64 => new FNV1a_64(),
HashType.MekaCrc => new MekaCrc(),
HashType.MD2 => new MD2(),
HashType.MD4 => new MD4(),
HashType.MD5 => MD5.Create(),
#if NETFRAMEWORK
HashType.RIPEMD160 => RIPEMD160.Create(),
#endif
HashType.RIPEMD128 => new RipeMD128(),
HashType.RIPEMD160 => new RipeMD160(),
HashType.RIPEMD256 => new RipeMD256(),
HashType.RIPEMD320 => new RipeMD320(),
HashType.SHA1 => SHA1.Create(),
HashType.SHA256 => SHA256.Create(),
@@ -198,12 +260,27 @@ namespace SabreTools.Hashing
HashType.SHAKE128 => Shake128.IsSupported ? new Shake128() : null,
HashType.SHAKE256 => Shake256.IsSupported ? new Shake256() : null,
#endif
HashType.SpamSum => new SpamSumContext(),
#if NET462_OR_GREATER || NETCOREAPP
HashType.SpamSum => new SpamSum.SpamSum(),
HashType.Tiger128_3 => new Tiger128_3(),
HashType.Tiger128_4 => new Tiger128_4(),
HashType.Tiger160_3 => new Tiger160_3(),
HashType.Tiger160_4 => new Tiger160_4(),
HashType.Tiger192_3 => new Tiger192_3(),
HashType.Tiger192_4 => new Tiger192_4(),
HashType.Tiger2_128_3 => new Tiger2_128_3(),
HashType.Tiger2_128_4 => new Tiger2_128_4(),
HashType.Tiger2_160_3 => new Tiger2_160_3(),
HashType.Tiger2_160_4 => new Tiger2_160_4(),
HashType.Tiger2_192_3 => new Tiger2_192_3(),
HashType.Tiger2_192_4 => new Tiger2_192_4(),
HashType.XxHash32 => new XxHash32(),
HashType.XxHash64 => new XxHash64(),
HashType.XxHash3 => new XxHash3(),
HashType.XxHash128 => new XxHash128(),
#if NET462_OR_GREATER || NETCOREAPP
HashType.XxHash3 => new System.IO.Hashing.XxHash3(),
HashType.XxHash128 => new System.IO.Hashing.XxHash128(),
#endif
_ => null,
};
@@ -227,22 +304,12 @@ namespace SabreTools.Hashing
{
switch (_hasher)
{
case CrcRunner cr:
cr.TransformBlock(buffer, offset, size);
break;
case HashAlgorithm ha:
ha.TransformBlock(buffer, offset, size, null, 0);
break;
case IChecksum ic:
byte[] icBlock = new byte[size];
Array.Copy(buffer, offset, icBlock, 0, size);
ic.Update(icBlock);
break;
#if NET462_OR_GREATER || NETCOREAPP
case NonCryptographicHashAlgorithm ncha:
case System.IO.Hashing.NonCryptographicHashAlgorithm ncha:
var nchaBufferSpan = new ReadOnlySpan<byte>(buffer, offset, size);
ncha.Append(nchaBufferSpan);
break;
@@ -253,12 +320,15 @@ namespace SabreTools.Hashing
var s128BufferSpan = new ReadOnlySpan<byte>(buffer, offset, size);
s128.AppendData(s128BufferSpan);
break;
case Shake256 s256:
var s256BufferSpan = new ReadOnlySpan<byte>(buffer, offset, size);
s256.AppendData(s256BufferSpan);
break;
#endif
default:
// No-op
break;
}
}
@@ -274,36 +344,43 @@ namespace SabreTools.Hashing
case HashAlgorithm ha:
ha.TransformFinalBlock(emptyBuffer, 0, 0);
break;
default:
// No-op
break;
}
}
#endregion
/// <summary>
/// Get the variable-length string representing a CRC value
/// </summary>
/// <param name="cr">Crc to get the value from</param>
/// <returns>String representing the CRC, null on error</returns>
private static string? GetCRCVariableLengthString(Crc cr)
{
// Ignore null values
if (cr.Hash is null)
return null;
#region Helpers
// Get the total number of characters needed
ulong hash = BytesToUInt64(cr.Hash);
int length = (cr.Def.Width / 4) + (cr.Def.Width % 4 > 0 ? 1 : 0);
return hash.ToString($"x{length}");
}
/// <summary>
/// Convert a byte array to a hex string
/// Get the Base64 representation of a SpamSum value
/// </summary>
/// <param name="bytes">Byte array to convert</param>
/// <returns>Hex string representing the byte array</returns>
/// <link>http://stackoverflow.com/questions/311165/how-do-you-convert-byte-array-to-hexadecimal-string-and-vice-versa</link>
private static string? ByteArrayToString(byte[]? bytes)
/// <param name="ss">SpamSum to get the value from</param>
/// <returns>String representing the SpamSum, null on error</returns>
private static string? GetSpamSumBase64String(SpamSum.SpamSum ss)
{
// If we get null in, we send null out
if (bytes == null)
// Ignore null values
if (ss.Hash is null)
return null;
try
{
string hex = BitConverter.ToString(bytes);
return hex.Replace("-", string.Empty).ToLowerInvariant();
}
catch
{
return null;
}
return System.Text.Encoding.ASCII.GetString(ss.Hash);
}
#endregion
}
}
}

View File

@@ -0,0 +1,43 @@
namespace SabreTools.Hashing.NonCryptographicHash
{
internal static class Constants
{
#region FNV
public const uint FNV32Basis = 0x811c9dc5;
public const ulong FNV64Basis = 0xcbf29ce484222325;
public const uint FNV32Prime = 0x01000193;
public const ulong FNV64Prime = 0x00000100000001b3;
#endregion
#region xxHash-32
public const uint XXH_PRIME32_1 = 0x9E3779B1;
public const uint XXH_PRIME32_2 = 0x85EBCA77;
public const uint XXH_PRIME32_3 = 0xC2B2AE3D;
public const uint XXH_PRIME32_4 = 0x27D4EB2F;
public const uint XXH_PRIME32_5 = 0x165667B1;
#endregion
#region xxHash-64
public const ulong XXH_PRIME64_1 = 0x9E3779B185EBCA87;
public const ulong XXH_PRIME64_2 = 0xC2B2AE3D27D4EB4F;
public const ulong XXH_PRIME64_3 = 0x165667B19E3779F9;
public const ulong XXH_PRIME64_4 = 0x85EBCA77C2B2AE63;
public const ulong XXH_PRIME64_5 = 0x27D4EB2F165667C5;
#endregion
}
}

View File

@@ -0,0 +1,26 @@
using static SabreTools.Hashing.NonCryptographicHash.Constants;
namespace SabreTools.Hashing.NonCryptographicHash
{
public class FNV0_32 : FnvBase<uint>
{
/// <inheritdoc/>
public override int HashSize => 32;
public FNV0_32()
{
_basis = 0;
_prime = FNV32Prime;
Initialize();
}
/// <inheritdoc/>
protected override void HashCore(byte[] data, int offset, int length)
{
for (int i = offset; length > 0; i++, length--)
{
_hash = (_hash * _prime) ^ data[i];
}
}
}
}

View File

@@ -0,0 +1,26 @@
using static SabreTools.Hashing.NonCryptographicHash.Constants;
namespace SabreTools.Hashing.NonCryptographicHash
{
public class FNV0_64 : FnvBase<ulong>
{
/// <inheritdoc/>
public override int HashSize => 64;
public FNV0_64()
{
_basis = 0;
_prime = FNV64Prime;
Initialize();
}
/// <inheritdoc/>
protected override void HashCore(byte[] data, int offset, int length)
{
for (int i = offset; length > 0; i++, length--)
{
_hash = (_hash * _prime) ^ data[i];
}
}
}
}

View File

@@ -0,0 +1,26 @@
using static SabreTools.Hashing.NonCryptographicHash.Constants;
namespace SabreTools.Hashing.NonCryptographicHash
{
public class FNV1_32 : FnvBase<uint>
{
/// <inheritdoc/>
public override int HashSize => 32;
public FNV1_32()
{
_basis = FNV32Basis;
_prime = FNV32Prime;
Initialize();
}
/// <inheritdoc/>
protected override void HashCore(byte[] data, int offset, int length)
{
for (int i = offset; length > 0; i++, length--)
{
_hash = (_hash * _prime) ^ data[i];
}
}
}
}

View File

@@ -0,0 +1,26 @@
using static SabreTools.Hashing.NonCryptographicHash.Constants;
namespace SabreTools.Hashing.NonCryptographicHash
{
public class FNV1_64 : FnvBase<ulong>
{
/// <inheritdoc/>
public override int HashSize => 64;
public FNV1_64()
{
_basis = FNV64Basis;
_prime = FNV64Prime;
Initialize();
}
/// <inheritdoc/>
protected override void HashCore(byte[] data, int offset, int length)
{
for (int i = offset; length > 0; i++, length--)
{
_hash = (_hash * _prime) ^ data[i];
}
}
}
}

View File

@@ -0,0 +1,26 @@
using static SabreTools.Hashing.NonCryptographicHash.Constants;
namespace SabreTools.Hashing.NonCryptographicHash
{
public class FNV1a_32 : FnvBase<uint>
{
/// <inheritdoc/>
public override int HashSize => 32;
public FNV1a_32()
{
_basis = FNV32Basis;
_prime = FNV32Prime;
Initialize();
}
/// <inheritdoc/>
protected override void HashCore(byte[] data, int offset, int length)
{
for (int i = offset; length > 0; i++, length--)
{
_hash = (_hash ^ data[i]) * _prime;
}
}
}
}

View File

@@ -0,0 +1,26 @@
using static SabreTools.Hashing.NonCryptographicHash.Constants;
namespace SabreTools.Hashing.NonCryptographicHash
{
public class FNV1a_64 : FnvBase<ulong>
{
/// <inheritdoc/>
public override int HashSize => 64;
public FNV1a_64()
{
_basis = FNV64Basis;
_prime = FNV64Prime;
Initialize();
}
/// <inheritdoc/>
protected override void HashCore(byte[] data, int offset, int length)
{
for (int i = offset; length > 0; i++, length--)
{
_hash = (_hash ^ data[i]) * _prime;
}
}
}
}

View File

@@ -0,0 +1,60 @@
using System;
namespace SabreTools.Hashing.NonCryptographicHash
{
/// <summary>
/// Common base class for FNV non-cryptographic hashes
/// </summary>
public abstract class FnvBase : System.Security.Cryptography.HashAlgorithm
{
// No common, untyped functionality
}
/// <summary>
/// Common base class for FNV non-cryptographic hashes
/// </summary>
public abstract class FnvBase<T> : FnvBase where T : struct
{
/// <summary>
/// Initial value to use
/// </summary>
protected T _basis;
/// <summary>
/// Round prime to use
/// </summary>
protected T _prime;
/// <summary>
/// The current value of the hash
/// </summary>
protected T _hash;
/// <inheritdoc/>
public override void Initialize()
{
_hash = _basis;
}
/// <inheritdoc/>
protected override byte[] HashFinal()
{
byte[] hashArr = _hash switch
{
short s => BitConverter.GetBytes(s),
ushort s => BitConverter.GetBytes(s),
int i => BitConverter.GetBytes(i),
uint i => BitConverter.GetBytes(i),
long l => BitConverter.GetBytes(l),
ulong l => BitConverter.GetBytes(l),
_ => [],
};
Array.Reverse(hashArr);
return hashArr;
}
}
}

View File

@@ -0,0 +1,46 @@
using System;
namespace SabreTools.Hashing.NonCryptographicHash
{
public class XxHash32 : System.Security.Cryptography.HashAlgorithm
{
/// <inheritdoc/>
public override int HashSize => 32;
/// <summary>
/// The 32-bit seed to alter the hash result predictably.
/// </summary>
private readonly uint _seed;
/// <summary>
/// Internal xxHash-32 state
/// </summary>
private readonly XxHash32State _state;
public XxHash32(uint seed = 0)
{
_seed = seed;
_state = new XxHash32State();
_state.Reset(seed);
}
/// <inheritdoc/>
public override void Initialize()
{
_state.Reset(_seed);
}
/// <inheritdoc/>
protected override void HashCore(byte[] data, int offset, int length)
=> _state.Update(data, offset, length);
/// <inheritdoc/>
protected override byte[] HashFinal()
{
uint hash = _state.Digest();
byte[] hashArr = BitConverter.GetBytes(hash);
Array.Reverse(hashArr);
return hashArr;
}
}
}

View File

@@ -0,0 +1,204 @@
using System;
using static SabreTools.Hashing.HashOperations;
using static SabreTools.Hashing.NonCryptographicHash.Constants;
namespace SabreTools.Hashing.NonCryptographicHash
{
/// <summary>
/// Structure for xxHash-32 streaming API.
/// </summary>
/// <see href="https://github.com/Cyan4973/xxHash/blob/dev/xxhash.h"/>
internal class XxHash32State
{
/// <summary>
/// Total length hashed, modulo 2^32
/// </summary>
private uint _totalLen32;
/// <summary>
/// Whether the hash is >= 16 (handles <see cref="_totalLen32"/> overflow)
/// </summary>
private bool _largeLen;
/// <summary>
/// Accumulator lanes
/// </summary>
private readonly uint[] _acc = new uint[4];
/// <summary>
/// Internal buffer for partial reads. Treated as unsigned char[16].
/// </summary>
private readonly byte[] _mem32 = new byte[16];
/// <summary>
/// Amount of data in <see cref="_mem32">
/// </summary>
private int _memsize;
/// <summary>
/// Resets to begin a new hash
/// </summary>
/// <param name="seed">The 32-bit seed to alter the hash result predictably.</param>
public void Reset(uint seed)
{
_totalLen32 = 0;
_largeLen = false;
unchecked
{
_acc[0] = seed + XXH_PRIME32_1 + XXH_PRIME32_2;
_acc[1] = seed + XXH_PRIME32_2;
_acc[2] = seed + 0;
_acc[3] = seed - XXH_PRIME32_1;
}
Array.Clear(_mem32, 0, _mem32.Length);
_memsize = 0;
}
/// <summary>
/// Consumes a block of input
/// </summary>
/// <param name="data">Byte array representing the data</param>
/// <param name="offset">Offset in the byte array to include</param>
/// <param name="length">Length of the data to hash</param>
public void Update(byte[] data, int offset, int length)
{
int bEnd = offset + length;
_totalLen32 += (uint)length;
_largeLen |= (length >= 16) | (_totalLen32 >= 16);
// Fill in tmp buffer
if (_memsize + length < 16)
{
Array.Copy(data, offset, _mem32, _memsize, length);
_memsize += length;
return;
}
// Some data left from previous update
if (_memsize > 0)
{
Array.Copy(data, offset, _mem32, _memsize, 16 - _memsize);
int p32 = 0;
_acc[0] = Round(_acc[0], ReadLE32(_mem32, p32)); p32 += 4;
_acc[1] = Round(_acc[1], ReadLE32(_mem32, p32)); p32 += 4;
_acc[2] = Round(_acc[2], ReadLE32(_mem32, p32)); p32 += 4;
_acc[3] = Round(_acc[3], ReadLE32(_mem32, p32));
offset += 16 - _memsize;
_memsize = 0;
}
if (offset <= bEnd - 16)
{
int limit = bEnd - 16;
do
{
_acc[0] = Round(_acc[0], ReadLE32(data, offset)); offset += 4;
_acc[1] = Round(_acc[1], ReadLE32(data, offset)); offset += 4;
_acc[2] = Round(_acc[2], ReadLE32(data, offset)); offset += 4;
_acc[3] = Round(_acc[3], ReadLE32(data, offset)); offset += 4;
} while (offset <= limit);
}
if (offset < bEnd)
{
Array.Copy(data, offset, _mem32, 0, bEnd - offset);
_memsize = bEnd - offset;
}
}
/// <summary>
/// Returns the calculated hash value
/// </summary>
/// <returns>The calculated 32-bit xxHash32 value from that state.</returns>
public uint Digest()
{
uint hash;
if (_largeLen)
{
hash = RotateLeft32(_acc[0], 1)
+ RotateLeft32(_acc[1], 7)
+ RotateLeft32(_acc[2], 12)
+ RotateLeft32(_acc[3], 18);
}
else
{
hash = _acc[2] /* == seed */ + XXH_PRIME32_5;
}
hash += _totalLen32;
return Finalize(hash, _mem32, 0, _memsize);
}
/// <summary>
/// Normal stripe processing routine.
///
/// This shuffles the bits so that any bit from <paramref name="input"/> impacts
/// several bits in <paramref name="acc"/>.
/// </summary>
/// <param name="acc">The accumulator lane.</param>
/// <param name="input">The stripe of input to mix.</param>
/// <returns>The mixed accumulator lane.</returns>
private static uint Round(uint acc, uint input)
{
acc += input * XXH_PRIME32_2;
acc = RotateLeft32(acc, 13);
acc *= XXH_PRIME32_1;
return acc;
}
/// <summary>
/// Mixes all bits to finalize the hash.
///
/// The final mix ensures that all input bits have a chance to impact any bit in
/// the output digest, resulting in an unbiased distribution.
/// </summary>
private static uint Avalanche(uint hash)
{
hash ^= hash >> 15;
hash *= XXH_PRIME32_2;
hash ^= hash >> 13;
hash *= XXH_PRIME32_3;
hash ^= hash >> 16;
return hash;
}
/// <summary>
/// Processes the last 0-15 bytes of @p ptr.
///
/// There may be up to 15 bytes remaining to consume from the input.
/// This final stage will digest them to ensure that all input bytes are present
/// in the final mix.
/// </summary>
/// <param name="hash">The hash to finalize.</param>
/// <param name="data">The remaining input.</param>
/// <param name="offset">The pointer to the remaining input.</param>
/// <param name="length">The remaining length, modulo 16.</param>
/// <returns>The finalized hash.</returns>
private static uint Finalize(uint hash, byte[] data, int offset, int length)
{
length &= 15;
while (length >= 4)
{
hash += ReadLE32(data, offset) * XXH_PRIME32_3;
offset += 4;
hash = RotateLeft32(hash, 17) * XXH_PRIME32_4;
length -= 4;
}
while (length > 0)
{
hash += data[offset++] * XXH_PRIME32_5;
hash = RotateLeft32(hash, 11) * XXH_PRIME32_1;
--length;
}
return Avalanche(hash);
}
}
}

View File

@@ -0,0 +1,46 @@
using System;
namespace SabreTools.Hashing.NonCryptographicHash
{
public class XxHash64 : System.Security.Cryptography.HashAlgorithm
{
/// <inheritdoc/>
public override int HashSize => 64;
/// <summary>
/// The 64-bit seed to alter the hash result predictably.
/// </summary>
private readonly uint _seed;
/// <summary>
/// Internal xxHash-64 state
/// </summary>
private readonly XxHash64State _state;
public XxHash64(uint seed = 0)
{
_seed = seed;
_state = new XxHash64State();
_state.Reset(seed);
}
/// <inheritdoc/>
public override void Initialize()
{
_state.Reset(_seed);
}
/// <inheritdoc/>
protected override void HashCore(byte[] data, int offset, int length)
=> _state.Update(data, offset, length);
/// <inheritdoc/>
protected override byte[] HashFinal()
{
ulong hash = _state.Digest();
byte[] hashArr = BitConverter.GetBytes(hash);
Array.Reverse(hashArr);
return hashArr;
}
}
}

View File

@@ -0,0 +1,219 @@
using System;
using static SabreTools.Hashing.HashOperations;
using static SabreTools.Hashing.NonCryptographicHash.Constants;
namespace SabreTools.Hashing.NonCryptographicHash
{
/// <summary>
/// Structure for xxHash-64 streaming API.
/// </summary>
/// <see href="https://github.com/Cyan4973/xxHash/blob/dev/xxhash.h"/>
internal class XxHash64State
{
/// <summary>
/// Total length hashed. This is always 64-bit.
/// </summary>
private ulong _totalLen;
/// <summary>
/// Accumulator lanes
/// </summary>
private readonly ulong[] _acc = new ulong[4];
/// <summary>
/// Internal buffer for partial reads. Treated as unsigned char[32].
/// </summary>
private readonly byte[] _mem64 = new byte[32];
/// <summary>
/// Amount of data in <see cref="_mem64">
/// </summary>
private int _memsize;
/// <summary>
/// Resets to begin a new hash
/// </summary>
/// <param name="seed">The 64-bit seed to alter the hash result predictably.</param>
public void Reset(ulong seed)
{
_totalLen = 0;
unchecked
{
_acc[0] = seed + XXH_PRIME64_1 + XXH_PRIME64_2;
_acc[1] = seed + XXH_PRIME64_2;
_acc[2] = seed + 0;
_acc[3] = seed - XXH_PRIME64_1;
}
Array.Clear(_mem64, 0, _mem64.Length);
_memsize = 0;
}
/// <summary>
/// Consumes a block of input
/// </summary>
/// <param name="data">Byte array representing the data</param>
/// <param name="offset">Offset in the byte array to include</param>
/// <param name="length">Length of the data to hash</param>
public void Update(byte[] data, int offset, int length)
{
int bEnd = offset + length;
_totalLen += (ulong)length;
// Fill in tmp buffer
if (_memsize + length < 32)
{
Array.Copy(data, offset, _mem64, _memsize, length);
_memsize += length;
return;
}
// Some data left from previous update
if (_memsize > 0)
{
Array.Copy(data, offset, _mem64, _memsize, 32 - _memsize);
int p64 = 0;
_acc[0] = Round(_acc[0], ReadLE64(_mem64, p64)); p64 += 8;
_acc[1] = Round(_acc[1], ReadLE64(_mem64, p64)); p64 += 8;
_acc[2] = Round(_acc[2], ReadLE64(_mem64, p64)); p64 += 8;
_acc[3] = Round(_acc[3], ReadLE64(_mem64, p64));
offset += 32 - _memsize;
_memsize = 0;
}
if (offset <= bEnd - 32)
{
int limit = bEnd - 32;
do
{
_acc[0] = Round(_acc[0], ReadLE64(data, offset)); offset += 8;
_acc[1] = Round(_acc[1], ReadLE64(data, offset)); offset += 8;
_acc[2] = Round(_acc[2], ReadLE64(data, offset)); offset += 8;
_acc[3] = Round(_acc[3], ReadLE64(data, offset)); offset += 8;
} while (offset <= limit);
}
if (offset < bEnd)
{
Array.Copy(data, offset, _mem64, 0, bEnd - offset);
_memsize = bEnd - offset;
}
}
/// <summary>
/// Returns the calculated hash value
/// </summary>
/// <returns>The calculated 64-bit xxHash64 value from that state.</returns>
public ulong Digest()
{
ulong h64;
if (_totalLen >= 32)
{
h64 = RotateLeft64(_acc[0], 1)
+ RotateLeft64(_acc[1], 7)
+ RotateLeft64(_acc[2], 12)
+ RotateLeft64(_acc[3], 18);
h64 = MergeRound(h64, _acc[0]);
h64 = MergeRound(h64, _acc[1]);
h64 = MergeRound(h64, _acc[2]);
h64 = MergeRound(h64, _acc[3]);
}
else
{
h64 = _acc[2] /*seed*/ + XXH_PRIME64_5;
}
h64 += _totalLen;
return Finalize(h64, _mem64, 0, (int)_totalLen);
}
/// <summary>
/// Normal stripe processing routine.
///
/// This shuffles the bits so that any bit from @p input impacts
/// several bits in @p acc.
/// </summary>
/// <param name="acc">The accumulator lane.</param>
/// <param name="input">The stripe of input to mix.</param>
/// <returns>The mixed accumulator lane.</returns>
private static ulong Round(ulong acc, ulong input)
{
acc += unchecked(input * XXH_PRIME64_2);
acc = RotateLeft64(acc, 31);
acc *= XXH_PRIME64_1;
return acc;
}
private static ulong MergeRound(ulong acc, ulong val)
{
val = Round(0, val);
acc ^= val;
acc = (acc * XXH_PRIME64_1) + XXH_PRIME64_4;
return acc;
}
/// <summary>
/// Processes the last 0-31 bytes of @p ptr.
///
/// There may be up to 31 bytes remaining to consume from the input.
/// This final stage will digest them to ensure that all input bytes are present
/// in the final mix.
/// </summary>
/// <param name="hash">The hash to finalize.</param>
/// <param name="data">The pointer to the remaining input.</param>
/// <param name="offset">The pointer to the remaining input.</param>
/// <param name="length">The remaining length, modulo 32.</param>
/// <param name="align">Whether @p ptr is aligned.</param>
/// <returns>The finalized hash</returns>
private static ulong Finalize(ulong hash, byte[] data, int offset, int length)
{
length &= 31;
while (length >= 8)
{
ulong k1 = Round(0, ReadLE64(data, offset));
offset += 8;
hash ^= k1;
hash = (RotateLeft64(hash, 27) * XXH_PRIME64_1) + XXH_PRIME64_4;
length -= 8;
}
if (length >= 4)
{
hash ^= ReadLE32(data, offset) * XXH_PRIME64_1;
offset += 4;
hash = (RotateLeft64(hash, 23) * XXH_PRIME64_2) + XXH_PRIME64_3;
length -= 4;
}
while (length > 0)
{
hash ^= data[offset++] * XXH_PRIME64_5;
hash = RotateLeft64(hash, 11) * XXH_PRIME64_1;
--length;
}
return Avalanche(hash);
}
/// <summary>
/// Mixes all bits to finalize the hash.
///
/// The final mix ensures that all input bits have a chance to impact any bit in
/// the output digest, resulting in an unbiased distribution.
/// </summary>
private static ulong Avalanche(ulong hash)
{
hash ^= hash >> 33;
hash *= XXH_PRIME64_2;
hash ^= hash >> 29;
hash *= XXH_PRIME64_3;
hash ^= hash >> 32;
return hash;
}
}
}

View File

@@ -1,20 +1,21 @@
<Project Sdk="Microsoft.NET.Sdk">
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<!-- Assembly Properties -->
<TargetFrameworks>net20;net35;net40;net452;net462;net472;net48;netcoreapp3.1;net5.0;net6.0;net7.0;net8.0</TargetFrameworks>
<TargetFrameworks>net20;net35;net40;net452;net462;net472;net48;netcoreapp3.1;net5.0;net6.0;net7.0;net8.0;net9.0;net10.0;netstandard2.0;netstandard2.1</TargetFrameworks>
<CheckEolTargetFramework>false</CheckEolTargetFramework>
<IncludeSourceRevisionInInformationalVersion>false</IncludeSourceRevisionInInformationalVersion>
<IncludeSymbols>true</IncludeSymbols>
<LangVersion>latest</LangVersion>
<Nullable>enable</Nullable>
<SuppressTfmSupportBuildWarnings>true</SuppressTfmSupportBuildWarnings>
<SymbolPackageFormat>snupkg</SymbolPackageFormat>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<Version>1.2.3</Version>
<WarningsNotAsErrors>NU5104</WarningsNotAsErrors>
<Version>1.6.0</Version>
<!-- Package Properties -->
<Authors>Matt Nadareski</Authors>
<Copyright>Copyright (c)2016-2024 Matt Nadareski</Copyright>
<Copyright>Copyright (c)2016-2025 Matt Nadareski</Copyright>
<PackageProjectUrl>https://github.com/SabreTools/</PackageProjectUrl>
<PackageReadmeFile>README.md</PackageReadmeFile>
<RepositoryUrl>https://github.com/SabreTools/SabreTools.Hashing</RepositoryUrl>
@@ -23,34 +24,14 @@
<PackageLicenseExpression>MIT</PackageLicenseExpression>
</PropertyGroup>
<!-- Support All Frameworks -->
<PropertyGroup Condition="$(TargetFramework.StartsWith(`net2`)) OR $(TargetFramework.StartsWith(`net3`)) OR $(TargetFramework.StartsWith(`net4`))">
<RuntimeIdentifiers>win-x86;win-x64</RuntimeIdentifiers>
</PropertyGroup>
<PropertyGroup Condition="$(TargetFramework.StartsWith(`netcoreapp`)) OR $(TargetFramework.StartsWith(`net5`))">
<RuntimeIdentifiers>win-x86;win-x64;win-arm64;linux-x64;linux-arm64;osx-x64</RuntimeIdentifiers>
</PropertyGroup>
<PropertyGroup Condition="$(TargetFramework.StartsWith(`net6`)) OR $(TargetFramework.StartsWith(`net7`)) OR $(TargetFramework.StartsWith(`net8`))">
<RuntimeIdentifiers>win-x86;win-x64;win-arm64;linux-x64;linux-arm64;osx-x64;osx-arm64</RuntimeIdentifiers>
</PropertyGroup>
<PropertyGroup Condition="$(RuntimeIdentifier.StartsWith(`osx-arm`))">
<TargetFrameworks>net6.0;net7.0;net8.0</TargetFrameworks>
</PropertyGroup>
<ItemGroup>
<None Include="../README.md" Pack="true" PackagePath="" />
</ItemGroup>
<!-- Support for old .NET versions -->
<ItemGroup Condition="!$(TargetFramework.StartsWith(`net2`)) AND !$(TargetFramework.StartsWith(`net3`)) AND !$(TargetFramework.StartsWith(`net40`)) AND !$(TargetFramework.StartsWith(`net45`))">
<PackageReference Include="System.IO.Hashing" Version="8.0.0" />
</ItemGroup>
<ItemGroup Condition="$(TargetFramework.StartsWith(`net7`)) OR $(TargetFramework.StartsWith(`net8`))">
<PackageReference Include="Blake3" Version="1.1.0" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Aaru.Checksums.Native" Version="6.0.0-alpha9" />
<PackageReference Include="Blake3" Version="1.1.0" Condition="$(TargetFramework.StartsWith(`net7`))" />
<PackageReference Include="Blake3" Version="2.0.0" Condition="$(TargetFramework.StartsWith(`net8`)) OR $(TargetFramework.StartsWith(`net9`)) OR $(TargetFramework.StartsWith(`net10`))" />
<PackageReference Include="System.IO.Hashing" Version="10.0.0" Condition="!$(TargetFramework.StartsWith(`net2`)) AND !$(TargetFramework.StartsWith(`net3`)) AND !$(TargetFramework.StartsWith(`net40`)) AND !$(TargetFramework.StartsWith(`net45`))" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,45 @@
using static SabreTools.Hashing.SpamSum.Constants;
namespace SabreTools.Hashing.SpamSum
{
/// <summary>
/// A blockhash contains a signature state for a specific (implicit) blocksize.
/// The blocksize is given by <see cref="SSDEEP_BS(uint)"/>
/// </summary>
/// <see href="https://github.com/ssdeep-project/ssdeep/blob/master/fuzzy.c"/>
internal class BlockhashContext
{
/// <summary>
/// Current digest length
/// </summary>
public uint DIndex { get; set; }
/// <summary>
/// Current message digest
/// </summary>
public byte[] Digest { get; set; }
/// <summary>
/// Digest value at <see cref="HalfH"/>
/// </summary>
public byte HalfDigest { get; set; }
/// <summary>
/// Partial FNV hash
/// </summary>
public byte H { get; set; }
/// <summary>
/// Partial FNV hash reset after <see cref="Digest"/> is
/// <see cref="SPAMSUM_LENGTH"/> / 2 long. This is needed
/// to be able to truncate digest for the second output hash
/// to stay compatible with ssdeep output.
/// </summary>
public byte HalfH { get; set; }
public BlockhashContext()
{
Digest = new byte[SPAMSUM_LENGTH];
}
}
}

View File

@@ -0,0 +1,201 @@
using System;
using System.Text.RegularExpressions;
namespace SabreTools.Hashing.SpamSum;
internal static class Comparisons
{
/// <summary>
/// Regex to reduce any sequences longer than 3
/// </summary>
private static readonly Regex _reduceRegex = new("(.)(?<=\\1\\1\\1\\1)", RegexOptions.Compiled);
/// <summary>
/// Compares how similar two SpamSums are to each other
/// </summary>
/// <param name="first">First hash to compare</param>
/// <param name="second">Second hash to compare</param>
/// <returns>-1 on validity failure, 0 if they're not comparable, score from 0 (least similar) to 100 (most similar) otherwise.</returns>
/// <remarks>Implements ssdeep's fuzzy_compare</remarks>
/// <see href="https://github.com/ssdeep-project/ssdeep/blob/df3b860f8918261b3faeec9c7d2c8a241089e6e6/fuzzy.c#L860"/>
public static int FuzzyCompare(string? first, string? second)
{
// If either input is invalid
if (string.IsNullOrEmpty(first) || string.IsNullOrEmpty(second))
return -1;
// Split the string into 3 parts for processing
var firstSplit = first!.Split(':');
var secondSplit = second!.Split(':');
if (firstSplit.Length != 3 || secondSplit.Length != 3)
return -1;
// If any of the required parts are empty
if (firstSplit[0].Length == 0 || firstSplit[2].Length == 0)
return -1;
if (secondSplit[0].Length == 0 || secondSplit[2].Length == 0)
return -1;
// Ensure only second block data before a comma is used
firstSplit[2] = firstSplit[2].Split(',')[0];
secondSplit[2] = secondSplit[2].Split(',')[0];
// Each SpamSum string starts with its block size before the first semicolon.
if (!uint.TryParse(firstSplit[0], out uint firstBlockSize))
return -1;
if (!uint.TryParse(secondSplit[0], out uint secondBlockSize))
return -1;
// Check if blocksizes don't match. Each spamSum is broken up into two blocks.
// fuzzy_compare allows you to compare if one block in one hash is the same
// size as one block in the other hash, even if the other two are non-matching,
// so that's also checked for.
if (firstBlockSize != secondBlockSize
&& (firstBlockSize > uint.MaxValue / 2 || firstBlockSize * 2 != secondBlockSize)
&& (firstBlockSize % 2 == 1 || firstBlockSize / 2 != secondBlockSize))
{
return 0;
}
// Reduce any sequences longer than 3
// These sequences contain very little info and can be reduced as a result
string firstBlockOne = _reduceRegex.Replace(firstSplit[1], string.Empty);
string firstBlockTwo = _reduceRegex.Replace(firstSplit[2], string.Empty);
string secondBlockOne = _reduceRegex.Replace(secondSplit[1], string.Empty);
string secondBlockTwo = _reduceRegex.Replace(secondSplit[2], string.Empty);
// Return 100 immediately if both spamSums are identical.
if (firstBlockSize == secondBlockSize && firstBlockOne == secondBlockOne && firstBlockTwo == secondBlockTwo)
return 100;
// Choose different scoring combinations depending on block sizes present.
if (firstBlockSize <= uint.MaxValue / 2)
{
if (firstBlockSize == secondBlockSize)
{
uint score1 = ScoreStrings(firstBlockOne, secondBlockOne, firstBlockSize);
uint score2 = ScoreStrings(firstBlockTwo, secondBlockTwo, firstBlockSize * 2);
return (int)Math.Max(score1, score2);
}
else if (firstBlockSize * 2 == secondBlockSize)
{
return (int)ScoreStrings(secondBlockOne, firstBlockTwo, secondBlockSize);
}
else
{
return (int)ScoreStrings(firstBlockOne, secondBlockTwo, firstBlockSize);
}
}
else
{
if (firstBlockSize == secondBlockSize)
return (int)ScoreStrings(firstBlockOne, secondBlockOne, firstBlockSize);
else if (firstBlockSize % 2 == 0 && firstBlockSize / 2 == secondBlockSize)
return (int)ScoreStrings(firstBlockOne, secondBlockTwo, firstBlockSize);
else
return 0;
}
}
/// <summary>
/// Checks whether the two SpamSum strings have a common substring of 7 or more characters (as defined in fuzzy_compare's ROLLING_WINDOW size).
/// </summary>
/// <param name="first">First string to score</param>
/// <param name="second">Second string to score</param>
/// <returns>False if there is no common substring of 7 or more characters, true if there is.</returns>
private static bool HasCommmonSubstring(string first, string second)
{
// If either string is less than 7 characters
if (first.Length < 7 || second.Length < 7)
return false;
for (int i = 0; i < first.Length; i++)
{
for (int j = 0; j < second.Length; j++)
{
int currentIndex = 0;
while ((i + currentIndex) < first.Length && (j + currentIndex) < second.Length && first[i + currentIndex] == second[j + currentIndex])
{
currentIndex++;
}
if (currentIndex >= 7)
return true;
}
}
return false;
}
/// <summary>
/// Compares how similar two SpamSums are to each other. Implements ssdeep's fuzzy_compare.
/// </summary>
/// <param name="first">First string to score</param>
/// <param name="second">Second string to score</param>
/// <param name="blockSize">Current blocksize</param>
/// <returns>-1 on validity failure, 0 if they're not comparable, score from 0 (least similar) to 100 (most similar) otherwise.</returns>
private static uint ScoreStrings(string first, string second, uint blockSize)
{
if (!HasCommmonSubstring(first, second))
return 0;
const uint maxLength = 64;
const uint insertCost = 1;
const uint removeCost = 1;
const uint replaceCost = 2;
var firstTraverse = new uint[maxLength + 1];
var secondTraverse = new uint[maxLength + 1];
for (uint secondIndex = 0; secondIndex <= second.Length; secondIndex++)
{
firstTraverse[secondIndex] = secondIndex * removeCost;
}
for (uint firstIndex = 0; firstIndex < first.Length; firstIndex++)
{
secondTraverse[0] = (firstIndex + 1) * insertCost;
for (uint secondIndex = 0; secondIndex < second.Length; secondIndex++)
{
var costA = firstTraverse[secondIndex + 1] + insertCost;
var costD = secondTraverse[secondIndex] + removeCost;
var costR = firstTraverse[secondIndex] + (first[(int)firstIndex] == second[(int)secondIndex] ? 0 : replaceCost);
secondTraverse[secondIndex + 1] = Math.Min(Math.Min(costA, costD), costR);
}
#pragma warning disable IDE0180 // Use tuple to swap values
#if NETCOREAPP || NETSTANDARD2_0_OR_GREATER
(secondTraverse, firstTraverse) = (firstTraverse, secondTraverse);
#else
var tempArray = firstTraverse;
firstTraverse = secondTraverse;
secondTraverse = tempArray;
#endif
#pragma warning restore IDE0180
}
long score = firstTraverse[second.Length];
const int spamSumLength = 64;
const int rollingWindow = 7;
const int minBlocksize = 3;
score = score * spamSumLength / (first.Length + second.Length);
// Currently, the score ranges from 0-64 (64 being the length of a spamsum), with 0 being the strongest match
// and 64 being the weakest match.
// Change scale to 0-100
score = 100 * score / spamSumLength;
// Invert scale so 0 is the weakest possible match and 100 is the strongest
score = 100 - score;
// Compensate for small blocksizes, so match isn't reported as overly strong.
if (blockSize >= (99 + rollingWindow) / rollingWindow * minBlocksize)
return (uint)score;
if (score > blockSize / minBlocksize * Math.Min(first.Length, second.Length))
score = blockSize / minBlocksize * Math.Min(first.Length, second.Length);
return (uint)score;
}
}

View File

@@ -0,0 +1,446 @@
using System.Text;
namespace SabreTools.Hashing.SpamSum
{
/// <see href="github.com/ssdeep-project/ssdeep/blob/master/fuzzy.c"/>
/// <see href="github.com/ssdeep-project/ssdeep/blob/master/fuzzy.h"/>
internal static class Constants
{
/// <summary>
/// fuzzy_digest flag indicating to eliminate sequences of more than
/// three identical characters
/// </summary>
public const uint FUZZY_FLAG_ELIMSEQ = 1;
/// <summary>
/// fuzzy_digest flag indicating not to truncate the second part to
/// SPAMSUM_LENGTH / 2 characters.
/// </summary>
public const uint FUZZY_FLAG_NOTRUNC = 2;
/// <summary>
/// Length of an individual fuzzy hash signature component.
/// </summary>
public const int SPAMSUM_LENGTH = 64;
/// <summary>
/// The longest possible length for a fuzzy hash signature
/// (without the filename)
/// </summary>
public const int FUZZY_MAX_RESULT = (2 * SPAMSUM_LENGTH) + 20;
public const uint ROLLING_WINDOW = 7;
public const uint MIN_BLOCKSIZE = 3;
public const byte HASH_INIT = 0x27;
public const int NUM_BLOCKHASHES = 31;
public const uint FUZZY_STATE_NEED_LASTHASH = 1;
public const uint FUZZY_STATE_SIZE_FIXED = 2;
public static uint SSDEEP_BS(uint index) => MIN_BLOCKSIZE << (int)index;
public static ulong SSDEEP_TOTAL_SIZE_MAX
=> (ulong)SSDEEP_BS(NUM_BLOCKHASHES - 1) * SPAMSUM_LENGTH;
public static readonly byte[] B64 = Encoding.ASCII.GetBytes("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/");
#region Precomputed Tables
/// <summary>
/// Precomputed patrial FNV hash table
/// </summary>
public static readonly byte[][] SUM_TABLE = // [64][64]
[
[ // 0x00
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f,
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f,
],
[ // 0x01
0x13, 0x12, 0x11, 0x10, 0x17, 0x16, 0x15, 0x14, 0x1b, 0x1a, 0x19, 0x18, 0x1f, 0x1e, 0x1d, 0x1c,
0x03, 0x02, 0x01, 0x00, 0x07, 0x06, 0x05, 0x04, 0x0b, 0x0a, 0x09, 0x08, 0x0f, 0x0e, 0x0d, 0x0c,
0x33, 0x32, 0x31, 0x30, 0x37, 0x36, 0x35, 0x34, 0x3b, 0x3a, 0x39, 0x38, 0x3f, 0x3e, 0x3d, 0x3c,
0x23, 0x22, 0x21, 0x20, 0x27, 0x26, 0x25, 0x24, 0x2b, 0x2a, 0x29, 0x28, 0x2f, 0x2e, 0x2d, 0x2c,
],
[ // 0x02
0x26, 0x27, 0x24, 0x25, 0x22, 0x23, 0x20, 0x21, 0x2e, 0x2f, 0x2c, 0x2d, 0x2a, 0x2b, 0x28, 0x29,
0x36, 0x37, 0x34, 0x35, 0x32, 0x33, 0x30, 0x31, 0x3e, 0x3f, 0x3c, 0x3d, 0x3a, 0x3b, 0x38, 0x39,
0x06, 0x07, 0x04, 0x05, 0x02, 0x03, 0x00, 0x01, 0x0e, 0x0f, 0x0c, 0x0d, 0x0a, 0x0b, 0x08, 0x09,
0x16, 0x17, 0x14, 0x15, 0x12, 0x13, 0x10, 0x11, 0x1e, 0x1f, 0x1c, 0x1d, 0x1a, 0x1b, 0x18, 0x19,
],
[ // 0x03
0x39, 0x38, 0x3b, 0x3a, 0x3d, 0x3c, 0x3f, 0x3e, 0x31, 0x30, 0x33, 0x32, 0x35, 0x34, 0x37, 0x36,
0x29, 0x28, 0x2b, 0x2a, 0x2d, 0x2c, 0x2f, 0x2e, 0x21, 0x20, 0x23, 0x22, 0x25, 0x24, 0x27, 0x26,
0x19, 0x18, 0x1b, 0x1a, 0x1d, 0x1c, 0x1f, 0x1e, 0x11, 0x10, 0x13, 0x12, 0x15, 0x14, 0x17, 0x16,
0x09, 0x08, 0x0b, 0x0a, 0x0d, 0x0c, 0x0f, 0x0e, 0x01, 0x00, 0x03, 0x02, 0x05, 0x04, 0x07, 0x06,
],
[ // 0x04
0x0c, 0x0d, 0x0e, 0x0f, 0x08, 0x09, 0x0a, 0x0b, 0x04, 0x05, 0x06, 0x07, 0x00, 0x01, 0x02, 0x03,
0x1c, 0x1d, 0x1e, 0x1f, 0x18, 0x19, 0x1a, 0x1b, 0x14, 0x15, 0x16, 0x17, 0x10, 0x11, 0x12, 0x13,
0x2c, 0x2d, 0x2e, 0x2f, 0x28, 0x29, 0x2a, 0x2b, 0x24, 0x25, 0x26, 0x27, 0x20, 0x21, 0x22, 0x23,
0x3c, 0x3d, 0x3e, 0x3f, 0x38, 0x39, 0x3a, 0x3b, 0x34, 0x35, 0x36, 0x37, 0x30, 0x31, 0x32, 0x33,
],
[ // 0x05
0x1f, 0x1e, 0x1d, 0x1c, 0x1b, 0x1a, 0x19, 0x18, 0x17, 0x16, 0x15, 0x14, 0x13, 0x12, 0x11, 0x10,
0x0f, 0x0e, 0x0d, 0x0c, 0x0b, 0x0a, 0x09, 0x08, 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01, 0x00,
0x3f, 0x3e, 0x3d, 0x3c, 0x3b, 0x3a, 0x39, 0x38, 0x37, 0x36, 0x35, 0x34, 0x33, 0x32, 0x31, 0x30,
0x2f, 0x2e, 0x2d, 0x2c, 0x2b, 0x2a, 0x29, 0x28, 0x27, 0x26, 0x25, 0x24, 0x23, 0x22, 0x21, 0x20,
],
[ // 0x06
0x32, 0x33, 0x30, 0x31, 0x36, 0x37, 0x34, 0x35, 0x3a, 0x3b, 0x38, 0x39, 0x3e, 0x3f, 0x3c, 0x3d,
0x22, 0x23, 0x20, 0x21, 0x26, 0x27, 0x24, 0x25, 0x2a, 0x2b, 0x28, 0x29, 0x2e, 0x2f, 0x2c, 0x2d,
0x12, 0x13, 0x10, 0x11, 0x16, 0x17, 0x14, 0x15, 0x1a, 0x1b, 0x18, 0x19, 0x1e, 0x1f, 0x1c, 0x1d,
0x02, 0x03, 0x00, 0x01, 0x06, 0x07, 0x04, 0x05, 0x0a, 0x0b, 0x08, 0x09, 0x0e, 0x0f, 0x0c, 0x0d,
],
[ // 0x07
0x05, 0x04, 0x07, 0x06, 0x01, 0x00, 0x03, 0x02, 0x0d, 0x0c, 0x0f, 0x0e, 0x09, 0x08, 0x0b, 0x0a,
0x15, 0x14, 0x17, 0x16, 0x11, 0x10, 0x13, 0x12, 0x1d, 0x1c, 0x1f, 0x1e, 0x19, 0x18, 0x1b, 0x1a,
0x25, 0x24, 0x27, 0x26, 0x21, 0x20, 0x23, 0x22, 0x2d, 0x2c, 0x2f, 0x2e, 0x29, 0x28, 0x2b, 0x2a,
0x35, 0x34, 0x37, 0x36, 0x31, 0x30, 0x33, 0x32, 0x3d, 0x3c, 0x3f, 0x3e, 0x39, 0x38, 0x3b, 0x3a,
],
[ // 0x08
0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37,
0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27,
],
[ // 0x09
0x2b, 0x2a, 0x29, 0x28, 0x2f, 0x2e, 0x2d, 0x2c, 0x23, 0x22, 0x21, 0x20, 0x27, 0x26, 0x25, 0x24,
0x3b, 0x3a, 0x39, 0x38, 0x3f, 0x3e, 0x3d, 0x3c, 0x33, 0x32, 0x31, 0x30, 0x37, 0x36, 0x35, 0x34,
0x0b, 0x0a, 0x09, 0x08, 0x0f, 0x0e, 0x0d, 0x0c, 0x03, 0x02, 0x01, 0x00, 0x07, 0x06, 0x05, 0x04,
0x1b, 0x1a, 0x19, 0x18, 0x1f, 0x1e, 0x1d, 0x1c, 0x13, 0x12, 0x11, 0x10, 0x17, 0x16, 0x15, 0x14,
],
[ // 0x0a
0x3e, 0x3f, 0x3c, 0x3d, 0x3a, 0x3b, 0x38, 0x39, 0x36, 0x37, 0x34, 0x35, 0x32, 0x33, 0x30, 0x31,
0x2e, 0x2f, 0x2c, 0x2d, 0x2a, 0x2b, 0x28, 0x29, 0x26, 0x27, 0x24, 0x25, 0x22, 0x23, 0x20, 0x21,
0x1e, 0x1f, 0x1c, 0x1d, 0x1a, 0x1b, 0x18, 0x19, 0x16, 0x17, 0x14, 0x15, 0x12, 0x13, 0x10, 0x11,
0x0e, 0x0f, 0x0c, 0x0d, 0x0a, 0x0b, 0x08, 0x09, 0x06, 0x07, 0x04, 0x05, 0x02, 0x03, 0x00, 0x01,
],
[ // 0x0b
0x11, 0x10, 0x13, 0x12, 0x15, 0x14, 0x17, 0x16, 0x19, 0x18, 0x1b, 0x1a, 0x1d, 0x1c, 0x1f, 0x1e,
0x01, 0x00, 0x03, 0x02, 0x05, 0x04, 0x07, 0x06, 0x09, 0x08, 0x0b, 0x0a, 0x0d, 0x0c, 0x0f, 0x0e,
0x31, 0x30, 0x33, 0x32, 0x35, 0x34, 0x37, 0x36, 0x39, 0x38, 0x3b, 0x3a, 0x3d, 0x3c, 0x3f, 0x3e,
0x21, 0x20, 0x23, 0x22, 0x25, 0x24, 0x27, 0x26, 0x29, 0x28, 0x2b, 0x2a, 0x2d, 0x2c, 0x2f, 0x2e,
],
[ // 0x0c
0x24, 0x25, 0x26, 0x27, 0x20, 0x21, 0x22, 0x23, 0x2c, 0x2d, 0x2e, 0x2f, 0x28, 0x29, 0x2a, 0x2b,
0x34, 0x35, 0x36, 0x37, 0x30, 0x31, 0x32, 0x33, 0x3c, 0x3d, 0x3e, 0x3f, 0x38, 0x39, 0x3a, 0x3b,
0x04, 0x05, 0x06, 0x07, 0x00, 0x01, 0x02, 0x03, 0x0c, 0x0d, 0x0e, 0x0f, 0x08, 0x09, 0x0a, 0x0b,
0x14, 0x15, 0x16, 0x17, 0x10, 0x11, 0x12, 0x13, 0x1c, 0x1d, 0x1e, 0x1f, 0x18, 0x19, 0x1a, 0x1b,
],
[ // 0x0d
0x37, 0x36, 0x35, 0x34, 0x33, 0x32, 0x31, 0x30, 0x3f, 0x3e, 0x3d, 0x3c, 0x3b, 0x3a, 0x39, 0x38,
0x27, 0x26, 0x25, 0x24, 0x23, 0x22, 0x21, 0x20, 0x2f, 0x2e, 0x2d, 0x2c, 0x2b, 0x2a, 0x29, 0x28,
0x17, 0x16, 0x15, 0x14, 0x13, 0x12, 0x11, 0x10, 0x1f, 0x1e, 0x1d, 0x1c, 0x1b, 0x1a, 0x19, 0x18,
0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01, 0x00, 0x0f, 0x0e, 0x0d, 0x0c, 0x0b, 0x0a, 0x09, 0x08,
],
[ // 0x0e
0x0a, 0x0b, 0x08, 0x09, 0x0e, 0x0f, 0x0c, 0x0d, 0x02, 0x03, 0x00, 0x01, 0x06, 0x07, 0x04, 0x05,
0x1a, 0x1b, 0x18, 0x19, 0x1e, 0x1f, 0x1c, 0x1d, 0x12, 0x13, 0x10, 0x11, 0x16, 0x17, 0x14, 0x15,
0x2a, 0x2b, 0x28, 0x29, 0x2e, 0x2f, 0x2c, 0x2d, 0x22, 0x23, 0x20, 0x21, 0x26, 0x27, 0x24, 0x25,
0x3a, 0x3b, 0x38, 0x39, 0x3e, 0x3f, 0x3c, 0x3d, 0x32, 0x33, 0x30, 0x31, 0x36, 0x37, 0x34, 0x35,
],
[ // 0x0f
0x1d, 0x1c, 0x1f, 0x1e, 0x19, 0x18, 0x1b, 0x1a, 0x15, 0x14, 0x17, 0x16, 0x11, 0x10, 0x13, 0x12,
0x0d, 0x0c, 0x0f, 0x0e, 0x09, 0x08, 0x0b, 0x0a, 0x05, 0x04, 0x07, 0x06, 0x01, 0x00, 0x03, 0x02,
0x3d, 0x3c, 0x3f, 0x3e, 0x39, 0x38, 0x3b, 0x3a, 0x35, 0x34, 0x37, 0x36, 0x31, 0x30, 0x33, 0x32,
0x2d, 0x2c, 0x2f, 0x2e, 0x29, 0x28, 0x2b, 0x2a, 0x25, 0x24, 0x27, 0x26, 0x21, 0x20, 0x23, 0x22,
],
[ // 0x10
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f,
0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f,
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
],
[ // 0x11
0x03, 0x02, 0x01, 0x00, 0x07, 0x06, 0x05, 0x04, 0x0b, 0x0a, 0x09, 0x08, 0x0f, 0x0e, 0x0d, 0x0c,
0x13, 0x12, 0x11, 0x10, 0x17, 0x16, 0x15, 0x14, 0x1b, 0x1a, 0x19, 0x18, 0x1f, 0x1e, 0x1d, 0x1c,
0x23, 0x22, 0x21, 0x20, 0x27, 0x26, 0x25, 0x24, 0x2b, 0x2a, 0x29, 0x28, 0x2f, 0x2e, 0x2d, 0x2c,
0x33, 0x32, 0x31, 0x30, 0x37, 0x36, 0x35, 0x34, 0x3b, 0x3a, 0x39, 0x38, 0x3f, 0x3e, 0x3d, 0x3c,
],
[ // 0x12
0x16, 0x17, 0x14, 0x15, 0x12, 0x13, 0x10, 0x11, 0x1e, 0x1f, 0x1c, 0x1d, 0x1a, 0x1b, 0x18, 0x19,
0x06, 0x07, 0x04, 0x05, 0x02, 0x03, 0x00, 0x01, 0x0e, 0x0f, 0x0c, 0x0d, 0x0a, 0x0b, 0x08, 0x09,
0x36, 0x37, 0x34, 0x35, 0x32, 0x33, 0x30, 0x31, 0x3e, 0x3f, 0x3c, 0x3d, 0x3a, 0x3b, 0x38, 0x39,
0x26, 0x27, 0x24, 0x25, 0x22, 0x23, 0x20, 0x21, 0x2e, 0x2f, 0x2c, 0x2d, 0x2a, 0x2b, 0x28, 0x29,
],
[ // 0x13
0x29, 0x28, 0x2b, 0x2a, 0x2d, 0x2c, 0x2f, 0x2e, 0x21, 0x20, 0x23, 0x22, 0x25, 0x24, 0x27, 0x26,
0x39, 0x38, 0x3b, 0x3a, 0x3d, 0x3c, 0x3f, 0x3e, 0x31, 0x30, 0x33, 0x32, 0x35, 0x34, 0x37, 0x36,
0x09, 0x08, 0x0b, 0x0a, 0x0d, 0x0c, 0x0f, 0x0e, 0x01, 0x00, 0x03, 0x02, 0x05, 0x04, 0x07, 0x06,
0x19, 0x18, 0x1b, 0x1a, 0x1d, 0x1c, 0x1f, 0x1e, 0x11, 0x10, 0x13, 0x12, 0x15, 0x14, 0x17, 0x16,
],
[ // 0x14
0x3c, 0x3d, 0x3e, 0x3f, 0x38, 0x39, 0x3a, 0x3b, 0x34, 0x35, 0x36, 0x37, 0x30, 0x31, 0x32, 0x33,
0x2c, 0x2d, 0x2e, 0x2f, 0x28, 0x29, 0x2a, 0x2b, 0x24, 0x25, 0x26, 0x27, 0x20, 0x21, 0x22, 0x23,
0x1c, 0x1d, 0x1e, 0x1f, 0x18, 0x19, 0x1a, 0x1b, 0x14, 0x15, 0x16, 0x17, 0x10, 0x11, 0x12, 0x13,
0x0c, 0x0d, 0x0e, 0x0f, 0x08, 0x09, 0x0a, 0x0b, 0x04, 0x05, 0x06, 0x07, 0x00, 0x01, 0x02, 0x03,
],
[ // 0x15
0x0f, 0x0e, 0x0d, 0x0c, 0x0b, 0x0a, 0x09, 0x08, 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01, 0x00,
0x1f, 0x1e, 0x1d, 0x1c, 0x1b, 0x1a, 0x19, 0x18, 0x17, 0x16, 0x15, 0x14, 0x13, 0x12, 0x11, 0x10,
0x2f, 0x2e, 0x2d, 0x2c, 0x2b, 0x2a, 0x29, 0x28, 0x27, 0x26, 0x25, 0x24, 0x23, 0x22, 0x21, 0x20,
0x3f, 0x3e, 0x3d, 0x3c, 0x3b, 0x3a, 0x39, 0x38, 0x37, 0x36, 0x35, 0x34, 0x33, 0x32, 0x31, 0x30,
],
[ // 0x16
0x22, 0x23, 0x20, 0x21, 0x26, 0x27, 0x24, 0x25, 0x2a, 0x2b, 0x28, 0x29, 0x2e, 0x2f, 0x2c, 0x2d,
0x32, 0x33, 0x30, 0x31, 0x36, 0x37, 0x34, 0x35, 0x3a, 0x3b, 0x38, 0x39, 0x3e, 0x3f, 0x3c, 0x3d,
0x02, 0x03, 0x00, 0x01, 0x06, 0x07, 0x04, 0x05, 0x0a, 0x0b, 0x08, 0x09, 0x0e, 0x0f, 0x0c, 0x0d,
0x12, 0x13, 0x10, 0x11, 0x16, 0x17, 0x14, 0x15, 0x1a, 0x1b, 0x18, 0x19, 0x1e, 0x1f, 0x1c, 0x1d,
],
[ // 0x17
0x35, 0x34, 0x37, 0x36, 0x31, 0x30, 0x33, 0x32, 0x3d, 0x3c, 0x3f, 0x3e, 0x39, 0x38, 0x3b, 0x3a,
0x25, 0x24, 0x27, 0x26, 0x21, 0x20, 0x23, 0x22, 0x2d, 0x2c, 0x2f, 0x2e, 0x29, 0x28, 0x2b, 0x2a,
0x15, 0x14, 0x17, 0x16, 0x11, 0x10, 0x13, 0x12, 0x1d, 0x1c, 0x1f, 0x1e, 0x19, 0x18, 0x1b, 0x1a,
0x05, 0x04, 0x07, 0x06, 0x01, 0x00, 0x03, 0x02, 0x0d, 0x0c, 0x0f, 0x0e, 0x09, 0x08, 0x0b, 0x0a,
],
[ // 0x18
0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27,
0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37,
],
[ // 0x19
0x1b, 0x1a, 0x19, 0x18, 0x1f, 0x1e, 0x1d, 0x1c, 0x13, 0x12, 0x11, 0x10, 0x17, 0x16, 0x15, 0x14,
0x0b, 0x0a, 0x09, 0x08, 0x0f, 0x0e, 0x0d, 0x0c, 0x03, 0x02, 0x01, 0x00, 0x07, 0x06, 0x05, 0x04,
0x3b, 0x3a, 0x39, 0x38, 0x3f, 0x3e, 0x3d, 0x3c, 0x33, 0x32, 0x31, 0x30, 0x37, 0x36, 0x35, 0x34,
0x2b, 0x2a, 0x29, 0x28, 0x2f, 0x2e, 0x2d, 0x2c, 0x23, 0x22, 0x21, 0x20, 0x27, 0x26, 0x25, 0x24,
],
[ // 0x1a
0x2e, 0x2f, 0x2c, 0x2d, 0x2a, 0x2b, 0x28, 0x29, 0x26, 0x27, 0x24, 0x25, 0x22, 0x23, 0x20, 0x21,
0x3e, 0x3f, 0x3c, 0x3d, 0x3a, 0x3b, 0x38, 0x39, 0x36, 0x37, 0x34, 0x35, 0x32, 0x33, 0x30, 0x31,
0x0e, 0x0f, 0x0c, 0x0d, 0x0a, 0x0b, 0x08, 0x09, 0x06, 0x07, 0x04, 0x05, 0x02, 0x03, 0x00, 0x01,
0x1e, 0x1f, 0x1c, 0x1d, 0x1a, 0x1b, 0x18, 0x19, 0x16, 0x17, 0x14, 0x15, 0x12, 0x13, 0x10, 0x11,
],
[ // 0x1b
0x01, 0x00, 0x03, 0x02, 0x05, 0x04, 0x07, 0x06, 0x09, 0x08, 0x0b, 0x0a, 0x0d, 0x0c, 0x0f, 0x0e,
0x11, 0x10, 0x13, 0x12, 0x15, 0x14, 0x17, 0x16, 0x19, 0x18, 0x1b, 0x1a, 0x1d, 0x1c, 0x1f, 0x1e,
0x21, 0x20, 0x23, 0x22, 0x25, 0x24, 0x27, 0x26, 0x29, 0x28, 0x2b, 0x2a, 0x2d, 0x2c, 0x2f, 0x2e,
0x31, 0x30, 0x33, 0x32, 0x35, 0x34, 0x37, 0x36, 0x39, 0x38, 0x3b, 0x3a, 0x3d, 0x3c, 0x3f, 0x3e,
],
[ // 0x1c
0x14, 0x15, 0x16, 0x17, 0x10, 0x11, 0x12, 0x13, 0x1c, 0x1d, 0x1e, 0x1f, 0x18, 0x19, 0x1a, 0x1b,
0x04, 0x05, 0x06, 0x07, 0x00, 0x01, 0x02, 0x03, 0x0c, 0x0d, 0x0e, 0x0f, 0x08, 0x09, 0x0a, 0x0b,
0x34, 0x35, 0x36, 0x37, 0x30, 0x31, 0x32, 0x33, 0x3c, 0x3d, 0x3e, 0x3f, 0x38, 0x39, 0x3a, 0x3b,
0x24, 0x25, 0x26, 0x27, 0x20, 0x21, 0x22, 0x23, 0x2c, 0x2d, 0x2e, 0x2f, 0x28, 0x29, 0x2a, 0x2b,
],
[ // 0x1d
0x27, 0x26, 0x25, 0x24, 0x23, 0x22, 0x21, 0x20, 0x2f, 0x2e, 0x2d, 0x2c, 0x2b, 0x2a, 0x29, 0x28,
0x37, 0x36, 0x35, 0x34, 0x33, 0x32, 0x31, 0x30, 0x3f, 0x3e, 0x3d, 0x3c, 0x3b, 0x3a, 0x39, 0x38,
0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01, 0x00, 0x0f, 0x0e, 0x0d, 0x0c, 0x0b, 0x0a, 0x09, 0x08,
0x17, 0x16, 0x15, 0x14, 0x13, 0x12, 0x11, 0x10, 0x1f, 0x1e, 0x1d, 0x1c, 0x1b, 0x1a, 0x19, 0x18,
],
[ // 0x1e
0x3a, 0x3b, 0x38, 0x39, 0x3e, 0x3f, 0x3c, 0x3d, 0x32, 0x33, 0x30, 0x31, 0x36, 0x37, 0x34, 0x35,
0x2a, 0x2b, 0x28, 0x29, 0x2e, 0x2f, 0x2c, 0x2d, 0x22, 0x23, 0x20, 0x21, 0x26, 0x27, 0x24, 0x25,
0x1a, 0x1b, 0x18, 0x19, 0x1e, 0x1f, 0x1c, 0x1d, 0x12, 0x13, 0x10, 0x11, 0x16, 0x17, 0x14, 0x15,
0x0a, 0x0b, 0x08, 0x09, 0x0e, 0x0f, 0x0c, 0x0d, 0x02, 0x03, 0x00, 0x01, 0x06, 0x07, 0x04, 0x05,
],
[ // 0x1f
0x0d, 0x0c, 0x0f, 0x0e, 0x09, 0x08, 0x0b, 0x0a, 0x05, 0x04, 0x07, 0x06, 0x01, 0x00, 0x03, 0x02,
0x1d, 0x1c, 0x1f, 0x1e, 0x19, 0x18, 0x1b, 0x1a, 0x15, 0x14, 0x17, 0x16, 0x11, 0x10, 0x13, 0x12,
0x2d, 0x2c, 0x2f, 0x2e, 0x29, 0x28, 0x2b, 0x2a, 0x25, 0x24, 0x27, 0x26, 0x21, 0x20, 0x23, 0x22,
0x3d, 0x3c, 0x3f, 0x3e, 0x39, 0x38, 0x3b, 0x3a, 0x35, 0x34, 0x37, 0x36, 0x31, 0x30, 0x33, 0x32,
],
[ // 0x20
0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f,
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f,
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
],
[ // 0x21
0x33, 0x32, 0x31, 0x30, 0x37, 0x36, 0x35, 0x34, 0x3b, 0x3a, 0x39, 0x38, 0x3f, 0x3e, 0x3d, 0x3c,
0x23, 0x22, 0x21, 0x20, 0x27, 0x26, 0x25, 0x24, 0x2b, 0x2a, 0x29, 0x28, 0x2f, 0x2e, 0x2d, 0x2c,
0x13, 0x12, 0x11, 0x10, 0x17, 0x16, 0x15, 0x14, 0x1b, 0x1a, 0x19, 0x18, 0x1f, 0x1e, 0x1d, 0x1c,
0x03, 0x02, 0x01, 0x00, 0x07, 0x06, 0x05, 0x04, 0x0b, 0x0a, 0x09, 0x08, 0x0f, 0x0e, 0x0d, 0x0c,
],
[ // 0x22
0x06, 0x07, 0x04, 0x05, 0x02, 0x03, 0x00, 0x01, 0x0e, 0x0f, 0x0c, 0x0d, 0x0a, 0x0b, 0x08, 0x09,
0x16, 0x17, 0x14, 0x15, 0x12, 0x13, 0x10, 0x11, 0x1e, 0x1f, 0x1c, 0x1d, 0x1a, 0x1b, 0x18, 0x19,
0x26, 0x27, 0x24, 0x25, 0x22, 0x23, 0x20, 0x21, 0x2e, 0x2f, 0x2c, 0x2d, 0x2a, 0x2b, 0x28, 0x29,
0x36, 0x37, 0x34, 0x35, 0x32, 0x33, 0x30, 0x31, 0x3e, 0x3f, 0x3c, 0x3d, 0x3a, 0x3b, 0x38, 0x39,
],
[ // 0x23
0x19, 0x18, 0x1b, 0x1a, 0x1d, 0x1c, 0x1f, 0x1e, 0x11, 0x10, 0x13, 0x12, 0x15, 0x14, 0x17, 0x16,
0x09, 0x08, 0x0b, 0x0a, 0x0d, 0x0c, 0x0f, 0x0e, 0x01, 0x00, 0x03, 0x02, 0x05, 0x04, 0x07, 0x06,
0x39, 0x38, 0x3b, 0x3a, 0x3d, 0x3c, 0x3f, 0x3e, 0x31, 0x30, 0x33, 0x32, 0x35, 0x34, 0x37, 0x36,
0x29, 0x28, 0x2b, 0x2a, 0x2d, 0x2c, 0x2f, 0x2e, 0x21, 0x20, 0x23, 0x22, 0x25, 0x24, 0x27, 0x26,
],
[ // 0x24
0x2c, 0x2d, 0x2e, 0x2f, 0x28, 0x29, 0x2a, 0x2b, 0x24, 0x25, 0x26, 0x27, 0x20, 0x21, 0x22, 0x23,
0x3c, 0x3d, 0x3e, 0x3f, 0x38, 0x39, 0x3a, 0x3b, 0x34, 0x35, 0x36, 0x37, 0x30, 0x31, 0x32, 0x33,
0x0c, 0x0d, 0x0e, 0x0f, 0x08, 0x09, 0x0a, 0x0b, 0x04, 0x05, 0x06, 0x07, 0x00, 0x01, 0x02, 0x03,
0x1c, 0x1d, 0x1e, 0x1f, 0x18, 0x19, 0x1a, 0x1b, 0x14, 0x15, 0x16, 0x17, 0x10, 0x11, 0x12, 0x13,
],
[ // 0x25
0x3f, 0x3e, 0x3d, 0x3c, 0x3b, 0x3a, 0x39, 0x38, 0x37, 0x36, 0x35, 0x34, 0x33, 0x32, 0x31, 0x30,
0x2f, 0x2e, 0x2d, 0x2c, 0x2b, 0x2a, 0x29, 0x28, 0x27, 0x26, 0x25, 0x24, 0x23, 0x22, 0x21, 0x20,
0x1f, 0x1e, 0x1d, 0x1c, 0x1b, 0x1a, 0x19, 0x18, 0x17, 0x16, 0x15, 0x14, 0x13, 0x12, 0x11, 0x10,
0x0f, 0x0e, 0x0d, 0x0c, 0x0b, 0x0a, 0x09, 0x08, 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01, 0x00,
],
[ // 0x26
0x12, 0x13, 0x10, 0x11, 0x16, 0x17, 0x14, 0x15, 0x1a, 0x1b, 0x18, 0x19, 0x1e, 0x1f, 0x1c, 0x1d,
0x02, 0x03, 0x00, 0x01, 0x06, 0x07, 0x04, 0x05, 0x0a, 0x0b, 0x08, 0x09, 0x0e, 0x0f, 0x0c, 0x0d,
0x32, 0x33, 0x30, 0x31, 0x36, 0x37, 0x34, 0x35, 0x3a, 0x3b, 0x38, 0x39, 0x3e, 0x3f, 0x3c, 0x3d,
0x22, 0x23, 0x20, 0x21, 0x26, 0x27, 0x24, 0x25, 0x2a, 0x2b, 0x28, 0x29, 0x2e, 0x2f, 0x2c, 0x2d,
],
[ // 0x27
0x25, 0x24, 0x27, 0x26, 0x21, 0x20, 0x23, 0x22, 0x2d, 0x2c, 0x2f, 0x2e, 0x29, 0x28, 0x2b, 0x2a,
0x35, 0x34, 0x37, 0x36, 0x31, 0x30, 0x33, 0x32, 0x3d, 0x3c, 0x3f, 0x3e, 0x39, 0x38, 0x3b, 0x3a,
0x05, 0x04, 0x07, 0x06, 0x01, 0x00, 0x03, 0x02, 0x0d, 0x0c, 0x0f, 0x0e, 0x09, 0x08, 0x0b, 0x0a,
0x15, 0x14, 0x17, 0x16, 0x11, 0x10, 0x13, 0x12, 0x1d, 0x1c, 0x1f, 0x1e, 0x19, 0x18, 0x1b, 0x1a,
],
[ // 0x28
0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37,
0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27,
0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
],
[ // 0x29
0x0b, 0x0a, 0x09, 0x08, 0x0f, 0x0e, 0x0d, 0x0c, 0x03, 0x02, 0x01, 0x00, 0x07, 0x06, 0x05, 0x04,
0x1b, 0x1a, 0x19, 0x18, 0x1f, 0x1e, 0x1d, 0x1c, 0x13, 0x12, 0x11, 0x10, 0x17, 0x16, 0x15, 0x14,
0x2b, 0x2a, 0x29, 0x28, 0x2f, 0x2e, 0x2d, 0x2c, 0x23, 0x22, 0x21, 0x20, 0x27, 0x26, 0x25, 0x24,
0x3b, 0x3a, 0x39, 0x38, 0x3f, 0x3e, 0x3d, 0x3c, 0x33, 0x32, 0x31, 0x30, 0x37, 0x36, 0x35, 0x34,
],
[ // 0x2a
0x1e, 0x1f, 0x1c, 0x1d, 0x1a, 0x1b, 0x18, 0x19, 0x16, 0x17, 0x14, 0x15, 0x12, 0x13, 0x10, 0x11,
0x0e, 0x0f, 0x0c, 0x0d, 0x0a, 0x0b, 0x08, 0x09, 0x06, 0x07, 0x04, 0x05, 0x02, 0x03, 0x00, 0x01,
0x3e, 0x3f, 0x3c, 0x3d, 0x3a, 0x3b, 0x38, 0x39, 0x36, 0x37, 0x34, 0x35, 0x32, 0x33, 0x30, 0x31,
0x2e, 0x2f, 0x2c, 0x2d, 0x2a, 0x2b, 0x28, 0x29, 0x26, 0x27, 0x24, 0x25, 0x22, 0x23, 0x20, 0x21,
],
[ // 0x2b
0x31, 0x30, 0x33, 0x32, 0x35, 0x34, 0x37, 0x36, 0x39, 0x38, 0x3b, 0x3a, 0x3d, 0x3c, 0x3f, 0x3e,
0x21, 0x20, 0x23, 0x22, 0x25, 0x24, 0x27, 0x26, 0x29, 0x28, 0x2b, 0x2a, 0x2d, 0x2c, 0x2f, 0x2e,
0x11, 0x10, 0x13, 0x12, 0x15, 0x14, 0x17, 0x16, 0x19, 0x18, 0x1b, 0x1a, 0x1d, 0x1c, 0x1f, 0x1e,
0x01, 0x00, 0x03, 0x02, 0x05, 0x04, 0x07, 0x06, 0x09, 0x08, 0x0b, 0x0a, 0x0d, 0x0c, 0x0f, 0x0e,
],
[ // 0x2c
0x04, 0x05, 0x06, 0x07, 0x00, 0x01, 0x02, 0x03, 0x0c, 0x0d, 0x0e, 0x0f, 0x08, 0x09, 0x0a, 0x0b,
0x14, 0x15, 0x16, 0x17, 0x10, 0x11, 0x12, 0x13, 0x1c, 0x1d, 0x1e, 0x1f, 0x18, 0x19, 0x1a, 0x1b,
0x24, 0x25, 0x26, 0x27, 0x20, 0x21, 0x22, 0x23, 0x2c, 0x2d, 0x2e, 0x2f, 0x28, 0x29, 0x2a, 0x2b,
0x34, 0x35, 0x36, 0x37, 0x30, 0x31, 0x32, 0x33, 0x3c, 0x3d, 0x3e, 0x3f, 0x38, 0x39, 0x3a, 0x3b,
],
[ // 0x2d
0x17, 0x16, 0x15, 0x14, 0x13, 0x12, 0x11, 0x10, 0x1f, 0x1e, 0x1d, 0x1c, 0x1b, 0x1a, 0x19, 0x18,
0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01, 0x00, 0x0f, 0x0e, 0x0d, 0x0c, 0x0b, 0x0a, 0x09, 0x08,
0x37, 0x36, 0x35, 0x34, 0x33, 0x32, 0x31, 0x30, 0x3f, 0x3e, 0x3d, 0x3c, 0x3b, 0x3a, 0x39, 0x38,
0x27, 0x26, 0x25, 0x24, 0x23, 0x22, 0x21, 0x20, 0x2f, 0x2e, 0x2d, 0x2c, 0x2b, 0x2a, 0x29, 0x28,
],
[ // 0x2e
0x2a, 0x2b, 0x28, 0x29, 0x2e, 0x2f, 0x2c, 0x2d, 0x22, 0x23, 0x20, 0x21, 0x26, 0x27, 0x24, 0x25,
0x3a, 0x3b, 0x38, 0x39, 0x3e, 0x3f, 0x3c, 0x3d, 0x32, 0x33, 0x30, 0x31, 0x36, 0x37, 0x34, 0x35,
0x0a, 0x0b, 0x08, 0x09, 0x0e, 0x0f, 0x0c, 0x0d, 0x02, 0x03, 0x00, 0x01, 0x06, 0x07, 0x04, 0x05,
0x1a, 0x1b, 0x18, 0x19, 0x1e, 0x1f, 0x1c, 0x1d, 0x12, 0x13, 0x10, 0x11, 0x16, 0x17, 0x14, 0x15,
],
[ // 0x2f
0x3d, 0x3c, 0x3f, 0x3e, 0x39, 0x38, 0x3b, 0x3a, 0x35, 0x34, 0x37, 0x36, 0x31, 0x30, 0x33, 0x32,
0x2d, 0x2c, 0x2f, 0x2e, 0x29, 0x28, 0x2b, 0x2a, 0x25, 0x24, 0x27, 0x26, 0x21, 0x20, 0x23, 0x22,
0x1d, 0x1c, 0x1f, 0x1e, 0x19, 0x18, 0x1b, 0x1a, 0x15, 0x14, 0x17, 0x16, 0x11, 0x10, 0x13, 0x12,
0x0d, 0x0c, 0x0f, 0x0e, 0x09, 0x08, 0x0b, 0x0a, 0x05, 0x04, 0x07, 0x06, 0x01, 0x00, 0x03, 0x02,
],
[ // 0x30
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f,
0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f,
],
[ // 0x31
0x23, 0x22, 0x21, 0x20, 0x27, 0x26, 0x25, 0x24, 0x2b, 0x2a, 0x29, 0x28, 0x2f, 0x2e, 0x2d, 0x2c,
0x33, 0x32, 0x31, 0x30, 0x37, 0x36, 0x35, 0x34, 0x3b, 0x3a, 0x39, 0x38, 0x3f, 0x3e, 0x3d, 0x3c,
0x03, 0x02, 0x01, 0x00, 0x07, 0x06, 0x05, 0x04, 0x0b, 0x0a, 0x09, 0x08, 0x0f, 0x0e, 0x0d, 0x0c,
0x13, 0x12, 0x11, 0x10, 0x17, 0x16, 0x15, 0x14, 0x1b, 0x1a, 0x19, 0x18, 0x1f, 0x1e, 0x1d, 0x1c,
],
[ // 0x32
0x36, 0x37, 0x34, 0x35, 0x32, 0x33, 0x30, 0x31, 0x3e, 0x3f, 0x3c, 0x3d, 0x3a, 0x3b, 0x38, 0x39,
0x26, 0x27, 0x24, 0x25, 0x22, 0x23, 0x20, 0x21, 0x2e, 0x2f, 0x2c, 0x2d, 0x2a, 0x2b, 0x28, 0x29,
0x16, 0x17, 0x14, 0x15, 0x12, 0x13, 0x10, 0x11, 0x1e, 0x1f, 0x1c, 0x1d, 0x1a, 0x1b, 0x18, 0x19,
0x06, 0x07, 0x04, 0x05, 0x02, 0x03, 0x00, 0x01, 0x0e, 0x0f, 0x0c, 0x0d, 0x0a, 0x0b, 0x08, 0x09,
],
[ // 0x33
0x09, 0x08, 0x0b, 0x0a, 0x0d, 0x0c, 0x0f, 0x0e, 0x01, 0x00, 0x03, 0x02, 0x05, 0x04, 0x07, 0x06,
0x19, 0x18, 0x1b, 0x1a, 0x1d, 0x1c, 0x1f, 0x1e, 0x11, 0x10, 0x13, 0x12, 0x15, 0x14, 0x17, 0x16,
0x29, 0x28, 0x2b, 0x2a, 0x2d, 0x2c, 0x2f, 0x2e, 0x21, 0x20, 0x23, 0x22, 0x25, 0x24, 0x27, 0x26,
0x39, 0x38, 0x3b, 0x3a, 0x3d, 0x3c, 0x3f, 0x3e, 0x31, 0x30, 0x33, 0x32, 0x35, 0x34, 0x37, 0x36,
],
[ // 0x34
0x1c, 0x1d, 0x1e, 0x1f, 0x18, 0x19, 0x1a, 0x1b, 0x14, 0x15, 0x16, 0x17, 0x10, 0x11, 0x12, 0x13,
0x0c, 0x0d, 0x0e, 0x0f, 0x08, 0x09, 0x0a, 0x0b, 0x04, 0x05, 0x06, 0x07, 0x00, 0x01, 0x02, 0x03,
0x3c, 0x3d, 0x3e, 0x3f, 0x38, 0x39, 0x3a, 0x3b, 0x34, 0x35, 0x36, 0x37, 0x30, 0x31, 0x32, 0x33,
0x2c, 0x2d, 0x2e, 0x2f, 0x28, 0x29, 0x2a, 0x2b, 0x24, 0x25, 0x26, 0x27, 0x20, 0x21, 0x22, 0x23,
],
[ // 0x35
0x2f, 0x2e, 0x2d, 0x2c, 0x2b, 0x2a, 0x29, 0x28, 0x27, 0x26, 0x25, 0x24, 0x23, 0x22, 0x21, 0x20,
0x3f, 0x3e, 0x3d, 0x3c, 0x3b, 0x3a, 0x39, 0x38, 0x37, 0x36, 0x35, 0x34, 0x33, 0x32, 0x31, 0x30,
0x0f, 0x0e, 0x0d, 0x0c, 0x0b, 0x0a, 0x09, 0x08, 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01, 0x00,
0x1f, 0x1e, 0x1d, 0x1c, 0x1b, 0x1a, 0x19, 0x18, 0x17, 0x16, 0x15, 0x14, 0x13, 0x12, 0x11, 0x10,
],
[ // 0x36
0x02, 0x03, 0x00, 0x01, 0x06, 0x07, 0x04, 0x05, 0x0a, 0x0b, 0x08, 0x09, 0x0e, 0x0f, 0x0c, 0x0d,
0x12, 0x13, 0x10, 0x11, 0x16, 0x17, 0x14, 0x15, 0x1a, 0x1b, 0x18, 0x19, 0x1e, 0x1f, 0x1c, 0x1d,
0x22, 0x23, 0x20, 0x21, 0x26, 0x27, 0x24, 0x25, 0x2a, 0x2b, 0x28, 0x29, 0x2e, 0x2f, 0x2c, 0x2d,
0x32, 0x33, 0x30, 0x31, 0x36, 0x37, 0x34, 0x35, 0x3a, 0x3b, 0x38, 0x39, 0x3e, 0x3f, 0x3c, 0x3d,
],
[ // 0x37
0x15, 0x14, 0x17, 0x16, 0x11, 0x10, 0x13, 0x12, 0x1d, 0x1c, 0x1f, 0x1e, 0x19, 0x18, 0x1b, 0x1a,
0x05, 0x04, 0x07, 0x06, 0x01, 0x00, 0x03, 0x02, 0x0d, 0x0c, 0x0f, 0x0e, 0x09, 0x08, 0x0b, 0x0a,
0x35, 0x34, 0x37, 0x36, 0x31, 0x30, 0x33, 0x32, 0x3d, 0x3c, 0x3f, 0x3e, 0x39, 0x38, 0x3b, 0x3a,
0x25, 0x24, 0x27, 0x26, 0x21, 0x20, 0x23, 0x22, 0x2d, 0x2c, 0x2f, 0x2e, 0x29, 0x28, 0x2b, 0x2a,
],
[ // 0x38
0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27,
0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37,
0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
],
[ // 0x39
0x3b, 0x3a, 0x39, 0x38, 0x3f, 0x3e, 0x3d, 0x3c, 0x33, 0x32, 0x31, 0x30, 0x37, 0x36, 0x35, 0x34,
0x2b, 0x2a, 0x29, 0x28, 0x2f, 0x2e, 0x2d, 0x2c, 0x23, 0x22, 0x21, 0x20, 0x27, 0x26, 0x25, 0x24,
0x1b, 0x1a, 0x19, 0x18, 0x1f, 0x1e, 0x1d, 0x1c, 0x13, 0x12, 0x11, 0x10, 0x17, 0x16, 0x15, 0x14,
0x0b, 0x0a, 0x09, 0x08, 0x0f, 0x0e, 0x0d, 0x0c, 0x03, 0x02, 0x01, 0x00, 0x07, 0x06, 0x05, 0x04,
],
[ // 0x3a
0x0e, 0x0f, 0x0c, 0x0d, 0x0a, 0x0b, 0x08, 0x09, 0x06, 0x07, 0x04, 0x05, 0x02, 0x03, 0x00, 0x01,
0x1e, 0x1f, 0x1c, 0x1d, 0x1a, 0x1b, 0x18, 0x19, 0x16, 0x17, 0x14, 0x15, 0x12, 0x13, 0x10, 0x11,
0x2e, 0x2f, 0x2c, 0x2d, 0x2a, 0x2b, 0x28, 0x29, 0x26, 0x27, 0x24, 0x25, 0x22, 0x23, 0x20, 0x21,
0x3e, 0x3f, 0x3c, 0x3d, 0x3a, 0x3b, 0x38, 0x39, 0x36, 0x37, 0x34, 0x35, 0x32, 0x33, 0x30, 0x31,
],
[ // 0x3b
0x21, 0x20, 0x23, 0x22, 0x25, 0x24, 0x27, 0x26, 0x29, 0x28, 0x2b, 0x2a, 0x2d, 0x2c, 0x2f, 0x2e,
0x31, 0x30, 0x33, 0x32, 0x35, 0x34, 0x37, 0x36, 0x39, 0x38, 0x3b, 0x3a, 0x3d, 0x3c, 0x3f, 0x3e,
0x01, 0x00, 0x03, 0x02, 0x05, 0x04, 0x07, 0x06, 0x09, 0x08, 0x0b, 0x0a, 0x0d, 0x0c, 0x0f, 0x0e,
0x11, 0x10, 0x13, 0x12, 0x15, 0x14, 0x17, 0x16, 0x19, 0x18, 0x1b, 0x1a, 0x1d, 0x1c, 0x1f, 0x1e,
],
[ // 0x3c
0x34, 0x35, 0x36, 0x37, 0x30, 0x31, 0x32, 0x33, 0x3c, 0x3d, 0x3e, 0x3f, 0x38, 0x39, 0x3a, 0x3b,
0x24, 0x25, 0x26, 0x27, 0x20, 0x21, 0x22, 0x23, 0x2c, 0x2d, 0x2e, 0x2f, 0x28, 0x29, 0x2a, 0x2b,
0x14, 0x15, 0x16, 0x17, 0x10, 0x11, 0x12, 0x13, 0x1c, 0x1d, 0x1e, 0x1f, 0x18, 0x19, 0x1a, 0x1b,
0x04, 0x05, 0x06, 0x07, 0x00, 0x01, 0x02, 0x03, 0x0c, 0x0d, 0x0e, 0x0f, 0x08, 0x09, 0x0a, 0x0b,
],
[ // 0x3d
0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01, 0x00, 0x0f, 0x0e, 0x0d, 0x0c, 0x0b, 0x0a, 0x09, 0x08,
0x17, 0x16, 0x15, 0x14, 0x13, 0x12, 0x11, 0x10, 0x1f, 0x1e, 0x1d, 0x1c, 0x1b, 0x1a, 0x19, 0x18,
0x27, 0x26, 0x25, 0x24, 0x23, 0x22, 0x21, 0x20, 0x2f, 0x2e, 0x2d, 0x2c, 0x2b, 0x2a, 0x29, 0x28,
0x37, 0x36, 0x35, 0x34, 0x33, 0x32, 0x31, 0x30, 0x3f, 0x3e, 0x3d, 0x3c, 0x3b, 0x3a, 0x39, 0x38,
],
[ // 0x3e
0x1a, 0x1b, 0x18, 0x19, 0x1e, 0x1f, 0x1c, 0x1d, 0x12, 0x13, 0x10, 0x11, 0x16, 0x17, 0x14, 0x15,
0x0a, 0x0b, 0x08, 0x09, 0x0e, 0x0f, 0x0c, 0x0d, 0x02, 0x03, 0x00, 0x01, 0x06, 0x07, 0x04, 0x05,
0x3a, 0x3b, 0x38, 0x39, 0x3e, 0x3f, 0x3c, 0x3d, 0x32, 0x33, 0x30, 0x31, 0x36, 0x37, 0x34, 0x35,
0x2a, 0x2b, 0x28, 0x29, 0x2e, 0x2f, 0x2c, 0x2d, 0x22, 0x23, 0x20, 0x21, 0x26, 0x27, 0x24, 0x25,
],
[ // 0x3f
0x2d, 0x2c, 0x2f, 0x2e, 0x29, 0x28, 0x2b, 0x2a, 0x25, 0x24, 0x27, 0x26, 0x21, 0x20, 0x23, 0x22,
0x3d, 0x3c, 0x3f, 0x3e, 0x39, 0x38, 0x3b, 0x3a, 0x35, 0x34, 0x37, 0x36, 0x31, 0x30, 0x33, 0x32,
0x0d, 0x0c, 0x0f, 0x0e, 0x09, 0x08, 0x0b, 0x0a, 0x05, 0x04, 0x07, 0x06, 0x01, 0x00, 0x03, 0x02,
0x1d, 0x1c, 0x1f, 0x1e, 0x19, 0x18, 0x1b, 0x1a, 0x15, 0x14, 0x17, 0x16, 0x11, 0x10, 0x13, 0x12,
],
];
#endregion
}
}

View File

@@ -0,0 +1,91 @@
using System;
using static SabreTools.Hashing.SpamSum.Constants;
namespace SabreTools.Hashing.SpamSum
{
/// <see href="https://github.com/ssdeep-project/ssdeep/blob/master/fuzzy.c"/>
internal class FuzzyState
{
public ulong TotalSize { get; set; }
public ulong FixedSize { get; set; }
public ulong ReduceBorder { get; set; }
public uint BHStart { get; set; }
public uint BHEnd { get; set; }
public uint BHEndLimit { get; set; }
public uint Flags { get; set; }
public uint RollMask { get; set; }
public BlockhashContext[] BH { get; set; }
public RollState Roll { get; set; }
public byte LastH { get; set; }
public FuzzyState()
{
BH = new BlockhashContext[NUM_BLOCKHASHES];
for (int i = 0; i < NUM_BLOCKHASHES; i++)
{
BH[i] = new BlockhashContext();
}
Roll = new RollState();
}
public void TryForkBlockhash()
{
uint obh, nbh;
if (BHEnd <= 0)
throw new Exception("assert(BHEnd > 0)");
obh = BHEnd - 1;
if (BHEnd <= BHEndLimit)
{
nbh = obh + 1;
BH[nbh].H = BH[obh].H;
BH[nbh].HalfH = BH[obh].HalfH;
BH[nbh].Digest[0] = 0x00;
BH[nbh].HalfDigest = 0x00;
BH[nbh].DIndex = 0;
++BHEnd;
}
else if (BHEnd == NUM_BLOCKHASHES
&& ((Flags & FUZZY_STATE_NEED_LASTHASH) == 0))
{
Flags |= FUZZY_STATE_NEED_LASTHASH;
LastH = BH[obh].H;
}
}
public void TryReduceBlockhash()
{
if (BHStart >= BHEnd)
throw new Exception("assert(BHStart < BHEnd)");
// Need at least two working hashes.
if (BHEnd - BHStart < 2)
return;
// Initial blocksize estimate would select this or a smaller blocksize.
if (ReduceBorder >= (((Flags & FUZZY_STATE_SIZE_FIXED) != 0) ? FixedSize : TotalSize))
return;
// Estimate adjustment would select this blocksize.
if (BH[BHStart + 1].DIndex < SPAMSUM_LENGTH / 2)
return;
// At this point we are clearly no longer interested in the
// start_blocksize. Get rid of it.
++BHStart;
ReduceBorder *= 2;
RollMask = (RollMask * 2) + 1;
}
}
}

View File

@@ -0,0 +1,56 @@
using static SabreTools.Hashing.SpamSum.Constants;
namespace SabreTools.Hashing.SpamSum
{
/// <see href="https://github.com/ssdeep-project/ssdeep/blob/master/fuzzy.c"/>
internal class RollState
{
public byte[] Window { get; set; }
public uint H1 { get; set; }
public uint H2 { get; set; }
public uint H3 { get; set; }
public uint N { get; set; }
public RollState()
{
Window = new byte[ROLLING_WINDOW];
}
/// <summary>
/// A rolling hash, based on the Adler checksum. By using a rolling hash
/// we can perform auto resynchronisation after inserts/deletes.
///
/// Internally, H1 is the sum of the bytes in the window and H2
/// is the sum of the bytes times the index.
///
/// H3 is a shift/xor based rolling hash, and is mostly needed to ensure that
/// we can cope with large blocksize values.
/// </summary>
public void RollHash(byte c)
{
H2 -= H1;
H2 += ROLLING_WINDOW * c;
H1 += c;
H1 -= Window[N % ROLLING_WINDOW];
Window[N % ROLLING_WINDOW] = c;
N++;
// The original spamsum AND'ed this value with 0xFFFFFFFF which
// in theory should have no effect. This AND has been removed
// for performance (jk)
H3 <<= 5;
H3 ^= c;
}
/// <summary>
/// Return the current rolling sum
/// </summary>
public uint RollSum() => H1 + H2 + H3;
}
}

View File

@@ -0,0 +1,361 @@
using System;
using System.Text;
using static SabreTools.Hashing.SpamSum.Constants;
#pragma warning disable IDE0059 // Unnecessary assignment of a value
namespace SabreTools.Hashing.SpamSum
{
/// <see href="https://github.com/ssdeep-project/ssdeep/blob/master/fuzzy.c"/>
public class SpamSum : System.Security.Cryptography.HashAlgorithm
{
private FuzzyState _state;
public SpamSum()
{
_state = new();
Initialize();
}
/// <inheritdoc/>
public override void Initialize()
{
_state = new FuzzyState
{
BHStart = 0,
BHEnd = 1,
BHEndLimit = NUM_BLOCKHASHES - 1,
TotalSize = 0,
ReduceBorder = MIN_BLOCKSIZE * SPAMSUM_LENGTH,
Flags = 0,
RollMask = 0,
};
_state.BH[0].H = HASH_INIT;
_state.BH[0].HalfH = HASH_INIT;
_state.BH[0].Digest[0] = 0x00;
_state.BH[0].HalfDigest = 0x00;
_state.BH[0].DIndex = 0;
}
/// <inheritdoc cref="Comparisons.FuzzyCompare(string?, string?)"/>
public static int FuzzyCompare(string? firstHash, string? secondHash)
=> Comparisons.FuzzyCompare(firstHash, secondHash);
/// <inheritdoc/>
protected override void HashCore(byte[] array, int ibStart, int cbSize)
{
_state.TotalSize += (ulong)cbSize;
for (int i = ibStart; i < cbSize; i++)
{
ProcessByte(array[i]);
}
}
/// <inheritdoc/>
protected override byte[] HashFinal()
{
string? digest = Finalize(0);
if (digest is null)
return [];
return Encoding.ASCII.GetBytes(digest.TrimEnd('\0'));
}
/// <remarks>
/// Originally named `fuzzy_engine_step`
/// </remarks>
private void ProcessByte(byte c)
{
// At each character we update the rolling hash and the normal hashes.
// When the rolling hash hits a reset value then we emit a normal hash
// as a element of the signature and reset the normal hash.
_state.Roll.RollHash(c);
uint horg = _state.Roll.RollSum() + 1;
uint h = horg / MIN_BLOCKSIZE;
uint i;
for (i = _state.BHStart; i < _state.BHEnd; ++i)
{
_state.BH[i].H = SumHash(c, _state.BH[i].H);
_state.BH[i].HalfH = SumHash(c, _state.BH[i].HalfH);
}
if ((_state.Flags & FUZZY_STATE_NEED_LASTHASH) != 0)
_state.LastH = SumHash(c, _state.LastH);
// 0xffffffff !== -1 (mod 3)
if (horg == 0)
return;
// With growing blocksize almost no runs fail the next test.
if ((h & _state.RollMask) != 0)
return;
// Delay computation of modulo as possible.
if ((horg % MIN_BLOCKSIZE) != 0)
return;
h >>= (int)_state.BHStart;
i = _state.BHStart;
do
{
// We have hit a reset point. We now emit hashes which are
// based on all characters in the piece of the message between
// the last reset point and this one
if (_state.BH[i].DIndex == 0)
{
// Can only happen 30 times.
// First step for this blocksize. Clone next.
_state.TryForkBlockhash();
}
_state.BH[i].Digest[_state.BH[i].DIndex] = B64[_state.BH[i].H];
_state.BH[i].HalfDigest = B64[_state.BH[i].HalfH];
if (_state.BH[i].DIndex < SPAMSUM_LENGTH - 1)
{
// We can have a problem with the tail overflowing. The
// easiest way to cope with this is to only reset the
// normal hash if we have room for more characters in
// our signature. This has the effect of combining the
// last few pieces of the message into a single piece
_state.BH[i].Digest[++_state.BH[i].DIndex] = 0x00;
_state.BH[i].H = HASH_INIT;
if (_state.BH[i].DIndex < SPAMSUM_LENGTH / 2)
{
_state.BH[i].HalfH = HASH_INIT;
_state.BH[i].HalfDigest = 0x00;
}
}
else
{
_state.TryReduceBlockhash();
}
if ((h & 1) != 0)
break;
h >>= 1;
} while (++i < _state.BHEnd);
}
/// <summary>
/// A simple non-rolling hash, based on the FNV hash
/// </summary>
private static byte SumHash(byte c, byte h) => SUM_TABLE[h][c & 0x3f];
/// <remarks>
/// Originally named `fuzzy_digest`
/// </remarks>
private string? Finalize(uint flags)
{
uint bi = _state.BHStart;
uint h = _state.Roll.RollSum();
int i;
// Exclude terminating '\0'.
int remain = FUZZY_MAX_RESULT - 1;
// Verify that our elimination was not overeager.
if (bi != 0 && (ulong)SSDEEP_BS(bi) / 2 * SPAMSUM_LENGTH >= _state.TotalSize)
return null;
// The input exceeds data types.
if (_state.TotalSize > SSDEEP_TOTAL_SIZE_MAX)
return null;
// Initial blocksize guess.
while ((ulong)SSDEEP_BS(bi) * SPAMSUM_LENGTH < _state.TotalSize)
{
++bi;
}
// Adapt blocksize guess to actual digest length.
if (bi >= _state.BHEnd)
bi = _state.BHEnd - 1;
while (bi > _state.BHStart && _state.BH[bi].DIndex < SPAMSUM_LENGTH / 2)
{
--bi;
}
if (bi > 0 && _state.BH[bi].DIndex < SPAMSUM_LENGTH / 2)
return null;
byte[] result = new byte[FUZZY_MAX_RESULT];
int resultPtr = 0;
string prefixStr = $"{(ulong)SSDEEP_BS(bi)}:";
byte[] prefixArr = Encoding.ASCII.GetBytes(prefixStr);
Array.Copy(prefixArr, result, prefixArr.Length);
i = prefixArr.Length;
if (i >= remain)
return null;
remain -= i;
resultPtr += i;
i = (int)_state.BH[bi].DIndex;
if (i > remain)
return null;
if ((flags & FUZZY_FLAG_ELIMSEQ) != 0)
i = EliminateSequences(result, resultPtr, _state.BH[bi].Digest, 0, i);
else
Array.Copy(_state.BH[bi].Digest, 0, result, resultPtr, i);
resultPtr += i;
remain -= i;
if (h != 0)
{
if (remain <= 0)
return null;
result[resultPtr] = B64[_state.BH[bi].H];
if ((flags & FUZZY_FLAG_ELIMSEQ) == 0
|| i < 3
|| result[resultPtr] != result[resultPtr - 1]
|| result[resultPtr] != result[resultPtr - 2]
|| result[resultPtr] != result[resultPtr - 3])
{
++resultPtr;
--remain;
}
}
else if (_state.BH[bi].Digest[_state.BH[bi].DIndex] != '\0')
{
if (remain <= 0)
return null;
result[resultPtr] = _state.BH[bi].Digest[_state.BH[bi].DIndex];
if ((flags & FUZZY_FLAG_ELIMSEQ) == 0
|| i < 3
|| result[resultPtr] != result[resultPtr - 1]
|| result[resultPtr] != result[resultPtr - 2]
|| result[resultPtr] != result[resultPtr - 3])
{
++resultPtr;
--remain;
}
}
if (remain <= 0)
return null;
result[resultPtr++] = (byte)':';
--remain;
if (bi < _state.BHEnd - 1)
{
++bi;
i = (int)_state.BH[bi].DIndex;
if ((flags & FUZZY_FLAG_NOTRUNC) == 0 && i > (SPAMSUM_LENGTH / 2) - 1)
i = (SPAMSUM_LENGTH / 2) - 1;
if (i > remain)
return null;
if ((flags & FUZZY_FLAG_ELIMSEQ) != 0)
i = EliminateSequences(result, resultPtr, _state.BH[bi].Digest, 0, i);
else
Array.Copy(_state.BH[bi].Digest, 0, result, resultPtr, i);
resultPtr += i;
remain -= i;
if (h != 0)
{
if (remain <= 0)
return null;
h = (flags & FUZZY_FLAG_NOTRUNC) != 0
? _state.BH[bi].H
: _state.BH[bi].HalfH;
result[resultPtr] = B64[h];
if ((flags & FUZZY_FLAG_ELIMSEQ) == 0
|| i < 3
|| result[resultPtr] != result[resultPtr - 1]
|| result[resultPtr] != result[resultPtr - 2]
|| result[resultPtr] != result[resultPtr - 3])
{
++resultPtr;
--remain;
}
}
else
{
i = (flags & FUZZY_FLAG_NOTRUNC) != 0
? _state.BH[bi].Digest[_state.BH[bi].DIndex]
: _state.BH[bi].HalfDigest;
if (i != 0x00)
{
if (remain <= 0)
return null;
result[resultPtr] = (byte)i;
if ((flags & FUZZY_FLAG_ELIMSEQ) == 0
|| i < 3
|| result[resultPtr] != result[resultPtr - 1]
|| result[resultPtr] != result[resultPtr - 2]
|| result[resultPtr] != result[resultPtr - 3])
{
++resultPtr;
--remain;
}
}
}
}
else if (h != 0)
{
if (bi != 0 && bi != NUM_BLOCKHASHES - 1)
return null;
if (remain <= 0)
return null;
if (bi == 0)
result[resultPtr++] = B64[_state.BH[bi].H];
else
result[resultPtr++] = B64[_state.LastH];
/* No need to bother with FUZZY_FLAG_ELIMSEQ, because this
* digest has length 1. */
--remain;
}
result[resultPtr] = 0x00;
return Encoding.ASCII.GetString(result);
}
/// <remarks>
/// Originally named `memcpy_eliminate_sequences`
/// </remarks>
private static int EliminateSequences(byte[] dst, int dstPtr, byte[] src, int srcPtr, int n)
{
int srcend = srcPtr + n;
if (n < 0)
throw new ArgumentOutOfRangeException(nameof(n));
if (srcPtr < srcend) dst[dstPtr++] = src[srcPtr++];
if (srcPtr < srcend) dst[dstPtr++] = src[srcPtr++];
if (srcPtr < srcend) dst[dstPtr++] = src[srcPtr++];
while (srcPtr < srcend)
{
if (src[srcPtr] == dst[dstPtr - 1]
&& src[srcPtr] == dst[dstPtr - 2]
&& src[srcPtr] == dst[dstPtr - 3])
{
++srcPtr;
--n;
}
else
{
dst[dstPtr++] = src[srcPtr++];
}
}
return n;
}
}
}

View File

@@ -1,185 +0,0 @@
using System;
namespace SabreTools.Hashing.Tiger
{
/// <summary>
/// Reference implementation of the Tiger hash
/// </summary>
/// <see href="https://biham.cs.technion.ac.il/Reports/Tiger/"/>
public class TigerHash
{
/// <summary>
/// The number of passes of the hash function.
/// Three passes are recommended.
/// Use four passes when you need extra security.
/// Must be at least three.
/// </summary>
private const int PASSES = 3;
public void tiger(ulong[] str, ulong length)
{
ulong i, j;
byte[] temp = new byte[64];
ulong[] res =
[
0x0123456789ABCDEF,
0xFEDCBA9876543210,
0xF096A5B4C3B2E187
];
int strOffset = 0;
for (i = length; i >= 64; i -= 64)
{
Compress(str, strOffset, res);
strOffset += 8;
}
byte[] strBytes = new byte[str.Length * 8];
Array.ConstrainedCopy(str, 0, strBytes, 0, str.Length);
for (j = 0; j < i; j++)
{
temp[j] = strBytes[j];
}
temp[j++] = 0x01;
for (; (j & 7) > 0; j++)
{
temp[j] = 0;
}
if (j > 56)
{
for (; j < 64; j++)
{
temp[j] = 0;
}
Compress(ref temp, 0, res);
j = 0;
}
for (; j < 56; j++)
{
temp[j] = 0;
}
Compress(ref temp, 0, res, true, length);
}
private static bool Compress(ref byte[] str, int strOffset, ulong[] state, bool shouldSetSeven = false, ulong length = 0)
{
// Create the temp array
ulong[] temp = new ulong[str.Length / 8];
Array.ConstrainedCopy(str, 0, temp, 0, str.Length);
// Set index 7, if required
if (shouldSetSeven)
temp[7] = length << 3;
// Run the compression
bool success = Compress(temp, strOffset, state);
// Copy the values back
Array.ConstrainedCopy(temp, 0, str, 0, temp.Length);
return success;
}
private static bool Compress(ulong[] str, int strOffset, ulong[] state)
{
// Bounds checking
if (state.Length != 3)
return false;
if (str.Length < strOffset + 8)
return false;
ulong[] x = new ulong[8];
Array.Copy(str, strOffset, x, 0, 8);
// save_abc
ulong aa = state[0];
ulong bb = state[1];
ulong cc = state[2];
for (int pass_no = 0; pass_no < PASSES; pass_no++)
{
if (pass_no != 0)
KeySchedule(x);
int mul = pass_no == 0 ? 5 : pass_no == 1 ? 7 : 9;
Pass(state, x, mul);
ulong temp = state[0]; state[0] = state[2]; state[2] = state[1]; state[1] = temp;
}
// feedforward
state[0] ^= aa;
state[1] -= bb;
state[2] += cc;
return true;
}
private static void KeySchedule(ulong[] x)
{
x[0] -= x[7] ^ 0xA5A5A5A5A5A5A5A5;
x[1] ^= x[0];
x[2] += x[1];
x[3] -= x[2] ^ ((~x[1]) << 19);
x[4] ^= x[3];
x[5] += x[4];
x[6] -= x[5] ^ ((~x[4]) >> 23);
x[7] ^= x[6];
x[0] += x[7];
x[1] -= x[0] ^ ((~x[7]) << 19);
x[2] ^= x[1];
x[3] += x[2];
x[4] -= x[3] ^ ((~x[2]) >> 23);
x[5] ^= x[4];
x[6] += x[5];
x[7] -= x[6] ^ 0x0123456789ABCDEF;
}
private static bool Pass(ulong[] state, ulong[] x, int mul)
{
// Bounds checking
if (state.Length != 3)
return false;
Round(state, 0, 1, 2, x[0], mul);
Round(state, 1, 2, 0, x[1], mul);
Round(state, 2, 0, 1, x[2], mul);
Round(state, 0, 1, 2, x[3], mul);
Round(state, 1, 2, 0, x[4], mul);
Round(state, 2, 0, 1, x[5], mul);
Round(state, 0, 1, 2, x[6], mul);
Round(state, 1, 2, 0, x[7], mul);
return true;
}
private static bool Round(ulong[] state, int a, int b, int c, ulong x, int mul)
{
// Bounds checking
if (state.Length != 3)
return false;
state[c] ^= x;
state[a] -= t1((byte)state[c])
^ t2((byte)(((uint)state[c]) >> (2 * 8)))
^ t3((byte)((state[c]) >> (4 * 8)))
^ t4((byte)(((uint)((state[c]) >> (4 * 8))) >> (2 * 8)));
state[b] += t4((byte)(((uint)state[c]) >> (1 * 8)))
^ t3((byte)(((uint)state[c]) >> (3 * 8)))
^ t2((byte)(((uint)((state[c]) >> (4 * 8))) >> (1 * 8)))
^ t1((byte)(((uint)((state[c]) >> (4 * 8))) >> (3 * 8)));
state[b] *= (ulong)mul;
return true;
}
private static ulong t1(int offset) => SBoxes.Table[offset];
private static ulong t2(int offset) => SBoxes.Table[offset + 256];
private static ulong t3(int offset) => SBoxes.Table[offset + 256 * 2];
private static ulong t4(int offset) => SBoxes.Table[offset + 256 * 3];
}
}

View File

@@ -0,0 +1,71 @@
#pragma warning disable IDE0051 // Remove unused private members
namespace SabreTools.Hashing.XxHash
{
// https://github.com/Cyan4973/xxHash/blob/dev/xxhash.h
internal static class Constants
{
#region Version
public const int XXH_VERSION_MAJOR = 0;
public const int XXH_VERSION_MINOR = 8;
public const int XXH_VERSION_RELEASE = 3;
#endregion
#region XXH3
/// <summary>
/// Pseudorandom secret taken directly from FARSH.
/// </summary>
public static readonly byte[] XXH3_kSecret =
[
0xb8, 0xfe, 0x6c, 0x39, 0x23, 0xa4, 0x4b, 0xbe, 0x7c, 0x01, 0x81, 0x2c, 0xf7, 0x21, 0xad, 0x1c,
0xde, 0xd4, 0x6d, 0xe9, 0x83, 0x90, 0x97, 0xdb, 0x72, 0x40, 0xa4, 0xa4, 0xb7, 0xb3, 0x67, 0x1f,
0xcb, 0x79, 0xe6, 0x4e, 0xcc, 0xc0, 0xe5, 0x78, 0x82, 0x5a, 0xd0, 0x7d, 0xcc, 0xff, 0x72, 0x21,
0xb8, 0x08, 0x46, 0x74, 0xf7, 0x43, 0x24, 0x8e, 0xe0, 0x35, 0x90, 0xe6, 0x81, 0x3a, 0x26, 0x4c,
0x3c, 0x28, 0x52, 0xbb, 0x91, 0xc3, 0x00, 0xcb, 0x88, 0xd0, 0x65, 0x8b, 0x1b, 0x53, 0x2e, 0xa3,
0x71, 0x64, 0x48, 0x97, 0xa2, 0x0d, 0xf9, 0x4e, 0x38, 0x19, 0xef, 0x46, 0xa9, 0xde, 0xac, 0xd8,
0xa8, 0xfa, 0x76, 0x3f, 0xe3, 0x9c, 0x34, 0x3f, 0xf9, 0xdc, 0xbb, 0xc7, 0xc7, 0x0b, 0x4f, 0x1d,
0x8a, 0x51, 0xe0, 0x4b, 0xcd, 0xb4, 0x59, 0x31, 0xc8, 0x9f, 0x7e, 0xc9, 0xd9, 0x78, 0x73, 0x64,
0xea, 0xc5, 0xac, 0x83, 0x34, 0xd3, 0xeb, 0xc3, 0xc5, 0x81, 0xa0, 0xff, 0xfa, 0x13, 0x63, 0xeb,
0x17, 0x0d, 0xdd, 0x51, 0xb7, 0xf0, 0xda, 0x49, 0xd3, 0x16, 0x55, 0x26, 0x29, 0xd4, 0x68, 0x9e,
0x2b, 0x16, 0xbe, 0x58, 0x7d, 0x47, 0xa1, 0xfc, 0x8f, 0xf8, 0xb8, 0xd1, 0x7a, 0xd0, 0x31, 0xce,
0x45, 0xcb, 0x3a, 0x8f, 0x95, 0x16, 0x04, 0x28, 0xaf, 0xd7, 0xfb, 0xca, 0xbb, 0x4b, 0x40, 0x7e,
];
public const ulong PRIME_MX1 = 0x165667919E3779F9;
public const ulong PRIME_MX2 = 0x9FB21C651E98DF25;
/// <summary>
/// The size of the internal XXH3 buffer.
/// This is the optimal update size for incremental hashing.
/// </summary>
public const int XXH3_INTERNALBUFFER_SIZE = 256;
/// <summary>
/// The bare minimum size for a custom secret.
/// </summary>
public const int XXH3_SECRET_SIZE_MIN = 136;
/// <summary>
/// Default size of the secret buffer (and <see cref="XXH3_kSecret"/>).
/// This is the size used in <see cref="XXH3_kSecret"/> and the seeded functions.
/// Not to be confused with @ref XXH3_SECRET_SIZE_MIN.
/// </summary>
public const int XXH3_SECRET_DEFAULT_SIZE = 192;
public const int XXH_STRIPE_LEN = 64;
/// <summary>
/// Number of secret bytes consumed at each accumulation
/// </summary>
public const int XXH_SECRET_CONSUME_RATE = 8;
private const int XXH_ACC_NB = XXH_STRIPE_LEN / sizeof(ulong);
#endregion
}
}

View File

@@ -0,0 +1,74 @@
namespace SabreTools.Hashing.XxHash
{
// https://github.com/Cyan4973/xxHash/blob/dev/xxhash.h
internal enum ErrorCode
{
/// <summary>
/// OK
/// </summary>
XXH_OK = 0,
/// <summary>
/// Error
/// </summary>
XXH_ERROR,
}
// https://github.com/Cyan4973/xxHash/blob/dev/xxhash.h
internal enum Alignment
{
/// <summary>
/// Aligned
/// </summary>
XXH_aligned,
/// <summary>
/// Possibly unaligned
/// </summary>
XXH_unaligned,
}
// https://github.com/Cyan4973/xxHash/blob/dev/xxhash.h
internal enum VectorType
{
/// <summary>
/// Portable scalar version
/// </summary>
XXH_SCALAR = 0,
/// <summary>
/// SSE2 for Pentium 4, Opteron, all x86_64.
/// </summary>
/// <remarks>
/// SSE2 is also guaranteed on Windows 10, macOS, and Android x86.
/// </remarks>
XXH_SSE2 = 1,
/// <summary>
/// AVX2 for Haswell and Bulldozer
/// </summary>
XXH_AVX2 = 2,
/// <summary>
/// AVX512 for Skylake and Icelake
/// </summary>
XXH_AVX512 = 3,
/// <summary>
/// NEON for most ARMv7-A, all AArch64, and WASM SIMD128
/// via the SIMDeverywhere polyfill provided with the
/// Emscripten SDK.
/// </summary>
XXH_NEON = 4,
/// <summary>
/// VSX and ZVector for POWER8/z13 (64-bit)
/// </summary>
XXH_VSX = 5,
/// <summary>
/// SVE for some ARMv8-A and ARMv9-A
/// </summary>
XXH_SVE = 6,
}
}

View File

@@ -0,0 +1,252 @@
using static SabreTools.Hashing.HashOperations;
using static SabreTools.Hashing.NonCryptographicHash.Constants;
using static SabreTools.Hashing.XxHash.Constants;
namespace SabreTools.Hashing.XxHash
{
internal static class Utility
{
#region Multiply and Fold
/// <summary>
/// Calculates a 64-bit to 128-bit multiply, then XOR folds it.
/// </summary>
public static ulong MultiplyTo128Fold64(ulong lhs, ulong rhs)
{
var product = MultiplyTo128(lhs, rhs);
return product.Low ^ product.High;
}
/// <summary>
/// Calculates a 32-bit to 64-bit long multiply.
/// </summary>
public static ulong MultiplyTo64(ulong x, ulong y)
{
return (x & 0xFFFFFFFF) * (y & 0xFFFFFFFF);
}
/// <summary>
/// Calculates a 64->128-bit long multiply.
/// </summary>
public static XXH3_128Hash MultiplyTo128(ulong lhs, ulong rhs)
{
// First calculate all of the cross products.
ulong lo_lo = MultiplyTo64(lhs & 0xFFFFFFFF, rhs & 0xFFFFFFFF);
ulong hi_lo = MultiplyTo64(lhs >> 32, rhs & 0xFFFFFFFF);
ulong lo_hi = MultiplyTo64(lhs & 0xFFFFFFFF, rhs >> 32);
ulong hi_hi = MultiplyTo64(lhs >> 32, rhs >> 32);
// Now add the products together. These will never overflow.
ulong cross = (lo_lo >> 32) + (hi_lo & 0xFFFFFFFF) + lo_hi;
ulong upper = (hi_lo >> 32) + (cross >> 32) + hi_hi;
ulong lower = (cross << 32) | (lo_lo & 0xFFFFFFFF);
return new XXH3_128Hash
{
Low = lower,
High = upper,
};
}
#endregion
#region Shift
public static ulong XorShift64(ulong v64, int shift)
{
return v64 ^ (v64 >> shift);
}
#endregion
#region XXH64 Common
/// <summary>
/// Mixes all bits to finalize the hash.
///
/// The final mix ensures that all input bits have a chance to impact any bit in
/// the output digest, resulting in an unbiased distribution.
/// </summary>
public static ulong XXH64Avalanche(ulong hash)
{
hash ^= hash >> 33;
hash *= XXH_PRIME64_2;
hash ^= hash >> 29;
hash *= XXH_PRIME64_3;
hash ^= hash >> 32;
return hash;
}
#endregion
#region XXH3 Common
/// <summary>
/// This is a fast avalanche stage,
/// suitable when input bits are already partially mixed
/// </summary>
public static ulong XXH3Avalanche(ulong hash)
{
hash = XorShift64(hash, 37);
hash *= PRIME_MX1;
hash = XorShift64(hash, 32);
return hash;
}
/// <summary>
/// This is a stronger avalanche,
/// inspired by Pelle Evensen's rrmxmx
/// preferable when input has not been previously mixed
/// </summary>
public static ulong XXH3Rrmxmx(ulong hash, ulong length)
{
// This mix is inspired by Pelle Evensen's rrmxmx
hash ^= RotateLeft64(hash, 49) ^ RotateLeft64(hash, 24);
hash *= PRIME_MX2;
hash ^= (hash >> 35) + length;
hash *= PRIME_MX2;
return XorShift64(hash, 28);
}
/// <summary>
/// Handle length 1 to 3 values
/// </summary>
public static ulong Len1To3Out64(byte[] data, int offset, int length, byte[] secret, ulong seed)
{
byte c1 = data[offset + 0];
byte c2 = data[offset + (length >> 1)];
byte c3 = data[offset + (length - 1)];
uint combined = ((uint)c1 << 16)
| ((uint)c2 << 24)
| ((uint)c3 << 0)
| ((uint)length << 8);
ulong bitflip = (ReadLE32(secret, 0) ^ ReadLE32(secret, 4)) + seed;
ulong keyed = combined ^ bitflip;
return XXH64Avalanche(keyed);
}
/// <summary>
/// Handle length 4 to 8 values
/// </summary>
public static ulong Len4To8Out64(byte[] data, int offset, int length, byte[] secret, ulong seed)
{
seed ^= (ulong)Swap32((uint)seed) << 32;
uint input1 = ReadLE32(data, offset);
uint input2 = ReadLE32(data, offset + length - 4);
ulong bitflip = (ReadLE64(secret, 8) ^ ReadLE64(secret, 16)) - seed;
ulong input64 = input2 + (((ulong)input1) << 32);
ulong keyed = input64 ^ bitflip;
return XXH3Rrmxmx(keyed, (ulong)length);
}
/// <summary>
/// Handle length 9 to 16 values
/// </summary>
public static ulong Len9To16Out64(byte[] data, int offset, int length, byte[] secret, ulong seed)
{
ulong bitflip1 = (ReadLE64(secret, 24) ^ ReadLE64(secret, 32)) + seed;
ulong bitflip2 = (ReadLE64(secret, 40) ^ ReadLE64(secret, 48)) - seed;
ulong input_lo = ReadLE64(data, offset) ^ bitflip1;
ulong input_hi = ReadLE64(data, offset + length - 8) ^ bitflip2;
ulong acc = (ulong)length
+ Swap64(input_lo) + input_hi
+ MultiplyTo128Fold64(input_lo, input_hi);
return XXH3Avalanche(acc);
}
/// <summary>
/// Handle length 0 to 16 values
/// </summary>
public static ulong Len0To16Out64(byte[] data, int offset, int length, byte[] secret, ulong seed)
{
if (length > 8)
return Len9To16Out64(data, offset, length, secret, seed);
if (length >= 4)
return Len4To8Out64(data, offset, length, secret, seed);
if (length > 0)
return Len1To3Out64(data, offset, length, secret, seed);
return XXH64Avalanche(seed ^ ReadLE64(secret, 56) ^ ReadLE64(secret, 64));
}
public static ulong Mix16B(byte[] data, int offset, byte[] secret, int secretOffset, ulong seed)
{
ulong input_lo = ReadLE64(data, offset + 0);
ulong input_hi = ReadLE64(data, offset + 8);
return MultiplyTo128Fold64(
input_lo ^ (ReadLE64(secret, secretOffset + 0) + seed),
input_hi ^ (ReadLE64(secret, secretOffset + 8) - seed)
);
}
/// <summary>
/// Handle length 7 to 128 values
/// </summary>
public static ulong Len17To128Out64(byte[] data, int offset, int length, byte[] secret, ulong seed)
{
ulong acc = (ulong)length * XXH_PRIME64_1;
if (length > 32)
{
if (length > 64)
{
if (length > 96)
{
acc += Mix16B(data, offset + 48, secret, 96, seed);
acc += Mix16B(data, offset + length - 64, secret, 112, seed);
}
acc += Mix16B(data, offset + 32, secret, 64, seed);
acc += Mix16B(data, offset + length - 48, secret, 80, seed);
}
acc += Mix16B(data, offset + 16, secret, 32, seed);
acc += Mix16B(data, offset + length - 32, secret, 48, seed);
}
acc += Mix16B(data, offset + 0, secret, 0, seed);
acc += Mix16B(data, offset + length - 16, secret, 16, seed);
return XXH3Avalanche(acc);
}
/// <summary>
/// Handle length 129 to 240 values
/// </summary>
public static ulong Len129To240Out64(byte[] data, int offset, int length, byte[] secret, ulong seed)
{
const int XXH3_MIDSIZE_STARTOFFSET = 3;
const int XXH3_MIDSIZE_LASTOFFSET = 17;
ulong acc = (ulong)length * XXH_PRIME64_1;
ulong acc_end;
uint nbRounds = (uint)length / 16;
uint i;
for (i = 0; i < 8; i++)
{
acc += Mix16B(data, offset + (int)(16 * i), secret, (int)(16 * i), seed);
}
// Last bytes
acc_end = Mix16B(data, offset + length - 16, secret, XXH3_SECRET_SIZE_MIN - XXH3_MIDSIZE_LASTOFFSET, seed);
acc = XXH3Avalanche(acc);
for (i = 8; i < nbRounds; i++)
{
acc_end += Mix16B(data, offset + (int)(16 * i), secret, (int)(16 * (i - 8)) + XXH3_MIDSIZE_STARTOFFSET, seed);
}
return XXH3Avalanche(acc + acc_end);
}
#endregion
}
}

View File

@@ -0,0 +1,9 @@
namespace SabreTools.Hashing.XxHash
{
internal class XXH3_128Hash
{
public ulong Low { get; set; }
public ulong High { get; set; }
}
}

View File

@@ -0,0 +1,133 @@
#pragma warning disable CS0169 // Private field is never used
#pragma warning disable CS0414 // Private field is assigned but its value is never used
#pragma warning disable CS0649 // Field is never assigned to
#pragma warning disable IDE0044 // Add readonly modifier
#pragma warning disable IDE0051 // Remove unused private members
#pragma warning disable IDE0052 // Remove unread private members
#pragma warning disable IDE0060 // Remove unused parameter
namespace SabreTools.Hashing.XxHash
{
/// <summary>
/// Structure for XXH3 streaming API.
/// </summary>
/// <see href="https://github.com/Cyan4973/xxHash/blob/dev/xxhash.h"/>
internal class XXH3_128State
{
/// <summary>
/// Accumulator lanes
/// </summary>
private readonly ulong[] _acc = new ulong[8];
/// <summary>
/// Used to store a custom secret generated from a seed.
/// </summary>
private readonly byte[] _customSecret = new byte[Constants.XXH3_SECRET_DEFAULT_SIZE];
/// <summary>
/// The internal buffer. <see cref="XXH32State._mem32"/>
/// </summary>
private readonly byte[] _buffer = new byte[Constants.XXH3_INTERNALBUFFER_SIZE];
/// <summary>
/// The amount of memory in <see cref="_buffer"/>, <see cref="XXH32State._memsize"/>
/// </summary>
private uint _bufferedSize;
/// <summary>
/// Reserved field. Needed for padding on 64-bit.
/// </summary>
private uint _useSeed;
/// <summary>
/// Number or stripes processed.
/// </summary>
private ulong _stripesSoFar;
/// <summary>
/// Total length hashed. 64-bit even on 32-bit targets.
/// </summary>
private ulong _totalLength;
/// <summary>
/// Number of stripes per block.
/// </summary>
private ulong _stripesPerBlock;
/// <summary>
/// Size of <see cref="_customSecret"/> or <see cref="_extSecret">
/// </summary>
private ulong _secretLimit;
/// <summary>
/// Seed for _withSeed variants. Must be zero otherwise, @see XXH3_INITSTATE()
/// </summary>
private ulong _seed;
/// <summary>
/// Reference to an external secret for the _withSecret variants, NULL
/// for other variants.
/// </summary>
/// <remarks>There may be some padding at the end due to alignment on 64 bytes</remarks>
private byte[]? _extSecret = null;
/// <param name="seed">The 64-bit seed to alter the hash result predictably.</param>
public XXH3_128State(ulong seed = 0)
{
// TODO: XXH3_128bits_withSeed
}
/// <param name="secret">The secret data.</param>
public XXH3_128State(byte[] secret)
{
// TODO: XXH3_128bits_withSecret
}
/// <summary>
/// Resets to begin a new hash
/// </summary>
/// <param name="seed">The 64-bit seed to alter the hash result predictably.</param>
public void Reset()
{
// TODO: XXH3_128bits_reset
}
/// <summary>
/// Resets to begin a new hash
/// </summary>
/// <param name="seed">The 64-bit seed to alter the hash result predictably.</param>
public void Reset(ulong seed)
{
// TODO: XXH3_128bits_reset_withSeed
}
/// <summary>
/// Resets to begin a new hash
/// </summary>
/// <param name="secret">The secret data.</param>
public void Reset(byte[] secret)
{
// TODO: XXH3_128bits_reset_withSecret
}
/// <summary>
/// Hash a block of data and append it to the existing hash
/// </summary>
/// <param name="data">Byte array representing the data</param>
/// <param name="offset">Offset in the byte array to include</param>
/// <param name="length">Length of the data to hash</param>
public void TransformBlock(byte[] data, int offset, int length)
{
// TODO: XXH3_128bits_update
}
/// <summary>
/// Returns the calculated hash value
/// </summary>
/// <returns>The calculated 64-bit xxHash64 value from that state.</returns>
public ulong Digest()
{
// TODO: XXH3_128bits_digest
return ulong.MaxValue;
}
}
}

Some files were not shown because too many files have changed in this diff Show More