encrypting appSettings in a external file using aspnet_regiis -pef - c#

I am trying to encrypting appSettings in a external file using aspnet_regiis -pef. Does anyone how how to do this.
My main web config file :
<appSettings file="ExternalAppSettings.config">
<add key="test1" value="val1" />
<add key="test2" value="val2" />
</appSettings>
external file ExternalAppSettings.config
<appSettings>
<add key="pwd1" value="test1" />
<add key="pwd2" value="test2" />
</appSettings>
I want to encrypt only appsetting in ExternalAppSettings.config how to do this ?

I have done this type of work. I just encrypt the string and than put encrypted string in the values. when i retrieve the values i will again decrypt it into original values.

Please try the below.
aspnet_regiis -pe "appSettings" -prov "{0}" -site {1} -app "/"
example: aspnet_regiis -pe "appSettings" -prov "DataProtectionConfigurationProvider" -site "1" -app "/virtualdirectory_name"
{0}: encryption provider
{1} : Site id in IIS

Related

The X.509 certificate could not be loaded from the file

I am using the API SAML2.0 for ASP.net MVC and I used openssl to create the private and public key files and used a password for the private file. It generated two files ca.key and cas.pem, I used the ca.key file as the private key but I am getting this error
Additional information: The X.509 certificate could not be loaded from the file D:\Test Web Projects\TestSaml\TestSaml\Certificates\ca.key.
My users login to my mvc application the login process has nothing to do with SAML. I just check the users against my DB. The reason I am using SAML2.0 is because I need to direct my users for payment process to another external page which is my service provider. So once they click on a button on my page they should be redirected to the other website. The following is the sample code I built to verify if its working.
Web.config
<?xml version="1.0" encoding="utf-8"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=301880
-->
<configuration>
<appSettings>
<add key="TargetURL" value="https://btat2.paybill.com/consumer/SSO/SSOLogin?clientId=ReadyCapital"/>
<add key="webpages:Version" value="3.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
</system.web>
</configuration>
Saml.config
<?xml version="1.0"?>
<SAMLConfiguration xmlns="urn:componentspace:SAML:2.0:configuration">
<IdentityProvider Name="https://TestSaml"
Description="Test Identity Provider"
LocalCertificateFile="Certificates\ca.key"
LocalCertificatePassword="readycapital"/>
<PartnerServiceProviders>
<!-- MVC example -->
<PartnerServiceProvider Name="urn:oasis:names:tc:SAML:2.0:assertion"
Description="MVC Example Service Provider"
SignSAMLResponse="true"
SignAssertion="false"
EncryptAssertion="true"
AssertionConsumerServiceUrl="http://www.paybill.com/V2/Test/Login.aspx"
PartnerCertificateFile="Certificates\btat2.cert"/>
</PartnerServiceProviders>
</SAMLConfiguration>
Controller
public ActionResult Index(Profile profile)
{
string targetUrl = WebConfigurationManager.AppSettings["TargetURL"];
string userName = "00373219101";// WebConfigurationManager.AppSettings["SubjectName"];
SAMLAttribute[] attributes = new SAMLAttribute[2];
SAMLAttribute attribute = new SAMLAttribute("UserEmailAddress", SAMLIdentifiers.AttributeNameFormats.Unspecified, null, string.Empty);
attributes[0] = attribute;
SAMLAttribute attribute2 = new SAMLAttribute("MiscellaneousData", SAMLIdentifiers.AttributeNameFormats.Unspecified, null, string.Empty);
attributes[1] = attribute2;
SAMLIdentityProvider.InitiateSSO(Response, userName, attributes, targetUrl);
}
Did you check that the WebServer can actually access the files? Maybe use Microsoft Windows Sysinternals Process Monitor and check that the read operation is successful.
Replace the standalone .key file with a .pfx file both containing the certificate as well as the private key and link to that in IdentityProvider/#LocalCertificateFile

Protecting your Connection String on Shared Hosting

I am creating a website using MVC5 & EF6. I am also using a shared hosting to publish this website. Now the problem that I have is that my connection string at the moment is sitting in plain text in the web.config file. I am having a very hard time finding a "direct" answer on how I should deal with this.
I have come upon many articles such as this one. The article shows me how to encrypt the Connection Section of my web.config. So I tried following its example and encrypted the mail section it shows in that example. After I ran my code I noticed that my entire web.config file changed.
It use to be like this:
<system.net>
<mailSettings>
<smtp from="info#Site.com">
<network
host="mail.Site.com"
port="25"
userName="info#site.com"
password="password" />
</smtp>
</mailSettings>
</system.net>
and now it is like this:
<mailSettings>
<smtp 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>odapFFPDF1Fgsk2wyvbwVC4SNISqhWc9lXiAq+I/OW3wVVqBCPowxyen9M7c9+KUBkXmGSfaUVxDMlqutChv6g6VU8h4TWG3W6Tw/istjfw/UYrRsGguPiOqdvRsl9XLBmnS37v99+VX7FEA9TKb6ufC0a3Defp2MNpGTvTIR20=</CipherValue>
</CipherData>
</EncryptedKey>
</KeyInfo>
<CipherData>
<CipherValue>lHPPFRJAH2hIm/Ya+ABRMP5mo5rEYwL2aBJQ/DT4Q+1OZXaftutiddxxJZ4LSgw3pzi1QJpU8eOPwFVebvqFVA4cjs27l8Iqz50E/R/tBfS7e2oqdWTRsc8IFfE/xOIieMp22BuFsYEDbgnIbLdbHJnw+92zyt2lUlzJpW9epNpnb29sVQhtNJ9cPjAaYAaU</CipherValue>
</CipherData>
</EncryptedData>
</smtp>
</mailSettings>
My only problem right now is how do I read those values inside my code without having to decrypt and save the config file. I do not want to rewrite the webconfig file ever time I need to read the mail setting section or even the connection string section.
If I have a method like this:
public static string DecryptMailSettings()
{
var config = WebConfigurationManager.OpenWebConfiguration("~");
ConfigurationSection section = config.GetSection("system.net/mailSettings/smtp");
if (section.SectionInformation.IsProtected)
{
section.SectionInformation.UnprotectSection();
return section.???;
}
return "Nothing was read";
}
How do I get the value of lets say "host" from the example above.
From the documentation:
ASP.NET automatically decrypts the contents of the Web.config file when it processes the file. Therefore, no additional steps are required to decrypt the encrypted configuration settings for use by other ASP.NET features or to access the values in your code.
https://msdn.microsoft.com/en-us/library/dtkwfdky.aspx
I am suggesting that if the encryption/decryption is working fine, and it seems like that 'untangling' the Host Name is troublesome then just add a value to your web.config .
Like This:
<appSettings>
<add key="MAILHOST" value="mail.Site.com" /> ,
and then read that in your code.
Ex:
string HostName = ConfigurationManager.AppSettings["MAILHOST"].ToString();

Get connectionstring from web.config

I use System.Configuration.ConfigurationManager.AppSettings["key1"] in settings.designer.cs file. It's working fine in the development but after I moved all the .dll files into production it is not working.
In web.config file I added app settings in development and production both. What is the problem?
Code from settings.designer.cs file
get
{
return WebConfigurationManager.AppSettings["ConnectionString"];
//return (AppSettings["ConnectionString"]);
//return ((string)(this["ConnectionString"]));
}
I tried all three return statements. 3rd return is working fine in both dev & prod but it is not rendering from web.config.
Code in web.config
<add key="ConnectionString" value="connection string values are given here">
Don't use WebConfigurationManager.
Use System.Configuration.ConfigurationManager.AppSettings["key"] instead to read key-value pair kept in Web.config, e.g.:
<configuration>
<appSetttings>
<add key="key1" value="value1" />
</appSetttings>
</configuration>
and System.Configuration.ConfigurationManager.ConnectionStrings["name"].ConnectionString to read connection string, e.g.:
<configuration>
<connectionStrings>
<add name="name" connectionString="value1" />
</connectionStrings>
</configuration>
You have to add configuration setting (connectionstring) to last execution program config file.

reading symbols from application configuration file

I'm reading a password from a config file with my C# application (it's a windows service). I'm using these lines:
private NameValueCollection appSettings = ConfigurationManager.AppSettings;
string password = appSettings["Password"];
The config looks like:
<add key="Password" value="exam&ple" />
The service can't start because the application configuration is incorrect. If I remove the '&', the service works. How could I control this problem?? Thanks.
You need to encode your values in the app.config like this
<add key="Password" value="exam&ple"/>

How to encrypt app.config?

Create app.config in wpf (c#)
<?xml version="1.0"?>
<configuration>
<connectionStrings>
<clear />
<add name="Name"
providerName="MySql.Data"
connectionString="Server=.net;Uid=;Pwd=H;Database=;charset=utf8;Allow Zero Datetime=true;" />
</connectionStrings>
</configuration>
used code C#:
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
ConnectionStringsSection conStr = config.ConnectionStrings;
if (!conStr.SectionInformation.IsProtected)
{
conStr.SectionInformation.ProtectSection("RSAProtectedConfigurationProvider");
conStr.SectionInformation.ForceSave = true;
config.Save();
}
else
{
foreach (ConnectionStringSettings ss in conStr.ConnectionStrings)
Console.WriteLine(ss);
Console.Read();
}
config.Save(); - causes exception:
{"Failed to encrypt the section 'connectionStrings' using provider
'RsaProtectedConfigurationProvider'. The error message from the
provider: Object already exists .\r\n"}
I was getting the same exception on Save. By running the application as an Administrator, I was able to get around this.
I added an app.manifest file to my project, and changed the execution level like so: requestedExecutionLevel level="requireAdministrator" uiAccess="false"
This way, I always run as admin, and have permissions to save the encrypted section.
Check the SectionInformation.ProtectSection Method
also check here
You could look at using the aspnet_regiis.exe to perform encryption for you. Refer to this
MSDN Link
This way you could perform encryption without writing code.

Categories

Resources