简体   繁体   中英

How to import programmally a private key in the local machine keystore?

How to import programmally a private key in the local machine keystore?

Actually I'm testing this code:

    private static void InstallCertificate(string certificatePath, string certificatePassword, StoreName store) {
        try {
            var serviceRuntimeUserCertificateStore = new X509Store(store, StoreLocation.LocalMachine);
            serviceRuntimeUserCertificateStore.Open(OpenFlags.ReadWrite);

            X509Certificate2 cert;

            try {
                cert = new X509Certificate2(certificatePath, certificatePassword);
            } catch(Exception ex) {
                Console.WriteLine("Failed to load certificate " + certificatePath);
                throw new DataException("Certificate appeared to load successfully but also seems to be null.", ex);
            }

            serviceRuntimeUserCertificateStore.Add(cert);
            serviceRuntimeUserCertificateStore.Close();
        } catch(Exception) {
            Console.WriteLine("Failed to install {0}.  Check the certificate index entry and verify the certificate file exists.", certificatePath);
        }
    }

All tries to get the NetworkService token failed yet. The code here doesn't work with admin privileges.

The code above imports the private key to the currient user instat of the local machine. What should I do?

The MSDN has a solution . Simply add a flag X509KeyStorageFlags.MachineKeySet and it runs fine:

cert = new X509Certificate2(certificatePath,
                            certificatePassword,
                            X509KeyStorageFlags.MachineKeySet);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM