I’m trying to sign my JWT with a certificate saved as Base64 in my database, protected by a password.
My code works fine on my Windows Server 2012, but when I moved it to Windows Server 2022, it throws an exception: Invalid provider type specified.
My code .NET 4.7.2:
//Load certificate
var certificate = new X509Certificate2(certificateBytes, password, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable);
//Make header, add signing certificate
var header = new JwtHeader(new X509SigningCredentials(certificate));
header.Add(JwtHeaderParameterNames.X5c, new string[] { Convert.ToBase64String(certificate.RawData) });
//Make payload
var payload = new JwtPayload(issuer, audience, claimes, notBefore: null, expires);
//Make token and sign
var token = new JwtSecurityToken(header, payload);
//Serialize
var tokenHandler = new JwtSecurityTokenHandler();
return tokenHandler.WriteToken(token);
The exception: Invalid provider type specified.
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 System.Security.Cryptography.X509Certificates.X509Certificate2.get_PrivateKey()
at System.Security.Cryptography.X509Certificates.RSACertificateExtensions.GetRSAPrivateKey(X509Certificate2 certificate)
at Microsoft.IdentityModel.Tokens.X509SecurityKey.get_PrivateKey() at Microsoft.IdentityModel.Tokens.X509SecurityKey.get_PrivateKeyStatus()
at Microsoft.IdentityModel.Tokens.AsymmetricSignatureProvider..ctor(SecurityKey key, String algorithm, Boolean willCreateSignatures)
at Microsoft.IdentityModel.Tokens.CryptoProviderFactory.CreateSignatureProvider(SecurityKey key, String algorithm, Boolean willCreateSignatures, Boolean cacheProvider)
at Microsoft.IdentityModel.Tokens.CryptoProviderFactory.CreateForSigning(SecurityKey key, String algorithm, Boolean cacheProvider)
at Microsoft.IdentityModel.JsonWebTokens.JwtTokenUtilities.CreateEncodedSignature(String input, SigningCredentials signingCredentials)
at System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler.WriteToken(SecurityToken token)
and my certificate :MAC: sha1, Iteration 1024
MAC length: 20, salt length: 20
PKCS7 Data
Shrouded Keybag: pbeWithSHA1And3-KeyTripleDES-CBC, Iteration 1024