Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can not find the specified object with X509Certificate2

I'm trying to load a file that contains the secret key to access to Google Calendar API. Following this tutorial. For doing this I've created this code:

var certificate = new X509Certificate2("client_secret.json", "notasecret", X509KeyStorageFlags.Exportable);

I've uploaded client_secret.json file inside my solution, this is the path of the file: "...\Visual Studio 2015\Projects\Calendar\Calendar\bin\Debug\client_secret.json"

but seems that the code can't locate the file and return this error:

Can not find the specified object with X509Certificate2

I also set the property Always copy on Copy in the output directory on the file to read.

like image 925
Dillinger Avatar asked Apr 29 '16 19:04

Dillinger


2 Answers

After a bit 'of headaches I was able to understand where wrong, as I said in the comments I generate the certificate by:

The first step that I did is create the API for Google Calendar, later I clicked on "create credentials" and selected "Service account", choosing the API that I've created before and the key type as json.

this certificate is different against the key the the X509Certificate2 waiting, so the correct step to do is:

1. Click on Manage Service Account on the Developer Console, this workding is on the right of the credentials tab, just a little 'over to your projects list.

2. A new window appears, you need to click on the three dots next to the project you want to create the key. (The three dots are on the right).

3. A pop-up menu appear, and then, you need to click Create Key.

4. Chose the P12 format, and then click on Create.

5. Save the file downloaded on a folder and link them in your code, in particular:

var certificate = new X509Certificate2(@"C:\key.p12", "notasecret", X509KeyStorageFlags.Exportable | X509KeyStorageFlags.MachineKeySet);

note that key.p12 is the name of the file of the certificate, and notasecret is the default password that appear just a bit later of the step 4, in other word is the password associated to the certificate.

So my code seems to find the file and read it correctly without display any errors.

Thanks anyway to MegaTron that have aroused in me the doubt that the certificate was somehow not right.

like image 145
Dillinger Avatar answered Nov 11 '22 18:11

Dillinger


Try to use MachineKeySet. It means that need to use the local computer store for the key:

var certificate = new X509Certificate2("client_secret.json", "notasecret", X509KeyStorageFlags.Exportable | X509KeyStorageFlags.MachineKeySet);
like image 1
Roman Marusyk Avatar answered Nov 11 '22 18:11

Roman Marusyk