I have some code that needs to work with X509 Certificate information. I have downloaded a sample that does this:
const string CertWithoutPrivateKey = "MII....";
const string CertWithPrivateKey = "MII...";
public static SecurityToken GetSigningToken(bool includePrivateKey)
{
X509Certificate2 cert = null;
if (includePrivateKey)
{
cert = new X509Certificate2(
Convert.FromBase64String(CertWithPrivateKey),
"pw", X509KeyStorageFlags.PersistKeySet);
}
else
{
cert = new X509Certificate2(
Convert.FromBase64String(CertWithoutPrivateKey));
}
return cert;
}
The code needs to be able to get the cert with the private key. The Saml2AuthenticationModule (from the WIF Extension for the SAML 2.0 Protocol) relies on this private key to decrypt information sent from a SAML Identity Provider.
I don't know much about certificates or encryption, but it seems to me that hard-coding the certificate into a class is not secure.
So, how should my code go about retrieving the cert with private key? Afaik, this code is only run one time at app startup (so probably also after an app pool recycle).
I could:
- Store the cert as an appSetting in config file. As long as appSettings are config encrypted, is this secure?
- Store the cert in a database.
- Store the cert as a file in bin/App_Data. Afaik this means it could not be read over the web, but would be in plain view to anyone who can access the host server. Imo if someone can get into my server, letting them read this cert is probably the least of my worries.
Are there any other options? What is most appropriate in this case?