如何:使用完全签名来为动态程序集赋予强名称

可以使用部分签名或完全签名为动态程序集赋予强名称。 对于部分签名,必须在传递到 DefineDynamicAssembly 方法的 AssemblyName 中指定公钥。 公共语言运行时在可迁移可执行 (PE) 文件中为强名称签名 blob 分配空间,但并不实际对程序集签名。 可以使用 Windows 软件开发包 (SDK) 中提供的工具,在后续处理步骤中对所得到的程序集进行完全签名。

对于完全签名,必须提供公/私钥对。 这些实体通常存储在文件或磁盘中,或者存储在加密 API 加密服务提供程序 (CSP) 所拥有的密钥容器中。 安全性低的密钥通常由基于软件的 CSP 生成并导出到文件,以便项目开发期间可以将它们登记到源代码管理系统中。 安全性高的密钥通常由硬件生成,出于安全考虑,硬件通常禁止导出这些密钥。 这样的密钥对只能通过密钥容器间接访问。 使用 System.Reflection.StrongNameKeyPair 类指定强名称密钥对。

下面的示例阐释了使用完全签名来给动态程序集赋予强名称。

示例

Imports System
Imports System.IO
Imports System.Threading
Imports System.Reflection
Imports System.Reflection.Emit

Class SNKToAssembly
    Public Shared Sub Main()
        Dim fs As New FileStream("SomeKeyPair.snk", FileMode.Open)
        Dim kp As New StrongNameKeyPair(fs)
        fs.Close()
        Dim an As new AssemblyName()
        an.KeyPair = kp
        Dim appDomain As AppDomain = Thread.GetDomain()
        Dim ab As AssemblyBuilder = _
            appDomain.DefineDynamicAssembly(an, AssemblyBuilderAccess.RunAndSave)
    End Sub
End Class
' Construct a StrongNameKeyPair object. This object should obtain 
' the public key from the Company.keys file.
Dim k As Reflection.StrongNameKeyPair = _
    New Reflection.StrongNameKeyPair(fs)
using System;
using System.IO;
using System.Threading;
using System.Reflection;
using System.Reflection.Emit;

class SNKToAssembly
{
    public static void Main()
    {
        FileStream fs = new FileStream("SomeKeyPair.snk", FileMode.Open);
        StrongNameKeyPair kp = new StrongNameKeyPair(fs);
        fs.Close();
        AssemblyName an = new AssemblyName();
        an.KeyPair = kp;
        AppDomain appDomain = Thread.GetDomain();
        AssemblyBuilder ab = appDomain.DefineDynamicAssembly(an, AssemblyBuilderAccess.RunAndSave);
    }
}
// Construct a StrongNameKeyPair object. This object should obtain
// the public key from the Company.keys file.
StrongNameKeyPair k = new StrongNameKeyPair(fs);
using namespace System;
using namespace System::IO;
using namespace System::Threading;
using namespace System::Reflection;
using namespace System::Reflection::Emit;

ref class SNKToAssembly
{
public:
    static void Main()
    {
        FileStream^ fs = gcnew FileStream("SomeKeyPair.snk", FileMode::Open);
        StrongNameKeyPair^ kp = gcnew StrongNameKeyPair(fs);
        fs->Close();
        AssemblyName^ an = gcnew AssemblyName();
        an->KeyPair = kp;
        AppDomain^ appDomain = Thread::GetDomain();
        AssemblyBuilder^ ab = appDomain->DefineDynamicAssembly(an, AssemblyBuilderAccess::RunAndSave);
    }
};

int main()
{
   SNKToAssembly::Main();
}
// Construct a StrongNameKeyPair object. This object should obtain
// the public key from the Company.keys file.
StrongNameKeyPair^ k = gcnew StrongNameKeyPair(fs);

请参见

概念

具有强名称的程序集

其他资源

使用反射发出

创建和使用具有强名称的程序集