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.
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.
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;
}
}
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
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("-", "")
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With