如何防止未经授权的代码访问.NET 2.0中的程序集? [英] How can I prevent unauthorized code from accessing my assembly in .NET 2.0?

查看:119
本文介绍了如何防止未经授权的代码访问.NET 2.0中的程序集?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在.NET 1.x中,您可以使用程序集上的> StrongNameIdentityPermissionAttribute ,以确保只有您签名的代码才能访问程序集。根据MSDN文档,

In .NET 1.x, you could use the StrongNameIdentityPermissionAttribute on your assembly to ensure that only code signed by you could access your assembly. According to the MSDN documentation,


在.NET Framework 2.0版和更高版本中,如果身份要求
无效,则要求调用程序集具有完全信任。

In the .NET Framework version 2.0 and later, demands for identity permissions are ineffective if the calling assembly has full trust.

这意味着任何完全信任的应用程序都可以绕过我的安全要求。

This means that any application with full trust can just bypass my security demands.

如何防止未经授权的代码访问.NET 2.0中的程序集?

How can I prevent unauthorized code from accessing my assembly in .NET 2.0?

推荐答案

按照埃里克(Eric)的建议,我自己检查了钥匙就解决了。在我要保护的代码中,添加以下调用

As per Eric's suggestion, I solved it by checking the key myself. In the code I want to protect, I add the following call,

EnsureAssemblyIsSignedByMyCompany( Assembly.GetCallingAssembly() );

然后该方法的实现为

  /// <summary>
  /// Ensures that the given assembly is signed by My Company or Microsoft.
  /// </summary>
  /// <param name="assembly"></param>
  private static void EnsureAssemblyIsSignedByMyCompany( Assembly assembly )
  {
     if ( assembly == null )
        throw new ArgumentNullException( "assembly" );

     byte[] pubkey = assembly.GetName().GetPublicKeyToken();
     if ( pubkey.Length == 0 )
        throw new ArgumentException( "No public key token in assembly." );

     StringBuilder builder = new StringBuilder();
     foreach ( byte b in pubkey )
     {
        builder.AppendFormat( "{0:x2}", b );
     }
     string pkString = builder.ToString();
     if ( pkString != "b77a5c561934e089" /* Microsoft */ &&
          pkString != "abababababababab" /* Ivara */ )
     {
        throw new ArgumentException( "Assembly is not signed by My Company or Microsoft. You do not have permission to call this code." );
     }
  }

**更改名称和密钥以保护无辜者。对真实姓名或公司的任何相似都只是一个巧合。*

** Names and keys changed to protect the innocent. Any likeness to real names or companies is merely a coincidence.*

这篇关于如何防止未经授权的代码访问.NET 2.0中的程序集?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆