本文介绍了确保组装通过指定的组件被称为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有内置的功能,以确定是否一个程序集是从一个特定的程序集叫什么名字?

Is there any built in functionality to determine if an assembly is being called from a particular assembly?

我有组装 A 它引用组件 B 。大会 A 公开PowerShell命令输出 B 中发现的类型。某些方法和属性与类型的曝光通过 B 感兴趣的类型组装 A 但不感兴趣消费者的PowerShell或任何人试图加载类型 B 直接调用方法在其中。

I have assembly A which references assembly B. Assembly A exposes PowerShell cmdlets and outputs types that are found within B. Certain methods and properties with in types of exposed by B are of interest to types in assembly A but not of interest to consumers of PowerShell or anyone attempting to load types in B directly and call methods within it.

我看着 InternalsVisibleToAttribute 但它需要因使用接口的广泛返工。我制定了后来被模糊的共享密钥系统,但似乎笨重。

I have looked into InternalsVisibleToAttribute but it would require extensive rework because of the use of interfaces. I was devising a shared key system that would later be obfuscated but that seemed clunky.

有没有什么办法,以确保 B 只能由 A

Is there any way to ensure B is called only by A?

推荐答案

您会使用强名称密钥的程序集来做到这一点。

You'd use a Strong Name key on your assemblies to do this.

首先确保调用程序集(程序集A)是强名称签名(这可以在项目属性进行签名选项卡下的屏幕)

First make sure the calling assembly (assembly A) is strong name signed (this can be done in the project properties screen under the Signing tab)

下面code将检索调用程序集的强名称密钥。

The following code will retrieve the strong name key from the calling assembly.

internal static StrongName GetStrongName(Evidence evidence)
{
    foreach (var e in evidence)
    {
        if (e is StrongName)
        {
            return (StrongName)e;
        }
    }
    throw new ArgumentException();
}

的最简单的方法是将签署两个组件具有相同的强名称,然后验证Assembly.GetCallingAssembly()。证据和Assembly.GetExecutingAssembly()。证据由相同强名称签署

The easiest way would be to sign both assemblies with the same StrongName, then verify that Assembly.GetCallingAssembly().Evidence and Assembly.GetExecutingAssembly().Evidence are signed by the same StrongName.

var callerKey = GetStrongName(Assembly.GetCallingAssembly().Evidence).PublicKey;
var execKey = GetStrongName(Assembly.GetExecutingAssembly().Evidence).PublicKey;

if (callerKey != execKey)
{
    throw new UnauthorizedAccessException("The strong name of the calling assembly is invalid.");
}

这可能是不切实际的实施在现有的codeBase的,但看看的,则应该能够实现可以连接到需要被检查的有效呼叫者类的属性。

This might be impractical to implement over an existing codebase, but take a look at LinFu AOP, you should be able to implement an attribute that can be attached to classes that need to be checked for a valid caller.

这篇关于确保组装通过指定的组件被称为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 15:31