Can you pass a variable into the C# compiler code?

时间:2015-07-28 16:26:54

标签: c# compiler-construction codedom

Here's my current situation - I have an application that compiles C# code taken in as a string, using CodeDom. I have a SecureString that stores a password and I was wondering if there would be any way to pass that SecureString variable into the compiled code as a SecureString?

Here is some example code:

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);

I can't find a way to do this and I imagine that this isn't actually possible and instead I should possibly just store the password in an encrypted file and read it from that?

2 个答案:

答案 0 :(得分:4)

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

  

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

SecureString只会保护你的内存中密码1)加密内存密码,因此没有其他应用可以嗅探它,2)一旦你完成它就把它从内存中删除

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

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

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

答案 1 :(得分:1)

Well all you need is to figure a way to change SecureString to System.String.

Already answered here : 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));