0 votes
by (140 points)

related to an answer for: Private Key from PFX File

1 Answer

0 votes
by (150k points)

    public static void SavePrivateKey(RSAParameters privateKey, string keyContainerName)
    {
        var parameters = GetCspParameters(keyContainerName);
        parameters.Flags = CspProviderFlags.NoFlags;

        var rsa = new RSACryptoServiceProvider(parameters);
        rsa.PersistKeyInCsp = true;
        rsa.ImportParameters(privateKey);
        rsa.Clear();
    }

    public static RSAParameters GetPrivateKey(string keyContainerName)
    {
        var parameters = GetCspParameters(keyContainerName);
        parameters.Flags = CspProviderFlags.UseExistingKey;

        var rsa = new RSACryptoServiceProvider(parameters);
        var privateKey = rsa.ExportParameters(true);
        rsa.Clear();
        return privateKey;
    }

    private static CspParameters GetCspParameters(string keyContainerName)
    {
        var rsa = new RSACryptoServiceProvider();
        string providerName = rsa.CspKeyContainerInfo.ProviderName;
        int providerType = rsa.CspKeyContainerInfo.ProviderType;
        rsa.Clear();

        var parameters = new CspParameters(providerType, providerName, keyContainerName);
        parameters.KeyNumber = (int)KeyNumber.Exchange;
        return parameters;
    }
by (140 points)
Hi.

Here's what I'm trying to achieve:

- Generate Pair of Keys - RSA 512bit - OK
- Generate Certificate (.cer file) with Public Key - OK
- Generate PFX File (.pfx file) with Private Key - OK (I also generated in PEM format)
- Store Certificate into Certificate Storage: Keeping into StoreName.My / StoreLocation.CurrentUser - OK
- Store PFX file or Private Key into Key Storage (I know that Certificates and Private Keys are not stored in same location, but I was trying to save PFX file using X509 Store.

What would you recommend to store private key? I do not want to keep this as a file in SD Card (for instance).
by (150k points)
Windows key storage is actually a suitable place for storing private keys and offers several security features (such as exportable/non-exportable keys, displaying a dialog when using a key). If the RSACryptoServiceProvider-based code above works, I would give that a try.
by (140 points)
Hi. Thanks for your support. I managed to implement everything we need with your information.
...