CMS签名X509证书与Bouncy城堡
本文关键字:Bouncy 城堡 证书 签名 X509 CMS | 更新日期: 2023-09-27 17:53:22
我需要把这个。net代码翻译成BouncyCastle代码,因为我需要在mono中使用
X509Certificate2 certFirmante = LoadCertFromFile("sign.p12");
ContentInfo infoContenido = new ContentInfo(argBytesMsg);
SignedCms cmsFirmado = new SignedCms(infoContenido);
CmsSigner cmsFirmante = new CmsSigner(argCertFirmante);
cmsFirmante.IncludeOption = X509IncludeOption.EndCertOnly;
cmsFirmado.ComputeSignature(cmsFirmante, true);
return cmsFirmado.Encode();
我尝试用这段代码,但签名的数据是不一样的
CmsSignedDataGenerator gen = new CmsSignedDataGenerator();
CmsEnvelopedDataStreamGenerator dataGenerator = new CmsEnvelopedDataStreamGenerator();
dataGenerator.AddKeyTransRecipient(cert);
// Make the output stream
MemoryStream outStream = new MemoryStream();
// Sign the stream
Stream cryptoStream = dataGenerator.Open(outStream, CmsEnvelopedGenerator.Aes128Cbc);
BinaryWriter binWriter = new BinaryWriter(cryptoStream);
binWriter.Write(datos);
byte[] contenido = new byte[outStream.Length];
outStream.Read(contenido, 0, Convert.ToInt32(outStream.Length));
return contenido;
您想要的内容可能更像这样:
byte[] Sign (byte[] argBytesMsg)
{
var signedData = new CmsSignedDataStreamGenerator ();
var x509certificate2 = LoadCertFromFile ("sign.p12");
var cert = DotNetUtilities.FromX509Certificate (x509certificate2);
var key = DotNetUtilities.GetKeyPair (x509certificate2.PrivateKey);
signedData.AddSigner (key.PrivateKey, cert, X509ObjectIdentifiers.IdSha1.Id, null, null);
signedData.AddCertificate (cert);
using (var memory = new MemoryStream ()) {
using (var stream = signedData.Open (memory, true))
stream.Write (argBytesMsg, 0, argBytesMsg.Length);
return memory.ToArray ();
}
}
顺便说一下,你有没有考虑过使用MimeKit而不是自己尝试这样做?
MimeKit使用BouncyCastle,所以是跨平台的,是完全开源的。