Skip to content

Instantly share code, notes, and snippets.

@AArnott
Last active July 14, 2017 12:39
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AArnott/94439bc9f6b5a21aba7ec226d01205c1 to your computer and use it in GitHub Desktop.
Save AArnott/94439bc9f6b5a21aba7ec226d01205c1 to your computer and use it in GitHub Desktop.
Demonstrates calculating a strong name token from a public key
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
namespace ConsoleApp43
{
static class Program
{
static void Main(string[] args)
{
byte[] publicKey = File.ReadAllBytes(@"C:\git\Nerdbank.GitVersioning\src\NerdBank.GitVersioning.Tests\Keys\public.snk");
byte[] token = StrongNameTokenFromPublicKey(publicKey);
Console.WriteLine($"Public key: {publicKey.AsHex()}");
Console.WriteLine($"Public key token: {token.AsHex()}");
}
private static byte[] StrongNameTokenFromPublicKey(byte[] publicKey)
{
// Reverse engineered from the implementation found here:
// https://github.com/dotnet/coreclr/blob/2efbb9282c059eb9742ba5a59b8a1d52ac4dfa4c/src/strongname/api/strongname.cpp#L387
const int cbToken = 8;
var sha1Algorithm = SHA1.Create();
byte[] hash = sha1Algorithm.ComputeHash(publicKey);
int cbHashLengthMinusTokenSize = hash.Length - cbToken;
byte[] token = new byte[cbToken];
for (int i = 0; i < cbToken; i++)
{
token[cbToken - (i + 1)] = hash[i + cbHashLengthMinusTokenSize];
}
return token;
}
static string AsHex(this byte[] buffer)
{
var sb = new StringBuilder(buffer.Length * 2);
for (int i = 0; i < buffer.Length; i++)
{
sb.AppendFormat("{0:x2}", buffer[i]);
}
return sb.ToString();
}
}
}
@AArnott
Copy link
Author

AArnott commented Mar 13, 2017

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment