【问题标题】:Can you pass a variable into the C# compiler code?您可以将变量传递给 C# 编译器代码吗?
【发布时间】:2015-10-19 08:22:45
【问题描述】:

这是我目前的情况 - 我有一个应用程序,它使用 CodeDom 编译作为字符串接收的 C# 代码。我有一个存储密码的 SecureString,我想知道是否有任何方法可以将该 SecureString 变量作为 SecureString 传递到编译后的代码中?

下面是一些示例代码:

SecureString securePassword = getSecurePass();

string codeString =
        @"using System;
        using System.Security;

        namespace SomeProgram
        {
            class MyClass
            {
                static void Main(string[] args)
                {
                    SecureString securePass = new SecureString();
                    // somehow set this equal to the securePassword variable
                }
            }
        }";


// Compiler Code
CodeDomProvider codeProvider = CodeDomProvider.CreateProvider("CSharp");
string outFile = "output.exe"; 

System.CodeDom.Compiler.CompilerParameters parameters = new CompilerParameters();
parameters.GenerateExecutable = true;
parameters.OutputAssembly = outFile;
CompilerResults results = codeProvider.CompileAssemblyFromSource(parameters, codeString);

我找不到这样做的方法,我想这实际上是不可能的,而是我应该将密码存储在加密文件中并从中读取?

【问题讨论】:

  • 您正在编写一个 exe,因此您无论如何都希望将密码以序列化形式嵌入其中。这不像是在为正在运行的程序提供价值。
  • (adding a resource 可以方便地完成包含加密 blob 的程序集)。
  • @GSerg 这是一个天才的想法,是内置在实际 EXE 中的资源还是单独存储(在单独的文件中),因为如果它们单独存储,那么我不妨加密字符串并输出到txt文件?
  • Yes they do,因为他们是EmbeddedResources。还有LinkedResources。

标签: c# compiler-construction codedom


【解决方案1】:

我认为您对这些概念感到困惑。您正在尝试将密码编译为 exe 文件,并且您认为 SecureString 将确保您的密码安全。这不是SecureString 的用途。阅读the documentation:

(SecureString) 表示应该保密的文本,例如通过删除 不再需要时从计算机内存中提取。

SecureString 只会通过以下方式保护您的内存密码:1)在它在内存中时对其进行加密,因此其他应用程序无法嗅探它,以及 2)在您完成后将其从内存中删除。

如果你把你的密码编译成一个exe文件,即使它是加密的,黑客也可以很容易地从那里得到它。事实上,从 exe 中获取它比从内存中获取要容易得多。加密只会让它变得更难一些,但熟练的黑客在找到密钥后仍然可以解密它。 Gseg 给出的将其编译为嵌入式资源的建议以及您在文本文件中对其进行加密的建议都会有同样的问题。

这一切都归结为加密密钥,它存储在哪里?如果你将它存储在 exe 文件中(因为你需要你的应用程序能够解密它),那么黑客就会能够找到密钥并使用它来解密您的密码。您需要以黑客无法访问的方式将其存储在 exe 之外。因此,您需要考虑的真正问题是:将加密密钥存储在哪里,以便应用可以读取,而黑客却不能?。

现在,当您的应用检索密钥时,您可以将密码解密为 SecureString 变量,以便在它在内存中时对其进行保护并在之后将其删除。

【讨论】:

    【解决方案2】:

    那么,您只需想办法将SecureString 更改为System.String。

    已经在这里回答了:How to convert SecureString to System.String?

    string codeString =
        String.Format(@"using System;
        using System.Security;
    
        namespace SomeProgram
        {
            class MyClass
            {
                static void Main(string[] args)
                {
                    SecureString securePass = new SecureString();
                    {0} // use it the way u like
                }
            }
        }", SecureStringToString(securePassword));
    

    【讨论】:

    • 我相信 OP 希望在此过程中保持字符串的安全。
    • 我已经有一种方法可以做到这一点,但是硬编码密码不是一个非常糟糕的主意吗? (是的,就像 GSerg 所说,将密码保存在 SecureString 中是理想的)
    • @PhilJones-这是不可能的,您需要在内存中安全的东西,然后需要以原始格式再次安全。
    猜你喜欢
    • 2020-02-02
    • 2014-01-16
    • 1970-01-01
    • 2018-01-09
    • 1970-01-01
    • 2019-02-28
    • 2023-03-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多