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 = "";
source share