【问题标题】:Sign a file with a X509Certificate2 and private key使用 X509Certificate2 和私钥签署文件
【发布时间】:2016-04-06 16:49:27
【问题描述】:

我想用证书签署一个文件。我编写了以下代码,但出现“文件内容错误”,而且我总是询问私钥。 我做错了什么?如何发送私钥? 谢谢大家。

        string cSerial = "0C4744041F40B761322124EB691C5F32";
        //Find my certificate with serial    
        X509Store my = new X509Store(StoreName.My, StoreLocation.CurrentUser);

        my.Open(OpenFlags.ReadOnly);

        System.Security.Cryptography.RSACryptoServiceProvider csp = null;

        foreach (X509Certificate2 cert in my.Certificates)
        {
            if (cert.SerialNumber.Trim() == cSerial)
            { csp = (System.Security.Cryptography.RSACryptoServiceProvider)cert.PrivateKey; }
        }
        //Here i have the certificate, it's ok.
        System.Security.Cryptography.SHA1Managed sha1 = new System.Security.Cryptography.SHA1Managed();
        UnicodeEncoding encoding = new UnicodeEncoding();
        //////////byte[] data = encoding.GetBytes("test.xml");
        byte[] data = File.ReadAllBytes("test.xml")
        byte[] hash = sha1.ComputeHash(data);
        byte[] aa = csp.SignHash(hash, System.Security.Cryptography.CryptoConfig.MapNameToOID("SHA1"));
        File.WriteAllBytes("text.p7m", aa);

        my.Close();

【问题讨论】:

  • UnicodeEncoding.GetBytes 不读取文件。它只是将字符串“text.xml”中的字节编码为字节数组。
  • @Kevin,我编辑了我的源,但结果没有改变......谢谢。
  • 使用调试器找出是哪一行产生了错误。
  • 我用 BouncyCastle 解决了这个问题。

标签: c# x509certificate2


【解决方案1】:

您可以在没有 Bouncy Castle 的情况下解决这个问题,只需使用 .NET

    /// <summary>
    ///     Make attached signature.
    /// </summary>
    public byte[] SignAttached(X509Certificate2 certificate, byte[] dataToSign)
    {
        ContentInfo contentInfo = new ContentInfo(dataToSign);
        SignedCms cms = new SignedCms(contentInfo, false);
        CmsSigner signer = new CmsSigner(certificate);
        cms.ComputeSignature(signer, false);
        return cms.Encode();
    }

    /// <summary>
    ///     Make detached signature.
    /// </summary>
    public byte[] SignDetached(X509Certificate2 certificate, byte[] dataToSign)
    {
        ContentInfo contentInfo = new ContentInfo(dataToSign);
        SignedCms cms = new SignedCms(contentInfo, true);
        CmsSigner signer = new CmsSigner(certificate);
        cms.ComputeSignature(signer, false);
        return cms.Encode();
    }

【讨论】:

  • 附加和分离场景下如何验证签名?
猜你喜欢
  • 2018-09-03
  • 2017-09-20
  • 1970-01-01
  • 2015-08-26
  • 1970-01-01
  • 1970-01-01
  • 2014-12-17
  • 2013-05-30
  • 1970-01-01
相关资源
最近更新 更多