I'm trying to decrypt a Web.config section that was encrypted with RSA from an external Powershell script. The section goes:
<connectionStrings configProtectionProvider="RsaProtectedConfigurationProvider">
<EncryptedData Type="http://www.w3.org/2001/04/xmlenc#Element" xmlns="http://www.w3.org/2001/04/xmlenc#">
<EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#tripledes-cbc" />
<KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">
<EncryptedKey xmlns="http://www.w3.org/2001/04/xmlenc#">
<EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-1_5" />
<KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">
<KeyName>Rsa Key</KeyName>
</KeyInfo>
<CipherData>
<CipherValue>.......</CipherValue>
</CipherData>
</EncryptedKey>
</KeyInfo>
<CipherData>
<CipherValue>.......</CipherValue>
</CipherData>
</EncryptedData>
</connectionStrings>
The code goes:
[xml]$x = Get-Content "$Path\Web.config"
$Prov = New-Object System.Configuration.RsaProtectedConfigurationProvider
$Prov.Decrypt($x.configuration.connectionStrings.EncryptedData)
It's executed via remote Powershell on the server where the config is. The account is an admin, so local machine keys should be available. And I'm getting an error:
Value cannot be null. Parameter name: keyName
An identical, modulo provider name, fragment works for DPAPI encrypted sections. The key name is right there in the section. What am I missing here?
Update: when the Web code does it, it calls Initialize() on the provider first. I've mimicked the parameters on that Initialize call. They come from machine. config.
$nv = New-Object System.Collections.Specialized.NameValueCollection
$nv.Add("description", "Uses RsaCryptoServiceProvider to encrypt and decrypt")
$nv.Add("keyContainerName", "NetFrameworkConfigurationKey")
$nv.Add("cspProviderName", "")
$nv.Add("useMachineContainer", "true")
$nv.Add("useOAEP", "false")
$Prov.Initialize("RsaProtectedConfigurationProvider", $nv)
Now I'm getting a different error: "Bad data".
Update 2: tried siccing aspnet_regiis on that file, got the same "Bad data" error. But the site itself seems up and running and database aware. Maybe the connectionString section is damaged after all, and the site takes it elsewhere.
I"m not sure about doing it via Powershell but here's what I do manually via code-behind on a web page. There might be a clue in here. I can delete this answer if it doesn't help.
protected void btnEncryptConnStrings_Click(object sender, EventArgs e)
{
// Open web.config file as a configuration object to get information.
Configuration objConfigFile = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
// Work with the <connectionStrings> section.
ConfigurationSection connectionStrings = objConfigFile.GetSection("connectionStrings");
if(connectionStrings != null)
{
// Only encrypt the section if it is not already protected.
if(!connectionStrings.SectionInformation.IsProtected)
{
// Encrypt the <connectionStrings> section using the
// DataProtectionConfigurationProvider provider (see notes at top of file).
connectionStrings.SectionInformation.ProtectSection("RsaProtectedConfigurationProvider"); // alt: DataProtectionConfigurationProvider
objConfigFile.Save();
// other stuff.
}
}
}
Related
I'm trying to (re)use ADFS 2/WIF claims based authentication cookies for multiple different applications running on the same domain.
So I have these applications/virtual directories that I would like to reuse the same authentication cookie:
https://domain.local/portal
https://domain.local/myapp
In the portal, I'd like to include (client side authenticated) content from myapp, so I don't want every app to be authenticated separately with a redirect to STS/ADFS.
I thought this would be pretty straightforward as they could both access the same cookie as they reside on the same domain, but the cookie is only valid for the application it was created in (FedAuth and FedAuth1 cookie paths are restricted to "/portal/")
When I set the 'path' in the cookieHandler settings to "/", I will get an exception:
[SecurityTokenException: ID4291: The security token 'System.IdentityModel.Tokens.SessionSecurityToken' is not scoped to the current endpoint.]
System.IdentityModel.Tokens.SessionSecurityTokenHandler.ValidateToken(SessionSecurityToken token, String endpointId) +1008632
System.IdentityModel.Services.SessionAuthenticationModule.ValidateSessionToken(SessionSecurityToken sessionSecurityToken) +351
System.IdentityModel.Services.SessionAuthenticationModule.SetPrincipalFromSessionToken(SessionSecurityToken sessionSecurityToken) +91
System.IdentityModel.Services.SessionAuthenticationModule.AuthenticateSessionSecurityToken(SessionSecurityToken sessionToken, Boolean writeCookie) +66
System.IdentityModel.Services.SessionAuthenticationModule.OnAuthenticateRequest(Object sender, EventArgs eventArgs) +929
System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +80
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +165
I've tried to use the Microsoft.Owin.Security.WsFederation beta packages mentioned in this article as an alternative, no success getting this running:
http://blogs.msdn.com/b/webdev/archive/2014/02/21/using-claims-in-your-web-app-is-easier-with-the-new-owin-security-components.aspx
Before I'm going to try to override methods in the SessionSecurityTokenHandler, is it even possible what I'm trying to achieve?
Thanks in advance!
Change cookieHandler as below in system.identityModel.services --> federationConfiguration
<federatedAuthentication>
<cookieHandler requireSsl="true" path="/" />
</federatedAuthentication>
It was actually pretty simple to do it, by replacing MachineKeySessionSecurityTokenHandler with a custom implementation that get's rid of the token validation:
public class SharedSecurityTokenHandler : MachineKeySessionSecurityTokenHandler
public override ReadOnlyCollection<ClaimsIdentity> ValidateToken(SessionSecurityToken token, string endpointId)
{
if (token == null) throw new ArgumentNullException("token");
if (endpointId == null) throw new ArgumentNullException("endpointId");
return ValidateToken(token);
}
}
the just registering it here in the web.config:
<system.identityModel>
<identityConfiguration>
<securityTokenHandlers>
<add type="Security.Web.SharedSecurityTokenHandler, Security.Web, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
</securityTokenHandlers>
</identityConfiguration>
</system.identityModel>
I've been trying to achieve the same thing and found that SessionAuthenticationModule.ValidateSessionToken(SessionSecurityToken sessionSecurityToken) calls:
securityTokenHandler.ValidateToken(sessionSecurityToken, this.CookieHandler.Path)
..where the second argument is endpointId. Therefore, configuring both my apps with:
<system.identityModel.services>
<federationConfiguration>
<cookieHandler domain="example.com" path="/" />
...
</federationConfiguration>
</system.identityModel.services>
..allowed the validation in MachineKeySessionSecurityTokenHandler to pass.
I am trying to encrypt connection string in my web.config. I have followed the guidelines by microsoft, but it doesn't work. http://msdn.microsoft.com/en-us/library/ff650304.aspx#paght000006_step3
After I got "encrypting configuration sections succeeded!" in command prompt. I deleted "connectionStrings" section from my web.config and kept the newly added "connectionStrings" with encrypted data.
I had two MSSQL database connection strings for Entity Framework, but I am getting an error on runtime compile saying "The specified named connection is either not found in the configuration, not intended to be used with the EntityClient provider, or not valid."
When you open up the model edmx file, and update model from database. Visual Studio displays error saying "Failed to decrypt using provider RSAProtectedConfigurationProvider....The RSA key container could not be opened."
<connectionStrings configProtectionProvider="RsaProtectedConfigurationProvider">
<EncryptedData Type="http://www.w3.org/2001/04/xmlenc#Element"
xmlns="http://www.w3.org/2001/04/xmlenc#">
<EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#tripledes-cbc" />
<KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">
<EncryptedKey xmlns="http://www.w3.org/2001/04/xmlenc#">
<EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-1_5" />
<KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">
<KeyName>Rsa Key</KeyName>
</KeyInfo>
<CipherData>
<CipherValue>..........</CipherValue>
</CipherData>
</EncryptedKey>
</KeyInfo>
<CipherData>
<CipherValue>........</CipherValue>
</CipherData>
</EncryptedData>
</connectionStrings>
-------- solved, answer below. ------
It looks like the account which created the key is different from the account running the app. Have you ensured the appropriate accounts have access to the key store? From that article you sent...
To grant access to the ASP.NET application identity
a.If you are not sure which identity to use, check the identity from a Web page by using the following code:
using System.Security.Principal;
protected void Page_Load(object sender, EventArgs e)
{
Response.Write(WindowsIdentity.GetCurrent().Name);
}
By default, ASP.NET applications on Windows Server 2003 run using the NT Authority\Network Service account. Open a .NET command prompt, and use the following command to give this account access to the NetFrameworkConfigurationKey store:
aspnet_regiis -pa "NetFrameworkConfigurationKey" "NT Authority\Network Service"
If the command runs successfully you will see the following output:
Adding ACL for access to the RSA Key container...
Succeeded!
You can check the ACL of the file in the following folder:
\Documents and Settings\All Users\Application Data\Microsoft\Crypto\RSA\MachineKeys
Your RSA key container file is the file in this folder with the most recent timestamp.
Also, these simple commands seemed to work for use of EF/Linq-to-Entities
When you run aspnet commands, the encrypted data should replace the "connectionStrings", if it doesn't, then it failed. aspnet_regiis -pe "connectionStrings" -app "/" -location "subfolder" -site "2"
I ran that command, but it turns out I don't need -location and that was incorrect.
I should have known, when the cipher Value XML field was so small.
However, these two commands do the trick...
aspnet_regiis -pe "connectionStrings" -app "/" -site "2"
aspnet_regiis -pa "NetFrameworkConfigurationKey" "IIS APPPOOL\MyApp"
Run This Code On Your Server that Publish your Project
string provider = "RSAProtectedConfigurationProvider";
string section = "connectionStrings";
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnEncrypt_Click(object sender, EventArgs e)
{
Configuration confg = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
ConfigurationSection configSect = confg.GetSection(section);
if (configSect != null)
{
configSect.SectionInformation.ProtectSection(provider);
confg.Save();
}
}
protected void btnDecrypt_Click(object sender, EventArgs e)
{
Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
ConfigurationSection configSect = config.GetSection(section);
if (configSect.SectionInformation.IsProtected)
{
configSect.SectionInformation.UnprotectSection();
config.Save();
}
}
in this link : http://www.codeproject.com/Tips/304638/Encrypt-or-Decrypt-Connection-Strings-in-web-confi
<connectionStrings configProtectionProvider="RsaProtectedConfigurationProvider">
<EncryptedData Type="http://www.w3.org/2001/04/xmlenc#Element"
xmlns="http://www.w3.org/2001/04/xmlenc#">
<EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#tripledes-cbc" />
<KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">
<EncryptedKey xmlns="http://www.w3.org/2001/04/xmlenc#">
<EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-1_5" />
<KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">
<KeyName>Rsa Key</KeyName>
</KeyInfo>
<CipherData>
<CipherValue>WagJ9DDjWTNc1nmYVNQXaQqXalQzXaiCHAOtUJvTWBRZiuT6UK1fBElM80PnL6dC5Umb8qvfHdkSMgoMW9CJzwOTZ0zTy17JBGZqRQmlfW2G9LacoWIil0UrxjhgmJmRXhwXHFpdGwEVl7AoQGVlJGabXuChutaTxmfGOoUbCr0=</CipherValue>
</CipherData>
</EncryptedKey>
</KeyInfo>
<CipherData>
<CipherValue>qry5qnr3qxOgyoNPeP7OKEiHpr/PPTsaeQ2mYUsSK7cg4Kkl9uPO4RyUXgBIkgCTsjbObqLlyndcSBnYyek6bxG/IBL82G1R5J1ci8i1eyt8kIDqouzYOx5vtouErld4z1L+7WGf9Wg37QAH5RiiEfkCHndJJq3dTqjxnnXZSno6NgbxSXDfqzwE/eKDVhGV3oaTQSfjVmO8e5a9wvREYeeyasDhojx8J2mdy7/Q9rEIpv98RTiRxA==</CipherValue>
</CipherData>
</EncryptedData>
</connectionStrings>
How can I encrypt only passwords in a web.config file?
<add name="PSystem" connectionString="Server=test;Database=Dev;User ID=testuser;Password=password#123;Trusted_Connection=False;Encrypt=True;" providerName="System.Data.SqlClient" />
I believe that built-in encryption mechanisms work on the entire connectionString section:
See this website for more info
If you would like to encrypt in-memory passwords, maybe entered by the user through a login form, you could use SecureString
you can try using flags in the connecction string as follows:
<add name="PSystem"
connectionString="Server=test;
Database=Dev;
User ID=#UserID#;
Password=#Password#;
Trusted_Connection=False;
Encrypt=True;"
providerName="System.Data.SqlClient" />
then you can have the encrypted user and password as follows:
<add key="DB_User" value = [Encrypted Username]>
<add key="DB_Password" value = [Encrypted Password]>
Then in code you just replace the flags:
string _connectionString = ConfigurationManager.ConnectionStrings["PSystem"].ConnectionString;
string user = Decrypt(ConfigurationManager.AppSettings["DB_User"]);
string password = Decrypt(ConfigurationManager.AppSettings["DB_Password"]);
_connectionString = _connectionString.Replace("##User##", user).Replace("##Password##", password);
To encrypt configuration file
contents, use the Aspnet_regiis.exe tool with the –pe option and the
name of the configuration element to be encrypted.
aspnet_regiis -pe "connectionStrings" -app "/SampleApplication" -prov
"RsaProtectedConfigurationProvider"
Source: http://msdn.microsoft.com/en-us/library/zhhddkxy(v=vs.100).aspx
I am working on a asp.net web application that has is a part of TFS and is used by the development team. Recently as part of the project we setup ADFS and are now attempting to enforce authentication of the project to an ADFS server.
On my development machine I have gone through the steps of adding STS reference which generates the Federation Meta-Data as well as updates the web.config file for the project. Authorization within the web.config uses thumbprint certification which requires me to add to my local machine the ADFS certificate as well as generate a signed certificate for the dev machine and add this to ADFS.
All is setup and working but in looking at the web.config. and FederationMetadata.xml document these "appear" to be machine specific. I suspect that if I check the project/files into TFS the next developer or tester that takes a build will end up with a broken build on their machine.
My question is within TFS what is the process for a scenario like this to check in and still allow my team to check out, build, and test the project with the latest code in their development or test environments?
My work around at this time is to exclude the FederationMetaData.xml and web.config from check in then on each development machine manually setup ADFS authentication as well as for product test. Once done each person can prevent their local copy of the FederationMetatData.xml and web.config from being checked in.(aka have their own local copy) then when checking in/out just ensure that each developer preserves their own copy (or does not check them into TFS)
This seems extremely inefficient, and all but bypasses the essence of source code management as developers are being required to keep local copies of files on their machine. This also seems to introduce the opportunity for accidental check-in of local files or overwriting local files.
Does anyone have any references, documentation or information on how to check-in code for (ADFS) machine specific configurations and not hose up the entire development environment?
Thanks in advance,
I agree that the way that the WIF toolset does configuration is not great for working in teams with multiple developers and test environments. The approach that I've taken to get past this is to change WIF to be configured at runtime.
One approach you can take is to put a dummy /FederationMetadata/2007-06/FederationMetadata.xml in place and check that in to TFS. It must have valid urls and be otherwise a valid file.
Additionally, you will need a valid federationAuthentication section in web.config with dummy (but of valid form) audienceUris, issuer and realm entries.
<microsoft.identityModel>
<service>
<audienceUris>
<add value="https://yourwebsite.com/" />
</audienceUris>
<federatedAuthentication>
<wsFederation passiveRedirectEnabled="true" issuer="https://yourissuer/v2/wsfederation" realm="https://yourwebsite.com/" requireHttps="true" />
<cookieHandler requireSsl="false" />
</federatedAuthentication>
etc...
Then, change your application's ADFS configuration to be completely runtime driven. You can do this by hooking into various events during the ADFS module startup and ASP.NET pipeline.
Take a look at this forums post for more information.
Essentially, you'll want to have something like this in global.asax.cs. This is some code that I've used on a Windows Azure Web Role to read from ServiceConfiguration.cscfg (which is changeable at deploy/runtime in the Azure model). It could easily be adapted to read from web.config or any other configuration system of your choosing (e.g. database).
protected void Application_Start(object sender, EventArgs e)
{
FederatedAuthentication.ServiceConfigurationCreated += OnServiceConfigurationCreated;
}
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
/// Due to the way the ASP.Net pipeline works, the only way to change
/// configurations inside federatedAuthentication (which are configurations on the http modules)
/// is to catch another event, which is raised everytime a request comes in.
ConfigureWSFederation();
}
/// <summary>
/// Dynamically load WIF configuration so that it can live in ServiceConfiguration.cscfg instead of Web.config
/// </summary>
/// <param name="sender"></param>
/// <param name="eventArgs"></param>
void OnServiceConfigurationCreated(object sender, ServiceConfigurationCreatedEventArgs eventArgs)
{
try
{
ServiceConfiguration serviceConfiguration = eventArgs.ServiceConfiguration;
if (!String.IsNullOrEmpty(RoleEnvironment.GetConfigurationSettingValue("FedAuthAudienceUri")))
{
serviceConfiguration.AudienceRestriction.AllowedAudienceUris.Add(new Uri(RoleEnvironment.GetConfigurationSettingValue("FedAuthAudienceUri")));
Trace.TraceInformation("ServiceConfiguration: AllowedAudienceUris = {0}", serviceConfiguration.AudienceRestriction.AllowedAudienceUris[0]);
}
serviceConfiguration.CertificateValidationMode = X509CertificateValidationMode.None;
Trace.TraceInformation("ServiceConfiguration: CertificateValidationMode = {0}", serviceConfiguration.CertificateValidationMode);
// Now load the trusted issuers
if (serviceConfiguration.IssuerNameRegistry is ConfigurationBasedIssuerNameRegistry)
{
ConfigurationBasedIssuerNameRegistry issuerNameRegistry = serviceConfiguration.IssuerNameRegistry as ConfigurationBasedIssuerNameRegistry;
// Can have more than one. We don't.
issuerNameRegistry.AddTrustedIssuer(RoleEnvironment.GetConfigurationSettingValue("FedAuthTrustedIssuerThumbprint"), RoleEnvironment.GetConfigurationSettingValue("FedAuthTrustedIssuerName"));
Trace.TraceInformation("ServiceConfiguration: TrustedIssuer = {0} : {1}", RoleEnvironment.GetConfigurationSettingValue("FedAuthTrustedIssuerThumbprint"), RoleEnvironment.GetConfigurationSettingValue("FedAuthTrustedIssuerName"));
}
else
{
Trace.TraceInformation("Custom IssuerNameReistry type configured, ignoring internal settings");
}
// Configures WIF to use the RsaEncryptionCookieTransform if ServiceCertificateThumbprint is specified.
// This is only necessary on Windows Azure because DPAPI is not available.
ConfigureWifToUseRsaEncryption(serviceConfiguration);
}
catch (Exception exception)
{
Trace.TraceError("Unable to initialize the federated authentication configuration. {0}", exception.Message);
}
}
/// <summary>
/// Configures WIF to use the RsaEncryptionCookieTransform, DPAPI is not available on Windows Azure.
/// </summary>
/// <param name="requestContext"></param>
private void ConfigureWifToUseRsaEncryption(ServiceConfiguration serviceConfiguration)
{
String svcCertThumbprint = RoleEnvironment.GetConfigurationSettingValue("FedAuthServiceCertificateThumbprint");
if (!String.IsNullOrEmpty(svcCertThumbprint))
{
X509Store certificateStore = new X509Store(StoreName.My, StoreLocation.LocalMachine);
try
{
certificateStore.Open(OpenFlags.ReadOnly);
// We have to pass false as last parameter to find self-signed certs.
X509Certificate2Collection certs = certificateStore.Certificates.Find(X509FindType.FindByThumbprint, svcCertThumbprint, false /*validOnly*/);
if (certs.Count != 0)
{
serviceConfiguration.ServiceCertificate = certs[0];
// Use the service certificate to protect the cookies that are sent to the client.
List<CookieTransform> sessionTransforms =
new List<CookieTransform>(new CookieTransform[] { new DeflateCookieTransform(),
new RsaEncryptionCookieTransform(serviceConfiguration.ServiceCertificate)});
SessionSecurityTokenHandler sessionHandler = new SessionSecurityTokenHandler(sessionTransforms.AsReadOnly());
serviceConfiguration.SecurityTokenHandlers.AddOrReplace(sessionHandler);
Trace.TraceInformation("ConfigureWifToUseRsaEncryption: Using RsaEncryptionCookieTransform for cookieTransform");
}
else
{
Trace.TraceError("Could not find service certificate in the My store on LocalMachine");
}
}
finally
{
certificateStore.Close();
}
}
}
private static void ConfigureWSFederation()
{
// Load the federatedAuthentication settings
WSFederationAuthenticationModule federatedModule = FederatedAuthentication.WSFederationAuthenticationModule as WSFederationAuthenticationModule;
if (federatedModule != null)
{
federatedModule.PassiveRedirectEnabled = true;
if (!String.IsNullOrEmpty(RoleEnvironment.GetConfigurationSettingValue("FedAuthWSFederationRequireHttps")))
{
federatedModule.RequireHttps = bool.Parse(RoleEnvironment.GetConfigurationSettingValue("FedAuthWSFederationRequireHttps"));
}
if (!String.IsNullOrEmpty(RoleEnvironment.GetConfigurationSettingValue("FedAuthWSFederationIssuer")))
{
federatedModule.Issuer = RoleEnvironment.GetConfigurationSettingValue("FedAuthWSFederationIssuer");
}
if (!String.IsNullOrEmpty(RoleEnvironment.GetConfigurationSettingValue("FedAuthWSFederationRealm")))
{
federatedModule.Realm = RoleEnvironment.GetConfigurationSettingValue("FedAuthWSFederationRealm");
}
CookieHandler cookieHandler = FederatedAuthentication.SessionAuthenticationModule.CookieHandler;
cookieHandler.RequireSsl = false;
}
else
{
Trace.TraceError("Unable to configure the federated module. The modules weren't loaded.");
}
}
}
This will then allow you to configure the following settings at runtime:
<Setting name="FedAuthAudienceUri" value="-- update with audience url. e.g. https://yourwebsite/ --" />
<Setting name="FedAuthWSFederationIssuer" value="-- update with WSFederation endpoint. e.g. https://yourissuer/v2/wsfederation--" />
<Setting name="FedAuthWSFederationRealm" value="-- update with WSFederation realm. e.g. https://yourwebsite/" />
<Setting name="FedAuthTrustedIssuerThumbprint" value="-- update with certificate thumbprint from ACS configuration. e.g. cb27dd190485afe0f62e470e4e3578de51d52bf4--" />
<Setting name="FedAuthTrustedIssuerName" value="-- update with issuer name. e.g. https://yourissuer/--" />
<Setting name="FedAuthServiceCertificateThumbprint" value="-- update with service certificate thumbprint. e.g. same as HTTPS thumbprint: FE95C43CD4C4F1FC6BC1CA4349C3FF60433648DB --" />
<Setting name="FedAuthWSFederationRequireHttps" value="true" />
We developed an application to edit the web.config settings. The user has to locate the web.config file which they like to edit. Once their task is completed they can download the web.config file with the changes made by them. Since the web.config file has the database server information and passwords I have a concern that will it cause any security problem.
If so how can I rectify it?
Better encrypt your Connection string....
For ref MSDN article
You can use the following method to secure the the webconfig.
if there exist the following code at web.config.
<connectionStrings>
<add name="yjsDBConnectionString" connectionString="Data Source=HUAJLI-XP\SUN;Initial Catalog=yjsDB;Integrated Security=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
Then we can use the following code to protect it.
protected void Encryption()
{
Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
ConfigurationSection section = config.ConnectionStrings;
if (!section.SectionInformation.IsProtected)
{
section.SectionInformation.ProtectSection("DataProtectionConfigurationProvider");
section.SectionInformation.ForceSave = true;
config.Save(ConfigurationSaveMode.Modified);
}
}
And you can use the following code to Decrypting it.
protected void Decrypting()
{
Configuration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
ConfigurationSection section = config.ConnectionStrings;
if (section.SectionInformation.IsProtected)
{
section.SectionInformation.UnprotectSection();
section.SectionInformation.ForceSave = true;
config.Save(ConfigurationSaveMode.Modified);
}
}