Skip to content

Commit

Permalink
Fix icsharpcode#3153: Always use SHA1 for public key tokens. Accordin…
Browse files Browse the repository at this point in the history
…g to ECMA-335, the hash algorithm stored in the assembly metadata is intended for file content verification purposes, not identification purposes.
  • Loading branch information
siegfriedpammer authored and matt committed Jul 30, 2024
1 parent f259281 commit 4da6fff
Showing 1 changed file with 2 additions and 27 deletions.
29 changes: 2 additions & 27 deletions ICSharpCode.Decompiler/Metadata/MetadataExtensions.cs
Original file line number Diff line number Diff line change
@@ -1,15 +1,12 @@
using System;
using System.Buffers.Binary;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using System.Reflection;
using System.Reflection.Metadata;
using System.Reflection.Metadata.Ecma335;
using System.Reflection.PortableExecutable;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

using ICSharpCode.Decompiler.TypeSystem;
using ICSharpCode.Decompiler.TypeSystem.Implementation;
Expand All @@ -21,33 +18,11 @@ namespace ICSharpCode.Decompiler.Metadata
{
public static class MetadataExtensions
{
static HashAlgorithm GetHashAlgorithm(this MetadataReader reader)
{
switch (reader.GetAssemblyDefinition().HashAlgorithm)
{
case AssemblyHashAlgorithm.None:
// only for multi-module assemblies?
return SHA1.Create();
case AssemblyHashAlgorithm.MD5:
return MD5.Create();
case AssemblyHashAlgorithm.Sha1:
return SHA1.Create();
case AssemblyHashAlgorithm.Sha256:
return SHA256.Create();
case AssemblyHashAlgorithm.Sha384:
return SHA384.Create();
case AssemblyHashAlgorithm.Sha512:
return SHA512.Create();
default:
return SHA1.Create(); // default?
}
}

static string CalculatePublicKeyToken(BlobHandle blob, MetadataReader reader)
{
// Calculate public key token:
// 1. hash the public key using the appropriate algorithm.
byte[] publicKeyTokenBytes = reader.GetHashAlgorithm().ComputeHash(reader.GetBlobBytes(blob));
// 1. hash the public key (always use SHA1).
byte[] publicKeyTokenBytes = SHA1.Create().ComputeHash(reader.GetBlobBytes(blob));
// 2. take the last 8 bytes
// 3. according to Cecil we need to reverse them, other sources did not mention this.
return publicKeyTokenBytes.TakeLast(8).Reverse().ToHexString(8);
Expand Down

0 comments on commit 4da6fff

Please sign in to comment.