|
|

这类加密保护方式属于整体程序集的加密保护.这个方法首要解决的问题就是 native code 和 .Net Code如何交互.这里介绍三种实现方式.
1. C++/CLI 实现.
这个比较简单了,会C++/CLI一下子就能完成了.
Loader是由C++/CLI实现的.运行时通过解码程序集通过反射载入然后运行.
void InvokeAssemblyResource()
{
try
{
byte[] pBuf = GetDecryptedResource();
Assembly^ asm = Assembly::Load(pBuf);
asm->EntryPoint->Invoke(nullptr,nullptr);
}
catch(Exception^ ex)
{
MessageBox::Show(ex->Message);
}
}
2. 利用C#导出Com接口和native code交互.Loader由C#和native code两部分组成.
C#部分代码
public interface IInvokeAssembly
{
void LoadAndExecute(byte[] pBuf);
};
public class CInvokeAssembly : IInvokeAssembly
{
public CInvokeAssembly()
{
}
public void LoadAndExecute(byte[] pBuf)
{
try
{
Assembly asm = Assembly.Load(pBuf);
asm.EntryPoint.Invoke(null,null);
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
这里导出的 IInvokeAssembly 接口,将在native code中使用.
native code 部分
void InvokeAssemblyResource()
{
IInvokeAssemblyPtr pInvoker; //COM Pointer to the .Net Interface
if(FAILED(pInvoker.CreateInstance(CLSID_CInvokeAssembly)))
{
MessageBox(NULL,_T("Unable to Create Invoke Assembly Object !!"),_T("Error"),MB_OK|MB_ICONERROR);
return;
}
HRSRC hRC = FindResource(NULL,MAKEINTRESOURCE(IDR_EMBEDDED_ASSEMBLY),"RT_EMBEDDED_ASSEMBLY");
HGLOBAL hRes = LoadResource(NULL,hRC);
DWORD dwSize = SizeofResource(NULL,hRC);
SAFEARRAY* pSA = NULL;
if(NULL !=(pSA = SafeArrayCreateVector(VT_UI1, 0, dwSize)))
{
LPVOID pBuf = NULL;
if(FAILED(SafeArrayAccessData(pSA,&pBuf)))
MessageBox(NULL,_T("Unable to Access SafeArray Data"), _T("Error"),MB_OK|MB_ICONERROR);
else
{
LPVOID hAsm = LockResource(hRes);
memcpy(pBuf, hAsm, dwSize);
UnlockResource(hRes);
SafeArrayUnaccessData(pSA);
} Chinaz@com
pInvoker->LoadAndExecute(pSA); //Invoke the Reflection to load and Execute our Byte[]
}
else
MessageBox(NULL,_T("Unable to Allocate Memory"),_T("Memory Allocate Error"),MB_OK|MB_ICONERROR); Www_Chinaz_com
if(pSA) SafeArrayDestroy(pSA);
}
这里还有一个问题,loader是两部分.加密的程序集可以作为资源签入到native code loader中.但是C#部分怎么处理?一个比较隐蔽的方式是,在安装程序时将它安装到gac中. |
|