Lee
Lee

Reputation: 763

X509Certificate2.CreateFromEncryptedPem works on my local but fails on the server using the same certs

X509Certificate2.CreateFromEncryptedPem(clientCertString.AsSpan(), keyString.AsSpan(), keyFilePassword)

I am trying to create a X509Certificate2 from my client cert and a key with a passphrase.

On my local machine, it works, and does not throw any error. However, when the code is deployed to the server, and I call the same function with the same cert, key and passphrase, I get the following error:

System.Security.Cryptography.CryptographicException: The EncryptedPrivateKeyInfo structure was decoded but was not successfully interpreted, the password may be incorrect.
 ---> Internal.Cryptography.CryptoThrowHelper+WindowsCryptographicException: The system cannot find the file specified.
   at System.Security.Cryptography.CngKeyLite.ImportKeyBlob(String blobType, ReadOnlySpan`1 keyBlob, Boolean encrypted, ReadOnlySpan`1 password)
   at System.Security.Cryptography.CngPkcs8.ImportPkcs8(ReadOnlySpan`1 keyBlob)
   at System.Security.Cryptography.CngPkcs8.ImportEncryptedPkcs8PrivateKey(ReadOnlySpan`1 password, ReadOnlySpan`1 source, Int32& bytesRead)
   --- End of inner exception stack trace ---
   at System.Security.Cryptography.CngPkcs8.ImportEncryptedPkcs8PrivateKey(ReadOnlySpan`1 password, ReadOnlySpan`1 source, Int32& bytesRead)
   at System.Security.Cryptography.RSAImplementation.RSACng.ImportEncryptedPkcs8PrivateKey(ReadOnlySpan`1 password, ReadOnlySpan`1 source, Int32& bytesRead)
   at Internal.Cryptography.PemKeyImportHelpers.ImportEncryptedPem[TPass](ReadOnlySpan`1 input, ReadOnlySpan`1 password, ImportEncryptedKeyAction`1 importAction)
   at System.Security.Cryptography.RSA.ImportFromEncryptedPem(ReadOnlySpan`1 input, ReadOnlySpan`1 password)
   at System.Security.Cryptography.X509Certificates.X509Certificate2.ExtractKeyFromEncryptedPem[TAlg](ReadOnlySpan`1 keyPem, ReadOnlySpan`1 password, Func`1 factory, Func`2 import)
   at System.Security.Cryptography.X509Certificates.X509Certificate2.CreateFromEncryptedPem(ReadOnlySpan`1 certPem, ReadOnlySpan`1 keyPem, ReadOnlySpan`1 password)

What causes the difference in behavior?

Edit: Setting the App Pool identity to Local System resolved the issue https://stackoverflow.com/a/74516114/9491881 However, I would like to know why does it resolve the issue?

Upvotes: 0

Views: 72

Answers (0)

Related Questions