Search code examples
c#windowscertificateprivate-key

How can we store and retrieve a certificate containing private key in a windows store + C#


In my Windows application I will get a certificate containing private key. The public key is with me. I want to securely store this certificate in Windows secure folder and could be able to access this whenever required. Please help me to do this. Any sample program.


Solution

  • I got a solution for how can we store certificate with private key.

    byte[] byteKey = DecodePrivateKey(Convert.FromBase64String(cryptoCertificateKey));
    RSAParameters rsaParam = DecodeRSAPrivateKeyToRSAParam(byteKey);
                        var cspParams = new CspParameters
                        {
                            ProviderType = 1,
                            Flags = CspProviderFlags.UseUserProtectedKey | CspProviderFlags.NoPrompt};
     using (X509Store store = new X509Store(StoreName.Root, StoreLocation.LocalMachine))
    {
    store.Open(OpenFlags.ReadWrite); 
    using (RSACryptoServiceProvider rsaProvider = new RSACryptoServiceProvider(cspParams))
                        {
                            rsaProvider.ImportParameters(rsaParam);
                            rsaProvider.PersistKeyInCsp = true;
    X509Certificate2 x509Certificate = new X509Certificate2(cryptoCertificate, "123",
                                X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable |
                                X509KeyStorageFlags.PersistKeySet);
    store.Add(x509Certificate);
    }}
    

    But I didn't get a solution that how to secure the privatekey with password