Just By Hand: 得到Assembly的Public Key Token

强名签名了的程序集都有一个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> 吧.

原文地址:https://www.cnblogs.com/Dah/p/792302.html