在实体框架中加密ConnectionString(第一个代码)

时间:2012-01-06 15:19:03

标签: c# visual-studio-2010 entity-framework

如何保护我的连接字符串?我想在C#中使用Entity framework 4.1(第一个代码),但对我来说很重要的是其他人看不到我的连接字符串。

3 个答案:

答案 0 :(得分:7)

答案 1 :(得分:4)

您可以从Context Class(DBContext或IdentityDbContext,如果使用ASPNET标识)中阻止对连接字符串的调用,并修改返回的连接字符串。在我的情况下,我选择只加密密码,而不是加密整个连接字符串。您可以使用相同的方法来加密整个连接字符串。

注意:用于加密和解密的函数(StringCipher.Decrypt)来自此线程 - > https://stackoverflow.com/a/1344255/1390025

您可以在此处阻止对连接字符串的调用

        public YourDB()
        : base(GetSqlConnection("DefaultConnection"))
    {}

在上面的场景中,我从app.config或web.config获取连接字符串。但是,根据您的请求,您可以加密整个连接字符串,如下例所示;

public YourDB()
        : base(StringCipher.Decrypt("your-encrypted-connection-string", "passphrase-used-to-encrypt"))
    {}

在只加密密码的情况下,下面的函数用纯文本替换加密密码并返回连接字符串;

        public static string GetSqlConnection(string connectionStringName = "DefaultConnection")
    {
        // optionally defaults to "DefaultConnection" if no connection string name is inputted
        string connectionString = ConfigurationManager.ConnectionStrings[connectionStringName].ConnectionString;
        string passPhrase = "passphrase-used-to-encrypt";
        // decrypt password
        string password = get_prase_after_word(connectionString, "password=", ";");
        connectionString = connectionString.Replace(password, StringCipher.Decrypt(password, passPhrase));
        return connectionString;
    }

用于从连接字符串

解析密码的函数
        public static string get_prase_after_word(string search_string_in, string word_before_in, string word_after_in)
    {
        int myStartPos = 0;
        string myWorkString = "";

        // get position where phrase "word_before_in" ends

        if (!string.IsNullOrEmpty(word_before_in))
        {
            myStartPos = search_string_in.ToLower().IndexOf(word_before_in) + word_before_in.Length;

            // extract remaining text
            myWorkString = search_string_in.Substring(myStartPos, search_string_in.Length - myStartPos).Trim();

            if (!string.IsNullOrEmpty(word_after_in))
            {
                // get position where phrase starts in the working string
                myWorkString = myWorkString.Substring(0, myWorkString.IndexOf(word_after_in)).Trim();

            }
        }
        else
        {
            myWorkString = string.Empty;
        }
        return myWorkString.Trim();
    }

答案 2 :(得分:3)

您可以使用与asp.net应用程序相同的工具。

在执行以下操作之前,请确保已备份!

  1. 在此处查找:'C:\ Windows \ Microsoft.NET \ Framework'作为您的版本或最新版本。
  2. 打开您版本的文件夹
  3. 搜索“ aspnet_regiis”
  4. 右键单击它并选择属性,然后复制位置的路径
  5. 现在将项目中的“ app.config”文件重命名为“ web.config”(您可以在Visual Studio中完成此操作)
  6. 打开命令提示符
  7. 键入'\ aspnet_regiis -pef“ connectionStrings”'
  8. 按Enter
  9. 它应该给您类似“成功加密”之类的信息
  10. 现在您可以将“ web.config”文件重命名为“ app.config”

现在,您可以查看app.config并查看连接字符串是否已加密。