The problem with your approach is that your app will need to contain both decryption key and decryption algorithm in order to decrypt and use the connection string.
It would be dangerous to assume that even a junior developer won't be able to just debug the code, step through the decryption and get the unencrypted string at the end.
Storing secrets (like connection strings, passwords, API keys) in config files is strongly discouraged as it's a very insecure practice. Instead you should be using a "secrets manager" service -- it's a secure online service that can store your passwords and lets you retrieve them when needed.
When using a secret management service, no secrets or decryption key or algorithm is stored in your source code. Retrieving a secret is as simple as this:
For Azure Key Vault:
var keyVaultUrl = "https://<your-key-vault-name>.vault.azure.net/";
var credential = new DefaultAzureCredential();
var client = new SecretClient(vaultUri: new Uri(keyVaultUrl), credential);
KeyVaultSecret secret = client.GetSecret("<your-secret-name>");
Console.WriteLine($"{secret.Name}: {secret.Value}");
For AWS Secrets Manager (skipped some error handling code):
var client = new AmazonSecretsManagerClient(accessKeyId, secretAccessKey,
RegionEndpoint.APSoutheast2);
var request = new GetSecretValueRequest {
SecretId = secretName
};
GetSecretValueResponse response = null;
response = client.GetSecretValueAsync(request).Result;
This approach has lots of advantages over the storage of secrets locally:
- you don't have to mess with storing different values in configs for Prod/Staging/Dev environments -- just read appropriately named secrets (such as '[Dev|Prod|Stag]DBPassword`
- only selected few people can have access to the very important secrets (such as, I dunno, say an authorisation code to transfer all $$$ from Deus account to E-Coin wallets around the world #revolution), and their access can be revoked at any time
- if anyone steals your source code (disgruntled employee, accidental leak) none of your passwords have been leaked
- changing a password is easy -- you just update it using the could management console and restart the app(s)
I have written a couple of articles, showing how to set up and read secrets with AWS and Azure, feel free to check it out if you need step-by-step directions and complete source code: