繁体   English   中英

在 C# 中使用 BouncyCastle 生成 CMS PKCS#7 文件

[英]Generate a CMS PKCS#7 file with BouncyCastle in C#

我开始密码学。 我需要生成一个带有 XML 的 PKCS #7 文件、一个 RSA 私钥(不包含在证书中的是一个文件扩展名 .key)和一个证书扩展名 .cer。

为此,我正在使用 BouncyCastle。

编辑:

感谢@khlr 的帮助,但我无法解决我的问题。 当向 AC 发送数据时,返回“无效的 CMS”。 我有这个代码:

public static byte[] FirmaBytesMensaje(byte[] argBytesMsg, X509Certificate2 argCertFirmante)
{
    try
    {
        //Add message in object ContentInfo 
        ContentInfo infoContenido = new ContentInfo(argBytesMsg);
        SignedCms cmsFirmado = new SignedCms(infoContenido);


        CmsSigner cmsFirmante = new CmsSigner(argCertFirmante);
        cmsFirmante.IncludeOption = X509IncludeOption.EndCertOnly;


        // Sign message PKCS #7 
        cmsFirmado.ComputeSignature(cmsFirmante);


        // Encodeo el mensaje PKCS #7. 
        return cmsFirmado.Encode();
    }
    catch (Exception excepcionAlFirmar)
    {
        throw new Exception("***Error: " + excepcionAlFirmar.Message);
    }
}

在 PKCS # 7 上签名,但这会使用“PFX”证书,即在“.pfx”文件中包含私钥。 当我使用 OpenSSL 命令时:

openssl smime -sign -signer cert.crt -inkey private.key -out file.xml.cms -in file.xml -outform PEM -nodetach

AC 反应良好。 我如何使用 BouncyCastle 和 cer 以及密钥文件来做到这一点? 我快疯了! :-(

不幸的是,似乎没有 C# 的 bouncycastle API 文档 无论如何,有一个Java 参考,据说它与 C# API 非常相似。

因此, getEncoded() - 方法(寻找 C# 等价物,例如GetEncoded() )产生 ASN.1 编码的byte[]

然后你可以继续并从中获取一个字符串(请注意,我不熟悉 ASN.1 编码。这只是一个猜测😉):

byte[] buffer = datosFirmados.GetEncoded();
string signedDataString = System.Text.Encoding.UTF8.GetString(buffer, 0, buffer.Length);

编辑:

也许AsnEncodedData更适合该任务:

byte[] buffer = datosFirmados.GetEncoded();
var asndata = new AsnEncodedData(buffer);
const bool multiline = true;
string signedDataString = asndata.Format(multiline);

已经过了很长时间,但仍然没有答案。 您需要将证书和密钥文件合并在一起,如下所示。

            using (System.Security.Cryptography.X509Certificates.X509Certificate2 _pub = this.PublicKey.X509Certificate2)
            {
                using (X509Certificate2 _pri = _pub.CopyWithPrivateKey(_rsa))
                {
                    var _infoContenido          = new System.Security.Cryptography.Pkcs.ContentInfo(Message);
                    SignedCms _signedCms        = new SignedCms(_infoContenido);

                    CmsSigner _cmsSigner        = new CmsSigner(_pri);
                    if (IncludeSignDate)
                    {
                        _cmsSigner.SignedAttributes.Add(new Pkcs9SigningTime(DateTime.Now));    // [2020-05-02] 서명한 날짜 속성 추가
                    }
                    _cmsSigner.IncludeOption    = X509IncludeOption.EndCertOnly;

                    // Sign message PKCS #7
                    _signedCms.ComputeSignature(_cmsSigner);
                    var _signedMessage          = _signedCms.Encode();
                }
            }

暂无
暂无

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

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