Encrypt ConnectionString in entity structure (first code)

How can I protect my connection string? I want to use Entity framework 4.1 (first code) in C #, but for me it is important that other people cannot see my connection string.

+6
source share
2 answers

There is no difference between using EF or any other ORM, you can use the standard way to encrypt the connection string and decrypt it before calling EF Context initialization, it will be automatic.

+7
source

You can arrest calls in the connection string from the context class (DBContext or IdentityDbContext when using ASPNET Identity) and change the connection string. In my case, instead of encrypting the entire connection string, I decided to encrypt only the password. You can use the same approach to encrypt the entire connection string.

Note. The function (StringCipher.Decrypt) used for encryption and decryption came from this stream - > fooobar.com/questions/6756 / ...

Here you stop calling the connection string

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

In the above script, I get the connection string from app.config or web.config. However, according to your request, you can encrypt the entire connection string as an example below;

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

In a scenario where only the password is encrypted, the function below replaces the encrypted password with plain text and returns a connection string;

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

The function used to parse the password from the connection string

  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(); } 
+3
source

Source: https://habr.com/ru/post/905320/


All Articles