我开始加密了。 我需要使用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和密钥文件来做到这一点?我快疯了! : - (
答案 0 :(得分:0)
不幸的是,似乎有no bouncycastle API documentation for C#。从来没有一个Java reference被认为与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
-class更适合该任务:
byte[] buffer = datosFirmados.GetEncoded();
var asndata = new AsnEncodedData(buffer);
const bool multiline = true;
string signedDataString = asndata.Format(multiline);
答案 1 :(得分:0)
已经很长时间了,但是仍然没有答案。 您将需要将证书和密钥文件合并在一起,如下所示。
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();
}
}