简体   繁体   English

如何以编程方式在本地计算机密钥库中导入私钥?

[英]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. 所有尝试获取NetworkService令牌的尝试都失败了。 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. 上面的代码将私钥导入到本地计算机的当前用户instat中。 What should I do? 我该怎么办?

The MSDN has a solution . MSDN有一个解决方案 Simply add a flag X509KeyStorageFlags.MachineKeySet and it runs fine: 只需添加一个标志X509KeyStorageFlags.MachineKeySet ,它就可以正常运行:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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