Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Obtain .NET PublicKeyToken from snk file?

Tags:

.net

How to obtain the PublicKeyToken from an snk file? Using command line tools. I thought about using sn.exe, however, couldn't find a suiting parameter.

like image 714
D.R. Avatar asked Apr 21 '15 09:04

D.R.


People also ask

What is an SNK file?

Software key file created by Strong Name Tool (Sn.exe), a cryptographic program included with Microsoft's . NET framework; contains a public key and private key pair; used to digitally sign and authenticate an application.


3 Answers

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;
    }
}
like image 107
xanatos Avatar answered Oct 23 '22 00:10

xanatos


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

like image 32
Jehof Avatar answered Oct 23 '22 00:10

Jehof


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("-", "")
}
like image 25
Ivan G. Avatar answered Oct 23 '22 00:10

Ivan G.