我想加密我的WPF代码,所以当我用'ILSpy'或'IL Disassembler'等软件打开EXE文件时,我看不到代码。
我不想使用任何现有软件,而是自己编写加密。
谁能给我一个简单的代码呢? (我是否需要使用'System.Security.Cryptography'命名空间?)
...谢谢
答案 0 :(得分:1)
你无法真正加密代码(有几次尝试 - 其中一些像臭名昭着的Themida实际上工作)但你可以混淆它。有许多预制工具,如Dotfuscator,专为此目的而设计。
但是,如果您想编写自己的混淆器,则必须进入低级别&#34 ;,这在.NET上下文中为CIL。你可以重命名所有的变量和类,将常见的方法调用包装成一些模糊的代码等,但这将是一项艰苦的工作,最终,如果它对某人很重要,它将被反混淆。
答案 1 :(得分:1)
您正在讨论的问题有没有 简单解决方案。这就是为什么有几个,有时相当昂贵的商业工具。它们被称为obfuscators。既然你显然不知道混淆是如何起作用的,甚至可能不知道CLR是如何工作的(你也不会问你的问题不是这样),那么它很可能是一个自杀的任务。自定义混淆器。因此,我的建议是购买符合您要求的工具许可证。
答案 2 :(得分:0)
我假设你想在项目中存储加密的XAML,然后在运行中解密和编译它。首先编写一个命令行实用程序来加密你的文件,如下所示:
private static byte[] Key = { 123, 217, 19, 11, 24, 26, 85, 45, 114, 184, 27, 162, 37, 112, 222, 209, 241, 24, 175, 144, 173, 53, 196, 29, 24, 26, 17, 218, 131, 236, 53, 209 };
private static byte[] Vector = { 146, 64, 191, 111, 23, 3, 113, 119, 231, 121, 252, 112, 79, 32, 114, 156 };
static void Main(string[] args)
{
var xaml = File.ReadAllBytes(args[0]);
using (var outputFile = new FileStream(args[1], FileMode.Create))
{
RijndaelManaged rm = new RijndaelManaged();
var transform = rm.CreateEncryptor(Key, Vector);
CryptoStream cs = new CryptoStream(outputFile, transform, CryptoStreamMode.Write);
cs.Write(xaml, 0, xaml.Length);
cs.FlushFinalBlock();
}
}
现在回到你的主要主应用程序中,将你的XAML Build Actions设置为“None”,并在你的项目设置中添加pre-build命令来加密你的每个文件(我假装你只是将它们保存为加密文件在与exe相同的文件夹中,实际上你已经将它们作为嵌入式资源或其他东西)。然后它只是加载它们,解密它们并编译它们的问题:
private void LoadEncryptedXaml(string filename)
{
RijndaelManaged rm = new RijndaelManaged();
var transform = rm.CreateDecryptor(Key, Vector);
var bytes = File.ReadAllBytes(filename);
using (var stream = new MemoryStream(bytes))
using (var cs = new CryptoStream(stream, transform, CryptoStreamMode.Read))
{
var decrypted = ReadFully(cs);
using (var memstream = new MemoryStream(decrypted))
{
var xaml_object = XamlReader.Load(memstream);
// do something with it here, e.g. if you know it's a resource dictionary then merge it with the other app resources
Application.Current.Resources.MergedDictionaries.Add(xaml_object as ResourceDictionary);
}
}
}
ReadFully函数只读到流的末尾,你可以get the source code here。