您的位置:首页 > 其它

Just By Hand: 得到Assembly的Public Key Token

2007-06-21 21:19 465 查看
强名签名了的程序集都有一个Public Key Token, 每个引用了它的程序集的metadata中都会记录下这个Public Key Token.
用ILdasm反编译一个强名签名的程序集得到的IL文件里可以看到一个160字节长的Public Key, 它跟Public Key Token有什么关系呢? 其实很简单... 以下的一小段程序便可以计算和输出Public Key Token:

Code

// using the program:

// ptg <AssemblyPath>

using System;

using System.Collections.Generic;

using System.Text;

using System.IO;

using System.Security.Cryptography;

using System.Diagnostics;

namespace PublicKeyTokenGetter

{

class Program

{

static void Main(string[] args)

{

string asmFilePath = args[0];

if (File.Exists(asmFilePath))

{

string tempFileName = Guid.NewGuid().ToString();

// start a sn.exe process to get the public key

Process sn = new Process();

sn.StartInfo.FileName = "sn.exe";

sn.StartInfo.Arguments = "-e " + asmFilePath + " " + tempFileName;

sn.StartInfo.RedirectStandardOutput = true;

sn.StartInfo.UseShellExecute = false;

sn.Start();

sn.WaitForExit();

using (FileStream publicKeyFile = File.Open(tempFileName, FileMode.Open))

{

using (BinaryReader reader = new BinaryReader(publicKeyFile))

{

// get the public key bytes

// and compute the 20 bytes long hash using the SHA1 algorithm

SHA1Managed sha = new SHA1Managed();

byte[] hash = sha.ComputeHash(reader.ReadBytes(160));

byte[] pkt = new byte[8];

// copy the last 8 bytes and reverse it

Array.Copy(hash, hash.Length - 8, pkt, 0, 8);

Array.Reverse(pkt);

// show the result in hex

foreach (byte b in pkt)

{

Console.Write(Convert.ToString(b, 16).PadLeft(2, '0'));

}

Console.WriteLine();

}

}

File.Delete(tempFileName);

}

}

}

}

如果你仅仅是想看到Public Key Token, 直接用sn -T <Assembly> 吧.

var hideSidebar = true;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: