Overload FromCertificate to get byte array
Ron Grabowski suggested the following:
I was having difficulties calling the X509Certificate2 constructor to load my
key.p12 file on GoDaddy's shared .NET hosting (IIS 7.0, ASP.Net 4.0/4.5, Full
Trust, GoDaddy Hosting Configuration: 2.1):
var certificate = new X509Certificate2(keyp12, "notasecret",
X509KeyStorageFlags.Exportable);
I received a "System.Security.Cryptography.CryptographicException: An internal
error occurred" message similar to this:
http://stackoverflow.com/questions/14263457/x509-certificate-not-loading-private
-key-file-on-server
I don't have control to run my app pool under an identity that allows p12 certs
to be loaded. Because I'm using shared hosting I can't connect to an IIS admin
panel to make the "Load User Profile" change. This technique doesn't seem to
work:
http://blogs.msdn.com/b/vijaysk/archive/2009/03/08/iis-7-tip-3-you-can-now-load-
the-user-profile-of-the-application-pool-identity.aspx
I ended up having to extend ServiceAccountCredential.Initializer and use Bouncy
Castle to load the key.p12 file, extract the private key, and override how
ServiceAccountCredential.Initializer's Key property was set:
https://gist.github.com/ronosaurus/43fcadf43e78cd00c445
Perhaps an overload could be added that accepts a private key blob to bypass
the X509Certificate2 container:
https://code.google.com/p/google-api-dotnet-client/source/browse/Src/GoogleApis.
Auth.DotNet4/OAuth2/ServiceAccountCredential.cs#76
// proposed
public Initializer FromCertificate(X509Certificate2 certificate)
{
// Workaround to correctly cast the private key as a RSACryptoServiceProvider type 24.
RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)certificate.PrivateKey;
byte[] privateKeyBlob = rsa.ExportCspBlob(true);
return FromCertificate(privateKeyBlob);
}
// new
public Initializer FromCertificate(byte[] privateKeyBlob)
{
Key = new RSACryptoServiceProvider();
Key.ImportCspBlob(privateKeyBlob);
return this;
}
We should just overload FromCertificate(byte[] privateKeyBlob) :)
Original issue reported on code.google.com by [email protected] on 14 Jan 2015 at 6:03
Since version 1.9.3. you can create service account credential from a json key (see FromPrivateKey method). That way, you won't need to instantiate the X509Certificate2. Using json keys recommended over .p12 keys now anyway.
Closing for now, feel free to reopen.
Hope you don't mind me asking in a closed thread - but does anyone have an example on how to use a json key for google calendar in an MVC web app? I'm only seeing p12 examples and mine's currently hanging at the point where it's supposed to be retrieving events, so I wanted to try the json approach.