Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CryptographicException: Access denied - How to give access on User store?

I am trying to load a certificate from a pfx file in a WPF application and it gives me an access denied error.

using (FileStream stream = System.IO.File.OpenRead(certificatePath))
{
    using (BinaryReader reader = new BinaryReader(stream))
    {
        buffer = reader.ReadBytes((int)stream.Length);
    }
}

X509Certificate2 certificate = new X509Certificate2(buffer, password);

System.Security.Cryptography.CryptographicException: Access denied.
at System.Security.Cryptography.CryptographicException.ThrowCryptographicException(Int32 hr) at System.Security.Cryptography.X509Certificates.X509Utils._LoadCertFromBlob(Byte[] rawData, IntPtr password, UInt32 dwFlags, Boolean persistKeySet, SafeCertContextHandle& pCertCtx) at System.Security.Cryptography.X509Certificates.X509Certificate.LoadCertificateFromBlob(Byte[] rawData, Object password, X509KeyStorageFlags keyStorageFlags) at System.Security.Cryptography.X509Certificates.X509Certificate2..ctor(Byte[] rawData, String password) at HelloWorld.HelloClient.Models.Infrastructure.ReadCertificateFromPfxFile(String certificatePath, String password)

The last line in snippet is causing an exception, and if I run it as an administrator it works fine. The issue seems to be the default constructor of X509Certificate2 tries to put private key in the user store. I am not using web application. this post doesn't resolve my issue. I think the current user might not have access to his own private key store. But how can I give that access?

like image 744
Shiju Samuel Avatar asked Dec 25 '22 04:12

Shiju Samuel


2 Answers

Posting a fix if someone looking for a solution for similar issue. I ran sysinternal process monitor and realized the constructor call was creating a key in machine key folder and gave user access to write on machine key.

like image 190
Shiju Samuel Avatar answered Feb 13 '23 05:02

Shiju Samuel


In my situation, it was due to the lack of write access to the C:\ProgramData\Microsoft\Crypto\RSA\MachineKeys folder.

My user was having only having the Read Access and once I granted the Write access it worked fine.

like image 39
dinith jayabodhi Avatar answered Feb 13 '23 05:02

dinith jayabodhi