开发者

Check assembly's identity? Possibly by it's strong name?

开发者 https://www.devze.com 2023-03-23 10:18 出处:网络
In one of my apps I must distinguish my own included addins from others\' addins. They are signed with different keys each and so is the host app.

In one of my apps I must distinguish my own included addins from others' addins.

They are signed with different keys each and so is the host app.

Is there any way to distinguish my assembli开发者_如何学Pythones from others' assemblies? (Possibly with the help of the signing key)


You can check the loaded assembly public key token against the list that is stored in the container assembly.

http://blogs.msdn.com/b/miah/archive/2008/02/19/visual-studio-tip-get-public-key-token-for-a-stong-named-assembly.aspx

Or just simply store the full names of the assemblies like this:

var assembly = typeof (string).Assembly;

var myAssemblies = new HashSet<string>
{
 "mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
};

Assert.IsTrue(myAssemblies.Contains(assembly.FullName));

Also you can check egainst the tokens, using GetPublicKeyToken and BitConverter

var assembly = typeof(string).Assembly;

var token = BitConverter.ToString(assembly.GetName().GetPublicKeyToken()).Replace("-","").ToLowerInvariant();

var expectedToken = "b77a5c561934e089";

Assert.AreEqual(expectedToken, token);


If all your assemblies are signed you can use either GetPublicKey() or GetPublicKeyToken()

 Assembly a =...
 a.GetName().GetPublicKeyToken();

 Assembly a =...
 a.GetName().GetPublicKey();

and would be more convenient than keeping list of GUID and would work with future assemblies too.


You can accomplish this by checking the strong name signature. See Checking For A Valid Strong Name Signature for how to this. Note that the article refers to using P/invoke with StrongNameSignatureVerificationEx, but if you are using .NET 4.0 or above you should substitute ICLRStrongName::StrongNameSignatureVerificationEx.

See Public Keys and Public Key Tokens for what a public key token actually is. Given that it is only a hash of the public key, and therefore easily duplicated or extracted and then injected into an untrusted assembly, it isn't a secure mechanism for validating an assembly.


A little nice snippet:

// Assembly is a System.Reflection.Assembly
public string GetAssemblyGUID(Assembly assembly)
{
    object[] objects = assembly.GetCustomAttributes(typeof(System.Runtime.InteropServices.GuidAttribute), false);
    if (objects.Length > 0)
        return ((System.Runtime.InteropServices.GuidAttribute)objects[0]).Value;
    else
        return null;
}

This will retrieve the GUID of the specified assembly. You can set your assembly's GUID in Project Properties. This holds true for class libraries and PEs.

0

精彩评论

暂无评论...
验证码 换一张
取 消