Obtain .NET PublicKeyToken from snk file?

Two steps are required to extract Public Key Token from .snk file using the sn.exe.

Extract the Public Key from YourFile.snk using sn.exe and write it to Token.snk

sn -p YourFile.snk Token.snk

Extract the Public Key Token from Token.snk using sn.exe and write it to PublicToken.txt

sn -t Token.snk > PublicToken.txt


If you want to use the sn.exe tool:

sn -p yourkey.snk publickey.snk

now there is the publickey.snk with only the public key

sn -tp publickey.snk

now you have both the public key and the public key token.


Given a byte[] cotnaining the snk file, like

byte[] snk = File.ReadAllBytes("YourSnkFile.snk");

use

byte[] publicKey = GetPublicKey(snk);
byte[] publicKeyToken = GetPublicKeyToken(publicKey);

with these utility methods

public static byte[] GetPublicKey(byte[] snk)
{
    var snkp = new StrongNameKeyPair(snk);
    byte[] publicKey = snkp.PublicKey;
    return publicKey;
}

public static byte[] GetPublicKeyToken(byte[] publicKey)
{
    using (var csp = new SHA1CryptoServiceProvider())
    {
        byte[] hash = csp.ComputeHash(publicKey);

        byte[] token = new byte[8];

        for (int i = 0; i < 8; i++)
        {
            token[i] = hash[hash.Length - i - 1];
        }

        return token;
    }
}

In addition to @xanatos answer, PowerShell version if anyone needs it:

function Get-SnkPublicKey([string]$FilePath)
{
    $bytes = [System.IO.File]::ReadAllBytes($FilePath)
    $pair = New-Object System.Reflection.StrongNameKeyPair -ArgumentList @(,$bytes)
    $publicKey = $pair.PublicKey

    #[System.Convert]::ToBase64String($publicKey)
    $hexes = [System.BitConverter]::ToString($publicKey);
    $hexes.Replace("-", "")
}

Tags:

.Net