Prasanth S
Prasanth S

Reputation: 179

X509Certificate2 certification issue

I am working on a payment gateway integration with a certificate key (.pfx) file provided by the concerned authority, While I am working on localhost everything working perfect as I expected.But after I published in windows server 2019 we got some issue in the token generation process.

This is the token generation code we are used

RSACng key = new System.Security.Cryptography.RSACng();
            X509Certificate2 publicCert = new X509Certificate2(publicKeyLocation, "123", X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.PersistKeySet);
            X509Certificate2 privateCert = null;
            X509Store store = new X509Store(StoreLocation.CurrentUser);
            store.Open(OpenFlags.ReadOnly);
            foreach (X509Certificate2 cert in store.Certificates)
            {
                var val1 = publicCert.GetCertHashString();
                if (cert.GetCertHashString() == publicCert.GetCertHashString())
                    privateCert = cert;
            }
            key = privateCert.GetRSAPrivateKey() as RSACng;
            byte[] signature = key.SignHash(hashValue, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
            key = (System.Security.Cryptography.RSACng)publicCert.GetRSAPublicKey();
            if (!key.VerifyHash(hashValue, signature, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1))
                throw new CryptographicException();
            return signature;

This is the response we get while calling the api from localhost

Success Response Got In Localhost

This is the response of api after we publish in windows server 2019

Failure response after publishing the api

Upvotes: 0

Views: 589

Answers (1)

Tomas Chabada
Tomas Chabada

Reputation: 3019

The problem lies here: X509Store store = new X509Store(StoreLocation.CurrentUser);

That is working on your PC, because you have certificate stored under the CurrentUser store, but when you deploy application to Windows Server, the user that the application is running on does not have a specific certificate in it's cert store.

Install the certificate to LocalMachine cert store and get it from there:

X509Store store = new X509Store(StoreLocation.LocalMachine);

or install the certificate to correct CurrentUser store (not recommended, user may be NetworkUser, or System, ...)

Upvotes: 2

Related Questions