SnInstallPfx icon indicating copy to clipboard operation
SnInstallPfx copied to clipboard

CryptographicException thrown during RSACryptoServiceProvider ctor when container already created by another user

Open dannarsavage opened this issue 1 year ago • 0 comments

Running SnInstallPfx for a particular certificate in Jenkins yielded an exception with the following stack trace:

Unhandled Exception: System.Security.Cryptography.CryptographicException: Object already exists.

    at System.Security.Cryptography.CryptographicException.ThrowCryptographicException(Int32 hr)
    at System.Security.Cryptography.Utils._CreateCSP(CspParameters param, Boolean randomKeyContainer, SafeProvHandle& hProv)
    at System.Security.Cryptography.Utils.CreateProvHandle(CspParameters parameters, Boolean randomKeyContainer)
    at System.Security.Cryptography.Utils.GetKeyPairHelper(CspAlgorithmType keyType, CspParameters parameters, Boolean randomKeyContainer, Int32 dwKeySize, SafeProvHandle& safeProvHandle, SafeKeyHandle& safeKeyHandle)
    at System.Security.Cryptography.RSACryptoServiceProvider.GetKeyPair()
    at System.Security.Cryptography.RSACryptoServiceProvider..ctor(Int32 dwKeySize, CspParameters parameters, Boolean useDefaultKeySize)
    at SnInstallPfx.SnInstallPfx.Main(String[] args)

After some digging, I realized that before finding & trying SnInstallPfx.exe, I'd logged into the server and created that container myself (which of course didn't help Jenkins, running under a different account). Logging back into the server and deleting my copy of the container solved the issue for me.

FYI, I'll ship you a PR regarding this very soon that simply catches the CryptographicException and provides a useful error message. There's likely something more elegant & useful to be done inside ResolveKeySourceTask.IsContainerInstalled. I'm not comfortable enough with keys & containers to attempt that myself, but I thought a minimal PR would be a better "thank you" for providing this tool than no PR at all.

dannarsavage avatar Dec 15 '22 17:12 dannarsavage