Connection String Encryption , whats the idea? - c#

If I am encrypting the connection string section, anyone who has the web.config can reDecrypt the information.
There is no password key which is known only to me or something similar....
What's the idea here?? Anyone who will have that web.config with VS, will be able to decipher the info...
I dont get the idea...

You wrongly assume that anyone can decrypt the web.config. Once the config file section is encrypted, it can only be decrypted on the same machine (or the machine that has got the same key - this is for web farming).
Usually, it is fairly easy to download the actual web.config remotely (through vulnerabilities). But the malicious user will not have your key and will not be able to decrypt the file (or sections with sensitive data).
The point here is you have got to trust your site hoster, that is the sensitive key will not be distributed.

You can specify the encryption provider, but the default is the RSA provider. There is a key used, but it is 'secret'. So someone would need a privileges to run applications on your server, or unrestricted access to the file system in order to unencrypt your web.config.
This (especially step 2) talks about it:
http://msdn2.microsoft.com/en-us/library/ms998283.aspx

I don't know whether aspnet_regiis.exe tool uses keys to encrypt or decrypt web.config. But
If it stores in the web.config then It would be decrypted by anyone who has aspnet_regiis utlility installed but If it is stored in machine.config or in .Net Framework folder of the computer than It would not be decrypted by anyone.

Related

How can i encrypt a stored password that any user could decrypt on use of an application?

I have working code that will encrypt and decrypt a string provided to methods and this all works fine for when im storing a users entered password for convenience later.
However what I am trying to do is provide a password (encrypted) in the applications config file that allows users to pull data from an SQL server on the same domain.
Because I've used ProtectedData.Protect with DataProtectionScope.CurrentUser it has been encrypted using me as a key meaning users cannot decrypt this key, and DataProtectionScope.LocalMachine is also not applicable.
private static byte[] Entropy = { // Some arbitrary numbers };
public static string Encrypt(string _toEncrypt)
{
byte[] originalText = Encoding.Unicode.GetBytes(_toEncrypt);
byte[] EncryptedText = ProtectedData.Protect(originalText, Entropy, DataProtectionScope.CurrentUser);
return Convert.ToBase64String(EncryptedText);
}
public static string Decrypt(string _toDecrypt)
{
byte[] EncryptedText = Convert.FromBase64String(_toDecrypt);
byte[] OriginalText = ProtectedData.Unprotect(EncryptedText, Entropy, DataProtectionScope.CurrentUser);
return Encoding.Unicode.GetString(OriginalText);
}
Is there another way of doing this that allows for a password to be decrypted when required and be provided in its encrypted format for security reasons?
Since you're using app.config for your configuration file, you can actually use the aspnet_regiis utility to encrypt sections of the file.
It's been a while since I've had to do this, but there are some resources on the internet if you do some searching (for example). But, if I recall correctly the steps are basically:
Temporarily rename your app.config to web.config because
aspnet_regiis will only work on web.config.
Open a Developer Command Prompt (might need to do it as an administrator).
Run aspnet_regiis -pef <the section you're encrypting> <path to your web.config>. The path should just be the folder where the configuration file can be found, don't include web.config.
Rename your configuration file back to app.config.
This will need to be run on the server or machine hosting your application. If your application is not running from a single server things become more complicated as you will have to export the key, and import it to every computer running the application. This article contains the steps:
Create a machine-level RSA Key Container (1 time step)
Exporting the Custom RSA Encryption Key (1 time step)
Importing the Certificate (1 time step - per machine)
Adding Permissions to the Certificate (1 time step - per machine)
Encrypting the Configuration Section
Decrypting the Configuration Section
You don't actually need to do any sort of special decryption in your application. The configuration system will handle that for you automatically.

Encrypt SQL connection string

I know how to use System.Configuration.SectionInformation.ProtectSection to encrypt and decrypt connection string in app.config (VS 2010, C#, .Net 3.5), however I suppose that any one who know this method can take the encrypted string and decrypt it, right?
If not, please tell me why. If yes, is there any work around? I searched but could not find any help.
When a string is encrypted it uses a certificate installed on the machine to perform the encryption so you would need the string and the machine key to decrypt it.
The full instructions on encrypting sections of the configuration are on MSDN.
To decrypt connection string info you can use below method:
Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
ConfigurationSection section = config.GetSection("connectionStrings");
if (section.SectionInformation.IsProtected)
{
section.SectionInformation.UnprotectSection();
config.Save();
}
Read the full information from this article.

Encrypt connection string in app.config

I am having trouble encrypting a connection string in app.config. I have code that will protect the connectionStrings section of app.config, but the password is still displayed in plain text.
I need to encrypt the connection string in so it is not in plain text when deployed. I see similiar questions on SO for web.config, but not app.config.
You can easily apply the same solution as the web.config you just have to rename your app.config to web.config, encrypt with the aspnet_regiis tool and then rename it back to app.config.
Rename app.config to web.config
Open command prompt and type:
%windir%\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis -pef "connectionStrings" c:\<folder containing your web.config>
(stop at folder level and don't put the trailing "")
rename web.config back to app.config
You can open it in notepad to see the encrypted file. In visual studio you will see it's decrypted. You can use your connection string the same way as if it was not encrypted. (Note that it can only be decrypted on the same machine it's encrypted on.)
Have a look at This Article it has some very useful examples. You're basically looking for System.Configuration.SectionInformation.ProtectSection to help you out here.
Also have a peek at Implementing Protected Configuration
• Rename App.config file to web.config<br>
• Run Command prompt as admin:
For encrypt:
C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis.exe -pef "connectionStrings" your project location within quotes and -prov "DataProtectionConfigurationProvider"
Ex:
C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis.exe -pef "connectionStrings" "D:\location\location1\location" -prov "DataProtectionConfigurationProvider"
For Decrypt:
C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis.exe -pdf "connectionStrings" your project location within quotes.
Ex:
C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis.exe -pdf "connectionStrings" "D:\location1\location"
For error:
Add this in Configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0"
Like this:
• Finally, Rename web.config to App.Config
Additionally, If there is anyone who wants to encrypt and decrypt connection strings in web farms here are the steps:
Create an RSA key:
aspnet_regiis -pc "MyKeys" -exp
Grant access for application pool identity to this key:
aspnet_regiis -pa "MyKeys" "IIS AppPool\ApplicationPoolName" -full
Add RSA provider to the web.config:
<configuration>
<configProtectedData>
<providers>
<add name="MyProvider"
type="System.Configuration.RsaProtectedConfigurationProvider, System.Configuration, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL"
keyContainerName="MyKeys"
useMachineContainer="true" />
</providers>
</configProtectedData>
</configuration>
Encrypt web.config by using the RSA provider:
aspnet_regiis -pe "connectionStrings" -app "/MyApplication" -prov "MyProvider"
Note: You can use the alternative syntax like the one we did for a single server scenario. Example:
ASPNET_REGIIS -pef "connectionStrings" "D:\inetpub\wwwroot\applicationFolder" -prov "MyProvider"
Open the web.config and confirm that the connection string is encrypted
Test the site and confirm that it is working
Try decrypting the web.config. Create a test.aspx file with the code below inside. Browse it to see the decrypted file
Export the RSA key to the C drive:
aspnet_regiis -px "MyKeys" "c:\keys.xml" -pri
Copy this file to the second server in the web farm
Import it in that server:
aspnet_regiis -pi "MyKeys" "c:\keys.xml"
Grant access to this key (same as Step 2)
Test the application in the second server
Source: How to encrypt and decrypt connection strings
Define the location of config File
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
if you want to encrypt connectionStrings
config.ConnectionStrings.SectionInformation.ProtectSection(Nothing);
you must be aware of app config portions
so if you want to encrypt AppSettings
config.AppSettings.SectionInformation.ProtectSection(Nothing);
A way to automate this:
ProjectSettings > Compile > BuildEvents > Edit Post-build
Paste the code below:
SET ApplicationName=YourAppWithoutExtention
echo.
echo POST BUILD ACTIONS
echo ====================
if EXIST web.config (
echo Deleting web.config
DEL web.config
)
echo Renaming %ApplicationName%.exe.config to web.config
REN %ApplicationName%.exe.config web.config
echo Running aspnet_regis against webconfig
SET rpath=%windir%\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis -pef "connectionStrings" "$(TargetDir)
SET rpath=%rpath:~0,-1%"
echo Path: %rpath%
%rpath%
echo Renaming web.config to %ApplicationName%.exe.config
REN web.config %ApplicationName%.exe.config
echo Done.
Replacing "YourAppWithoutExtention" with your app name.
Then every time it builds, it will automatically encrypt your app.config.
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.

problem with encryption & decryption connectionStrings

I used the following command to encrypt my connection string but an error ocurred
"The connection name
'DatabaseConnectionString1' was not
found in the applications
configuration or the connection string
is empty"
How can I encrypt it while keeping the application working?
The command used was
aspnet_regiis -pef "connectionStrings" "C:\Users\ANAS\Documents\Visual Studio 2008\WebSites\WebSite7"
What if I move the encrypted application to another computer? Will it work?
How can I encrypt it while keeping the
application working?
You can't. If you change your web.config your application is initialized.
What if I move the encrypted
application to another computer? Will
it work?
It will not work. You can only encrypt config sections on the same machine you decrypted it before. That's the reason why this is secure: You can't take a config file away and decrypt it on another machine.

Encrypting class library app.config file

Please share your thoughts if there is any way to encrypt app.config section with out changing code? I know that we can use aspnet_regiis.exe to encrypt the web.config file.
I came across some blogs to rename app.config to web.config and run aspnet_regiis -pef command. I am able to create an encrypted version of app.config file but application failed to read the keys from encrypted app.config. so this approach didnt work for me.
Many thanks
What about this way? Are you able to do that?
Encrypt your connection strings and stored procedure names in app.config. (Use like tripleDes)
Store your encrypted values in app.config.(like: ConnectionString="asdasfasfasfdsdgsdfa")
After reading value from app.config, decrypt it with your service and use.
by the way I found my old answer about ready to use Crypto Class :)
.NET: what are my options for decrypting a password in my project .setting file

Categories