Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read a .p12 file in my web service

I have a question. I have a web service and I have a ".p12" file that I need to read in my web service for processing a couple of instructions. Reading the ".p12" file is necessary (The file [certified] allow me create users in my domain [google email service])

Well, In my machine the web service is running fine, but When I publish the web service in the server it doesn't work. I have copied the file (.p12) in the main folder of the web service, in the bin folder too, in the "C" unit in the server, but it doesn't work.

This is the line that read the file (I'm using C#):

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

It shows me one error: The server can not process the request. ---> Internal error.

After that, I tried this:

string hpath = HttpContext.Current.Server.MapPath(".");
hpath = hpath + "\\nameOfMyFile.p12";
var certificate = new X509Certificate2(System.Web.HttpContext.Current.Server.MapPath(hpath, "notasecret", X509KeyStorageFlags.Exportable);

It shows me the same error: The server can not process the request. ---> Internal error.

After that, I just write the name of the file:

var certificate = new X509Certificate2(@"nameOfMyFile.p12", "notasecret", X509KeyStorageFlags.Exportable);

It shows me this error: The server can not process the request. ---> The system can not find the file specified

So, Do I need to assign one special permission to the file, folder, web service ? What is the best way to read a file like this (.p12)?

Thanks in advance.

like image 572
Orlando Herrera Avatar asked Oct 26 '25 21:10

Orlando Herrera


1 Answers

Honestly I don't Know if this is the best way to do it, but it works in my case.

Add these namespaces:

using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;

I use this code:

X509Certificate2 certificate = new X509Certificate2(@"file.p12", "password", X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable);

And finally I copied my ".p12" file in the "inetsrv" folder of windows.

like image 193
Orlando Herrera Avatar answered Oct 28 '25 13:10

Orlando Herrera



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!