Is there any way to make uploaded certificate's private key exportable?

Charles He 1 Reputation point
2021-04-01T15:20:56.46+00:00

In Azure Cloud Service, I want to use below code to get client assertion, but the error at the line "var privateKeyXmlParams = certificate.PrivateKey.ToXmlString(true);" is "Key not valid for use in specified state.
".

X509Store store = new X509Store(StoreLocation.LocalMachine);  
store.Open(OpenFlags.ReadOnly);  
X509Certificate2Collection cers = store.Certificates.Find(X509FindType.FindBySubjectName, certificateName, false);  
if (cers.Count == 0)  
            throw new Exception("No certificate found.");  
  
X509Certificate2 certificate = cers[0];  
  
//Create RSACryptoServiceProvider  
var x509Key = new X509AsymmetricSecurityKey(certificate);  
var privateKeyXmlParams = certificate.PrivateKey.ToXmlString(true);  
var rsa = new RSACryptoServiceProvider();  
rsa.FromXmlString(privateKeyXmlParams);  
  
//alg represents the desired signing algorithm, which is SHA-256 in this case  
//kid represents the certificate thumbprint  
var header = new Dictionary<string, string>()  
{  
    { "alg", "RS256"},  
    { "kid", Encode(certificate.GetCertHash()) }  
};  
  
string token = Encode(Encoding.UTF8.GetBytes(JObject.FromObject(header).ToString())) + "." + Encode(Encoding.UTF8.GetBytes(JObject.FromObject(GetClaims(tenantId, clientId)).ToString()));  
  
string signature = Encode(rsa.SignData(Encoding.UTF8.GetBytes(token), new SHA256Cng()));  
string signedClientAssertion = string.Concat(token, ".", signature);  

I'm wondering if I can config the private key as exportable just as what I can do on my local machine. Can anyone help?

83669-kb-1-57x7kyj-markasexport.png

Azure Cloud Services
Azure Cloud Services
An Azure platform as a service offer that is used to deploy web and cloud applications.
633 questions
0 comments No comments
{count} votes