C#DLL加密保护

//Program.cs using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1Text
{
class Program
{
static void Main(string[] args)
{
MyDLL Dll= new MyDLL();
Model.IO.IClass1 obj = Dll.Creat < Model.IO.IClass1>("TestModel.dll", "TestModel", "TestModel.Class1", null);
string str = Test(obj);
Console.Write(str);
Console.ReadLine();

}
public static string Test(Model.IO.IClass1 ClassA)
{
return ClassA.HelloWord();

}

}

}
//TestModel.dll --嵌入的资源 using System;
using System.Collections.Generic;
using System.Text;
namespace TestModel
{
public class Class1 : Model.IO.IClass1
{
public string HelloWord()
{
return "Hellp Word ! /r/n";

}

}

}
//Model.IO 接口 using System;
namespace Model.IO
{
public interface IClass1
{
string HelloWord();

}

}
//MyDLL 类 using System.IO;
// 对文件的读写需要用到此命名空间 using System.Reflection;
// 使用 Assembly 类需用此命名空间 using System.Reflection.Emit;
// 使用 ILGenerator 需用此命名空间 public partial class MyDLL
{
//声明一静态变量MyAssembly: // 记录要导入的程序集 static Assembly MyAssembly;
/// /// DLL字节处理 /// /// /// public delegate byte[] LoadDLLHandler(byte[] Assembly);
/// /// DLL字节处理 /// public event LoadDLLHandler LoadDLLEventArgs;
//添加LoadDll方法: private byte[] LoadDll(string lpFileName)
{
Assembly NowAssembly = Assembly.GetEntryAssembly();
Stream fs = null;
try
{
// 尝试读取资源中的 DLL fs = NowAssembly.GetManifestResourceStream(NowAssembly.GetName().Name + "." + lpFileName);

}
finally
{
// 如果资源没有所需的 DLL ,就查看硬盘上有没有,有的话就读取 if (fs == null && !File.Exists(lpFileName)) throw (new Exception(" 找不到文件 :" + lpFileName));
else if (fs == null && File.Exists(lpFileName))
{
FileStream Fs = new FileStream(lpFileName, FileMode.Open);
fs = (Stream)Fs;

}

}
byte[] buffer = new byte[(int)fs.Length];
fs.Read(buffer, 0, buffer.Length);
fs.Close();
if (LoadDLLEventArgs != null)
{
return LoadDLLEventArgs(buffer);

}
return buffer;
// 以 byte[] 返回读到的 DLL
}
/// /// //添加UnLoadDll方法来卸载DLL: /// public void UnLoadDll()
{
// 使 MyAssembly 指空 MyAssembly = null;

}
/// /// 从资源创建实例 /// /// 资源名称 /// 命名空间 /// 完整类名 /// 参数 /// 创建的实例 public T Creat(string lpFileName, string Namespace, string FullClassName, object[] args)
{
object objType = null;
try
{
// 判断 MyAssembly 是否为空或 MyAssembly 的命名空间不等于要调用方法的命名空间,如果条件为真,就用 Assembly.Load 加载所需 DLL 作为程序集 if (MyAssembly == null || MyAssembly.GetName().Name != Namespace) MyAssembly = Assembly.Load(LoadDll(lpFileName));
objType = MyAssembly.CreateInstance(FullClassName, true, BindingFlags.Default, null, args, System.Globalization.CultureInfo.CurrentCulture, null);
//反射创建
}
catch (System.NullReferenceException e)
{
throw e;

}
return (T)objType;

}

}

原文地址:https://www.cnblogs.com/zhuhongbao/p/1709445.html