【问题标题】:c# Sign Xml with X509Certificate2c# 使用 X509Certificate2 签署 Xml
【发布时间】:2016-05-13 00:57:35
【问题描述】:

我尝试签署一个 Xml 文件。这是代码(来自 MSDN):

RSACryptoServiceProvider Key = new RSACryptoServiceProvider();
SignXmlFile(XmlStart, XmlEnd, Key);

如何将 X509Certificate2 作为密钥发送? 坦克! 弗朗切斯科

【问题讨论】:

  • 我相信RSACryptoServiceProvider 太少了,不能拥有X509Certificate2。您能否扩展您的问题并添加有关您如何实际获得加密货币提供商的详细信息,以及您的SignXmlFile 是否有一种方式低于成熟的X509Certificate2

标签: c# sign x509certificate2


【解决方案1】:

在这里,您将使用证书中的密钥(公钥/私钥)。

选项 1)

X509Certificate2 cert = RetrieveCertificate("abcd");
var key = cert.PrivateKey;

private static X509Certificate2 RetrieveCertificateFromStore(string certificateName)
{
    X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine);
    store.Open(OpenFlags.OpenExistingOnly);
    var cert = store.Certificates.OfType<X509Certificate2>().AsEnumerable().FirstOrDefault(c => c.FriendlyName == certificateName);
    return cert;
}

或从文件中检索证书:

    private static X509Certificate2 RetrieveCertificateFromFile(string certPath)
    {
        // string certPath = @"C:\Certificates\myCert.pfx";
        string certPass = "mycertPass";
        // Create a collection object and populate it using the PFX file
        X509Certificate2Collection collection = new X509Certificate2Collection();
        collection.Import(certPath, certPass, X509KeyStorageFlags.PersistKeySet);
        // Instead of foreach you can directly retrieve the certificate from collection as well.
        foreach (X509Certificate2 cert in collection)
        {
            // Import the certificates into X509Store objects
            return cert;
        }
        return null;
    }

选项2)

RSACryptoServiceProvider key = RetrieveKey(cert, EnumKeyType.Private);

【讨论】:

  • 我相信问题是相反的——他有RSACryptoServiceProvider,他想把X509Certificate2 去掉。你展示的是当你第一次拥有X509Certificate2时如何拥有RSACryptoServiceProvider
  • 来自 RSACryptoServiceProvider,我们无法获得证书。我相信,他正在寻找一种从 X509Certificate2 实例中获取密钥的方法。
  • 我知道我们不能,这就是为什么我在他的评论下面问了一个问题。我仍然相信他确实想从密钥中获取证书,但他只是不知道这行不通。另一方面,尽管他的问题很明确,但你假设他想要一些简单且可实现的东西。让我们等待 OP 的任何活动,但如果我没记错的话,你的答案不是他所要求的。
  • 是的,Wiktor,你是对的,我需要使用存储在 pfx 文件中的 X509Certificate2 签署一个 xml 文件,而不是在机器中。在网上只能在 MSDN 上找到 SignXml,但使用 RSACryptoServiceProvider 的示例,但我需要 X509Certificate2 来作为标志。
  • 嗨@Infoservice,请找到更新的答案以从 pfx 文件中检索证书。
猜你喜欢
  • 2014-11-12
  • 1970-01-01
  • 1970-01-01
  • 2016-12-14
  • 1970-01-01
  • 1970-01-01
  • 2018-02-24
  • 2013-01-01
  • 1970-01-01
相关资源
最近更新 更多