gpt4 book ai didi

c# - 使用 C# 将证书从 LocalComputer 复制到 CurrentUser

转载 作者:可可西里 更新时间:2023-11-01 10:32:02 26 4
gpt4 key购买 nike

如标题所述,我需要以编程方式将证书(给定指纹)从 LocalComputer 存储复制到 CurrentUser 存储。我一直在研究 X509Certificate2 定义并尝试一些东西,但似乎没有任何效果。这是我目前所拥有的

certPath = "@"C:\%temp%\Cert.pfx";
certPass = "CertPassHere";

X509Store localMachineStore = new X509Store(StoreName.My, StoreLocation.LocalMachine);
localMachineStore.Open(OpenFlags.ReadOnly);

X509Certificate2Collection certificate = localMachineStore.Certificates.Find(X509FindType.FindByThumbprint, "certThumbprint", true);
byte[] rawCertData = certificate[0].Export(X509ContentType.Pfx, certPass);
File.WriteAllBytes(certPath, rawCertData);
localMachineStore.Close();

X509Certificate2Collection collection = new X509Certificate2Collection();
collection.Import(certPath, certPass, X509KeyStorageFlags.PersistKeySet);
X509Store currentUserStore = new X509Store(StoreName.My, StoreLocation.CurrentUser);

foreach (X509Certificate2 cert in collection)
{
Console.WriteLine("Subject is: '{0}'", cert.Subject);
Console.WriteLine("Issuer is: '{0}'", cert.Issuer);
currentUserStore.Add(cert);
}

currentUserStore.Close();
File.Delete(certPath);

我觉得我在这里有点走在正确的轨道上,但非常感谢任何帮助:)

最佳答案

  • 不需要将其保存到文件中,因为您可以直接从 byte[] 加载 PFX。
  • 您似乎没有调用 currentUserStore.Open(OpenFlags.ReadWrite),代码是完成了还是抛出了 CryptographicException?
  • 您需要使用 X509KeyStorageFlags.UserKeySet 导入 PFX,因为私钥会“记住”它是从机器 keystore 中导出的,并且它想回到那里。
  • true 作为第三个参数传递给 X509Certificate2Collection.Find 通常不是您想要的,它主要只在按主题搜索时方便,忽略过期的东西。<

.

string thumbprint = IAssumeYouHaveThisForReal();

X509Certificate2Collection certificates = localMachineStore.Certificates.Find(
X509FindType.FindByThumbprint,
thumbprint,
false);

byte[] tempPfx = certificates[0].Export(X509ContentType.Pfx, "hi");

X509Certificate2 copyWithUserKey = new X509Certificate2(
tempPfx,
"hi",
X509KeyStorageFlags.UserKeySet /*| X509KeyStorageFlags.Exportable if you like */);

X509Store currentUserMy = new X509Store(StoreName.My, StoreLocation.CurrentUser);
currentUserMy.Open(OpenFlags.ReadWrite);
currentUserStore.Add(copyWithUserKey);

certificates = currentUserStore.Certificates.Find(
X509FindType.FindByThumbprint,
thumbprint,
false);

if (certificates.Count != 1)
throw new InvalidOperationException();

关于c# - 使用 C# 将证书从 LocalComputer 复制到 CurrentUser,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51094271/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com