After hours of researching solutions related to the question.
I found a reasonable solution:
The problem with your approach is that your app will need to contain
both a decryption key and a 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;
You can also search for an alternative secret manager and implementation like Google Cloud Secret Manager or others.
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)
How to use AWS Secrets Manager to store & read passwords in .Net Core apps
How to securely store and retrieve sensitive info in .NET Core apps with Azure Key Vault
Credits and thanks to @smartial-arts Reference; the second answer.