Welcome

首页 / 软件开发 / .NET编程技术 / 从编译DotNetOpenAuth中学到的程序集强签名知识

从编译DotNetOpenAuth中学到的程序集强签名知识2015-12-23 cnblogs dudu1. 背景

最近在研究DotNetOpenAuth——OAuth的一个.NET开源实现,官方网站:http://dotnetopenauth.net/ 。

从GitHub签出DotNetOpenAuth的源代码发现最新版本已到5.1,而NuGet中发布的版本只是4.3。新版中使用到了.NET 4.5的异步特性(async, await),于是决定直接用最新版。

用最新版,就要自己进行编译。用Visual Studio 2012打开解决方案文件进行编译,一次编译成功,但编译出的DotNetOpenAuth相关dll有20个,这么多dll引用起来不方便。发现DotNetOpenAuth提供了msbuild的配置文件,可以在编译时自动将dll文件进行合并(使用了ILMerge)。于是改用msbuild命令进行编译。

2. 用msbuild进行第一次编译

2.1. 使用的是DotNetOpenAuth的toolsdrop.proj编译配置文件,为了加快编译速度,注释了下面的内容:

<!--<ItemGroup><ProjectsToBuild Include="$(ProjectRoot)samplessamples.proj"><Properties>TargetFrameworkVersion=v4.5</Properties></ProjectsToBuild>--><!-- Sandcastle doesn"t seem to be able to handle .NET 4.0 dependencies right now. --><!--<ProjectsToBuild Include="$(ProjectRoot)docdoc.proj"><Properties>TargetFrameworkVersion=v4.5</Properties></ProjectsToBuild></ItemGroup>-->
2.2. 运行VS2012的命令行:Developer Command Prompt for VS2012

2.3. 运行msbuild命令:

msbuild tools/drop.proj
2.4. 编译成功

2.5. 在dropsv4.5Debug文件夹中得到合并后的DotNetOpenAuth.dll。

3. 测试已编译的DotNetOpenAuth

3.1. 在另外的项目中引用已编译出的DotNetOpenAuth.dll

3.2. 编译后运行项目,出现错误提示:

Could not load file or assembly "DotNetOpenAuth" or one of its dependencies. Strong name signature could not be verified. The assembly may have been tampered with, or it was delay signed but not fully signed with the correct private key. (Exception from HRESULT: 0x80131045)

从这个错误信息中可以解读出:需要对DotNetOpenAuth进行强签名。

4. 使用强签名进行msbuild编译

4.1.  生成公钥

生成公钥需要借助sn.exe(sn是Strong Name的缩写),它是Visual Studio/Windows SDK中自带的一个工具。运行sn.exe命令需要进入Developer Command Prompt for VS2012。

具体操作步骤如下:

4.1.1. 生成密钥对(公钥/私钥)并保存至.pfx文件中

sn -k mykeyfile.pfx

4.1.2. 将密钥对从文件安装至密钥容器中

sn -i mykeyfile.pfx mykeycontainer

4.1.3. 从存放密钥对的.pfx文件中导出公钥至.pub文件

sn -p mykeyfile.pfx mykeyfile.pub

4.1.4. 显示.pub文件中存放的公钥

sn -q -t mykeyfile.pub

4.2. 使用生成的公钥进行msbuild编译

msbuild /p:KeyPairContainer=mykeycontainer,PublicKeyFile="<full path>mykeyfile.pub" tools/drop.proj