How to change CSP parameter of RSACryptoServiceProvider

2.9k views Asked by At

I am doing rsa-sha256 xml signing using SignedXML class. But the problem is I need to change CSP to support sha256.

This is how I am selecting certificate,

public X509Certificate2 GetCertificateFromStore()
        {
            X509Store st = new X509Store(StoreName.My, StoreLocation.CurrentUser);
            st.Open(OpenFlags.ReadOnly);
            X509Certificate2Collection col = st.Certificates.Find(X509FindType.FindByTimeValid, (object)DateTime.Now, false);

            X509Certificate2 x509Certificate =null;
            X509Certificate2Collection sel = X509Certificate2UI.SelectFromCollection(col, "Certificate", "Select single certificate to sign", X509SelectionFlag.SingleSelection);
            if (sel.Count > 0)
            {
                X509Certificate2Enumerator en = sel.GetEnumerator();
                en.MoveNext();
                x509Certificate = en.Current;
            }
            st.Close();
            //x509Certificate.s
            return x509Certificate;
        }

This is how I am trying to change CSP parameter.

byte[] privateKeyBlob;
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
            rsa = cert.PrivateKey as RSACryptoServiceProvider;
            try
            {
                privateKeyBlob = rsa.ExportCspBlob(true);
            }
            catch
            {
                throw new ApplicationException("Private key fails to export");
            }
            // To use the RSA-SHA256 the CryptoAPI needs to select a special CSP: Microsoft Enhanced RSA and AES Cryptographic Provider
            // By reinstantiating a CSP of type 24 we ensure that we get the right CSP.
            CspParameters cp = new CspParameters(24);
            rsa = new RSACryptoServiceProvider(cp);
            rsa.ImportCspBlob(privateKeyBlob);


            signer.SigningKey = rsa;
            signer.KeyInfo = getKeyInfo(signer, cert);

Problem is I am using USB device token and I doubt private key is not exportable. On exporting its throwing an error 'Key not valid for use in specified state.'.

Can anybody help how to do this?

1

There are 1 answers

0
Matt On BEST ANSWER

If any one interested here is my solution, I ended up using another new version of my 3rd party CSP. The CSP version I was using was an old one and I switched to new version. Now the signing is working. Thanks for your help.