使用X509Certificate2和私钥对文件进行签名

时间:2016-03-09 17:47:35

标签: c# x509certificate2

我想签署一个带证书的文件。我写了下面的代码但是我得到了“文件内容错误”,而且我总是问私钥。 我做错了什么?我该如何发送私钥? 谢谢大家。

        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();

1 个答案:

答案 0 :(得分:2)

你可以在没有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();
    }