Jakub Čermoch
Jakub Čermoch

Reputation: 471

Using certificate from store for RSACryptoServiceProvider

I have problem with certificate from store. In my app, user can use certificate from file or certificate from store. After loading certificate I use certificate for sign data.

Using certificate from file is OK, but i cant use equivalent from store.

Code for sign:

// Sign data
using (RSACryptoServiceProvider csp = new RSACryptoServiceProvider())
{
    byte[] dataToSign = Encoding.UTF8.GetBytes(plainText);
    csp.ImportParameters(((RSACryptoServiceProvider)_certPopl.PrivateKey).ExportParameters(true));
    byte[] signature = csp.SignData(dataToSign, "SHA256");
    // Verify signature
    if (!csp.VerifyData(dataToSign, "SHA256", signature))
        throw new Exception("Nepodařilo se vytvořit platný podpisový kód poplatníka.");
    PKP = Convert.ToBase64String(signature);
}

Code for read certificate from file:

X509Certificate2Collection certStore = new X509Certificate2Collection();
certStore.Import(fileName, password, X509KeyStorageFlags.Exportable);
foreach (X509Certificate2 cert in certStore)
{
    // Find the first certificate with a private key
    if (cert.HasPrivateKey)
    {
        _certPopl = cert;
        break;
    }
}

Code for read certificate from store. After load certificate from store, I am unable to sign data:

public void LoadCertificate(string certificateName, DateTime notAfter, string password)
{
    var store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
    store.Open(OpenFlags.MaxAllowed);
    foreach (var certificate in store.Certificates)
    {
        if (certificate.FriendlyName.Equals(certificateName) && certificate.NotAfter.Equals(notAfter))
        {
            //X509Certificate2Collection certStore = new X509Certificate2Collection();
            //certStore.Import(certificate.Export(X509ContentType.SerializedCert), password, X509KeyStorageFlags.Exportable);
            //_certPopl = certStore[0];

            X509Certificate2Collection certStore = new X509Certificate2Collection();
            certStore.Import(certificate.GetRawCertData());
            foreach (X509Certificate2 cert in certStore)
            {
                // Find the first certificate with a private key
                if (cert.HasPrivateKey)
                {
                    _certPopl = cert;
                    break;
                }
            }

            break;
        }
    }
}

I havent experience with working with certificates. But I need equivalent of obtain certificate from store for signing.

System.Security.Cryptography.CryptographicException is thrown on ExportParameters(true). Additional information of Exception: Key not valid for use in specified state.

Thanks.

Upvotes: 1

Views: 4659

Answers (3)

bartonjs
bartonjs

Reputation: 33148

If you can use .NET 4.6 this is much simpler, the new way of accessing private keys works far more reliably for SHA-2 signatures:

using (RSA rsa = cert.GetRSAPrivateKey())
{
    if (rsa == null)
    {
        throw new Exception("Wasn't an RSA key, or no private key was present");
    }

    bool isValid = rsa.VerifyData(
        Encoding.UTF8.GetBytes(plainText),
        signature,
        HashAlgorithmName.SHA256,
        RSASignaturePadding.Pkcs1);

    if (!isValid)
    {
        throw new Exception("VerifyData failed");
    }
}

Upvotes: 3

Jakub Čermoch
Jakub Čermoch

Reputation: 471

Working state is:

Loading certificate from store:

var store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
try
{
    store.Open(OpenFlags.ReadOnly);
    foreach (var certificate in store.Certificates)
    {
        if (certificate.FriendlyName.Equals(certificateName) && certificate.NotAfter.Equals(notAfter))
        {
            _certPopl = certificate;
            break;
        }
    }
}
finally
{
    store.Close();
}

Sign and verify data:

byte[] dataToSign = Encoding.UTF8.GetBytes(plainText);
var privKey = (RSACryptoServiceProvider)_certPopl.PrivateKey;
// Force use of the Enhanced RSA and AES Cryptographic Provider with openssl-generated SHA256 keys
var enhCsp = new RSACryptoServiceProvider().CspKeyContainerInfo;
var cspparams = new CspParameters(enhCsp.ProviderType, enhCsp.ProviderName, privKey.CspKeyContainerInfo.KeyContainerName);
privKey = new RSACryptoServiceProvider(cspparams);
byte[] signature = privKey.SignData(dataToSign, "SHA256");
// Verify signature
if (!privKey.VerifyData(dataToSign, "SHA256", signature))
    throw new Exception("Nepodařilo se vytvořit platný podpisový kód poplatníka.");

Upvotes: 0

Crypt32
Crypt32

Reputation: 13974

I don't clearly understand why you are trying to export CSP parameters. CSP parameters export depends on key export options and will fail if the key is non-exportable. Instead, you should use RSACryptoServiceProvider directly on PrivateKey property of the X509Certificate2 object:

// assuming, you have X509Certificate2 object with existing private key in _certPol variable
// retrieve private key
var key = _certPol.PrivateKey as RSACryptoServiceProvider;
// check if it is legacy RSA, otherwise return.
if (key == null) { return; }
byte[] dataToSign = Encoding.UTF8.GetBytes(plainText);
// sign data
byte[] signature = key.SignData(dataToSign, "SHA256");
// Verify signature
if (!key.VerifyData(dataToSign, "SHA256", signature))
    throw new Exception("Nepodařilo se vytvořit platný podpisový kód poplatníka.");
...

Upvotes: 0

Related Questions