本文整理汇总了C#中System.Security.Cryptography.Pkcs.SignedCms.ComputeSignature方法的典型用法代码示例。如果您正苦于以下问题:C# SignedCms.ComputeSignature方法的具体用法?C# SignedCms.ComputeSignature怎么用?C# SignedCms.ComputeSignature使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Security.Cryptography.Pkcs.SignedCms
的用法示例。
在下文中一共展示了SignedCms.ComputeSignature方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: FirmarMensaje
/// <summary>
/// Firma el mensaje PKCS #7 con el certificado del firmante
/// </summary>
/// <param name="pMensaje">Mensaje (como cadena de bytes)</param>
/// <param name="pCertificadoFirmante">Certificado usado para firmar</param>
/// <returns>Mensaje Firmado (como cadena de bytes)</returns>
/// <remarks></remarks>
public static byte[] FirmarMensaje(byte[] pMensaje, X509Certificate2 pCertificadoFirmante)
{
byte[] msjFirmado;
try
{
// Se pone el Mensaje recibido en un objeto ContentInfo
ContentInfo infoContenidoMsj = new ContentInfo(pMensaje);
// Se instancia el CMS Firmado con el ContentInfo
SignedCms cmsFirmado = new SignedCms(infoContenidoMsj);
// Se instancia el objeto CmsSigner con las caracteristicas del firmante
CmsSigner cmsFirmante = new CmsSigner(pCertificadoFirmante);
cmsFirmante.IncludeOption = X509IncludeOption.EndCertOnly;
// Se firma el mensaje PKCS #7 con el certificado
cmsFirmado.ComputeSignature(cmsFirmante);
msjFirmado = cmsFirmado.Encode();
// Retorno el mensaje PKCS #7 firmado .
return msjFirmado;
}
catch (Exception excepcionAlFirmar)
{
throw new Exception("ERROR: Procedimiento: FirmarMensaje. Al intentar firmar el mensaje con el certificado del firmante: " + excepcionAlFirmar.Message);
}
}
示例2: FirmaBytesMensaje
/// <summary>
/// Firma mensaje
/// </summary>
/// <param name="argBytesMsg">Bytes del mensaje</param>
/// <param name="argCertFirmante">Certificado usado para firmar</param>
/// <returns>Bytes del mensaje firmado</returns>
/// <remarks></remarks>
public static byte[] FirmaBytesMensaje(byte[] argBytesMsg, X509Certificate2 argCertFirmante)
{
try
{
// Pongo el mensaje en un objeto ContentInfo (requerido para construir el obj SignedCms)
ContentInfo infoContenido = new ContentInfo(argBytesMsg);
SignedCms cmsFirmado = new SignedCms(infoContenido);
// Creo objeto CmsSigner que tiene las caracteristicas del firmante
CmsSigner cmsFirmante = new CmsSigner(argCertFirmante);
cmsFirmante.IncludeOption = X509IncludeOption.EndCertOnly;
if (VerboseMode)
{
Console.WriteLine("***Firmando bytes del mensaje...");
}
// Firmo el mensaje PKCS #7
cmsFirmado.ComputeSignature(cmsFirmante);
if (VerboseMode)
{
Console.WriteLine("***OK mensaje firmado");
}
// Encodeo el mensaje PKCS #7.
return cmsFirmado.Encode();
}
catch (Exception excepcionAlFirmar)
{
throw new Exception("***Error al firmar: " + excepcionAlFirmar.Message);
}
}
示例3: Sign
public byte[] Sign(byte[] data)
{
ContentInfo contentInfo = new ContentInfo(_md5.ComputeHash(data));
SignedCms signedCms = new SignedCms(contentInfo);
CmsSigner cmsSigner = new CmsSigner(_cert);
cmsSigner.IncludeOption = X509IncludeOption.WholeChain;
signedCms.ComputeSignature(cmsSigner);
return signedCms.Encode();
}
示例4: FirmaBytesMensaje
private byte[] FirmaBytesMensaje( byte[] argBytesMsg, X509Certificate2 argCertFirmante )
{
ContentInfo infoContenido = new ContentInfo( argBytesMsg );
SignedCms cmsFirmado = new SignedCms( infoContenido );
CmsSigner cmsFirmante = new CmsSigner( argCertFirmante );
try
{
cmsFirmante.IncludeOption = X509IncludeOption.EndCertOnly;
cmsFirmado.ComputeSignature( cmsFirmante );
}
catch ( Exception error )
{
this.manejadorErrores.ManejarError( error, "FirmaBytesMensaje", error.Message );
}
return cmsFirmado.Encode();
}
示例5: GenerateHtmlMessage
private MailMessage GenerateHtmlMessage(string from, string to, string subject, string content, string[] attachmentFilepaths)
{
MailMessage mail = new MailMessage();
mail.From = new MailAddress(from);
mail.To.Add(to);
mail.Subject = subject;
string body = null;
if (attachmentFilepaths != null && attachmentFilepaths.Length > 0)
{
StringBuilder sb = new StringBuilder();
sb.Append("MIME-Version: 1.0\r\n");
sb.Append("Content-Type: multipart/mixed; boundary=unique-boundary-1\r\n");
sb.Append("\r\n");
sb.Append("This is a multi-part message in MIME format.\r\n");
sb.Append("--unique-boundary-1\r\n");
sb.Append("Content-Type: text/html\r\n"); //could use text/plain as well here if you want a plaintext message
sb.Append("Content-Transfer-Encoding: 7Bit\r\n\r\n");
sb.Append(content);
if (!content.EndsWith("\r\n"))
sb.Append("\r\n");
sb.Append("\r\n\r\n");
foreach (string filepath in attachmentFilepaths)
{
sb.Append(GenerateRawAttachement(filepath));
}
body = sb.ToString();
}
else
{
body = "Content-Type: text/html\r\nContent-Transfer-Encoding: 7Bit\r\n\r\n" + content;
}
//input your certification and private key.
X509Certificate2 cert = new X509Certificate2("emailcertification.pfx", "6522626", X509KeyStorageFlags.Exportable | X509KeyStorageFlags.PersistKeySet);
ContentInfo contentInfo = new ContentInfo(Encoding.UTF8.GetBytes(body));
SignedCms signedCms = new SignedCms(contentInfo, false);
CmsSigner Signer = new CmsSigner(SubjectIdentifierType.IssuerAndSerialNumber, cert);
signedCms.ComputeSignature(Signer);
byte[] signedBytes = signedCms.Encode();
MemoryStream stream = new MemoryStream(signedBytes);
AlternateView view = new AlternateView(stream, "application/pkcs7-mime; smime-type=signed-data;name=smime.p7m");
mail.AlternateViews.Add(view);
return mail;
}
示例6: Sign
public static SignatureResponse Sign(byte[] data)
{
// TODO:
// padding configuration
// algorithm configuration
// encoding configuration
/*
SHA1Managed sha1 = new SHA1Managed();
byte[] hash = sha1.ComputeHash(data);
var sig = csp.SignHash(hash, CryptoConfig.MapNameToOID("SHA1"));
//sig = csp.SignData(Encoding.UTF8.GetBytes(text), CryptoConfig.MapNameToOID("SHA1"));
MessageBox.Show("SignData");
*/
var content = new ContentInfo(data);
var cms = new SignedCms(content, true); // TODO detached config
var signer = new CmsSigner();
signer.IncludeOption = X509IncludeOption.EndCertOnly;
cms.ComputeSignature(signer, false);
var sig = cms.Encode();
//ensure my signature is correct before continuing.
cms.CheckSignature(true);
var newCMS = new SignedCms(content, false);
newCMS.Decode(sig);
newCMS.CheckSignature(true);
var cert = cms.Certificates[0];
CheckSig(sig, data);
return new SignatureResponse
{
publicKey = Convert.ToBase64String(cert.PublicKey.EncodedKeyValue.RawData),
signature = Convert.ToBase64String(sig),
fullSig = null // TODO
};
}
示例7: SignFile
public static byte[] SignFile(X509Certificate2 cert, byte[] data)
{
try
{
ContentInfo content = new ContentInfo(data);
SignedCms signedCms = new SignedCms(content, false);
if (VerifySign(data))
{
signedCms.Decode(data);
}
CmsSigner signer = new CmsSigner(cert);
signer.IncludeOption = X509IncludeOption.WholeChain;
signedCms.ComputeSignature(signer);
return signedCms.Encode();
}
catch (Exception ex)
{
throw new Exception("Erro ao assinar arquivo. A mensagem retornada foi: " + ex.Message);
}
}
示例8: ComputeEmptySignature
public void ComputeEmptySignature ()
{
SignedCms sp = new SignedCms ();
sp.ComputeSignature ();
}
示例9: SmimeEnvelopeAndSignBy
/// <summary>
/// Signs the message and envelopes it.
/// </summary>
/// <param name="signer">An object containing the signer's information.</param>
/// <example>
/// <code>
/// [C#]
///
/// CmsSigner signer = new CmsSigner(new X509Certificate2("C:\\mycertificate.pfx"));
///
/// // Here we only want the signer's certificate to be sent along. Not the whole chain.
/// signer.IncludeOption = X509IncludeOption.EndCertOnly;
///
/// message.SmimeEnvelopeAndSignBy(signer);
/// </code>
/// </example>
public void SmimeEnvelopeAndSignBy(CmsSigner signer)
{
string mimeString = this.ToMimeString();
byte[] tosign = Encoding.ASCII.GetBytes(mimeString);
SignedCms cms = new SignedCms(new ContentInfo(tosign));
cms.ComputeSignature(signer);
MimePart envelope = new MimePart();
envelope.ContentType.MimeType = "application/pkcs7-mime";
envelope.ContentType.Parameters.Add("smime-type", "signed-data");
envelope.ContentType.Parameters.Add("name", "smime.p7m");
envelope.ContentDisposition.Disposition = "attachment";
envelope.ContentDisposition.FileName = "smime.p7m";
envelope.ContentTransferEncoding = ContentTransferEncoding.Base64;
envelope.BinaryContent = cms.Encode();
this.PartTreeRoot = envelope;
this.ContentType = this.PartTreeRoot.ContentType;
this.ContentDisposition = this.PartTreeRoot.ContentDisposition;
this.ContentTransferEncoding = this.PartTreeRoot.ContentTransferEncoding;
}
示例10: Sign
/// <summary>
/// Signs the signature request with the specified certificate, embeds all the specified additional certificates
/// in the signature, and uses the provided additional certificates (along with the Operating
/// System certificate store, if present) to build the full chain for the signing cert and
/// embed that in the signature.
/// </summary>
/// <param name="signingCert">The certificate and private key to sign the document with</param>
/// <param name="chainBuildingCertificates">Additional certificates to use when building the chain to embed</param>
/// <param name="certificatesToEmbed">Additional certificates to add to the signature</param>
public void Sign(X509Certificate2 signingCert, X509Certificate2Collection chainBuildingCertificates, X509Certificate2Collection certificatesToEmbed)
{
if (_signature != null)
{
throw new InvalidOperationException("A signature already exists");
}
// Create the content info
var content = new ContentInfo(Payload.Encode());
// Create the signer
var signer = new CmsSigner(SubjectIdentifierType.SubjectKeyIdentifier, signingCert);
var signingTime = new Pkcs9SigningTime(DateTime.UtcNow);
signer.SignedAttributes.Add(
new CryptographicAttributeObject(
signingTime.Oid,
new AsnEncodedDataCollection(signingTime)));
// We do want the whole chain in the file, but we can't control how
// CmsSigner builds the chain and add our additional certificates.
// So, we tell it not to worry and we manually build the chain and
// add it to the signer.
signer.IncludeOption = X509IncludeOption.EndCertOnly;
// Embed all the certificates in the CMS
var chain = new X509Chain();
if (chainBuildingCertificates != null)
{
chain.ChainPolicy.ExtraStore.AddRange(chainBuildingCertificates);
}
chain.Build(signingCert);
foreach (var element in chain.ChainElements)
{
// Don't re-embed the signing certificate!
if (!Equals(element.Certificate, signingCert))
{
signer.Certificates.Add(element.Certificate);
}
}
if (certificatesToEmbed != null)
{
signer.Certificates.AddRange(certificatesToEmbed);
}
// Create the message and sign it
// Use a local variable so that if the signature fails to compute, this object
// remains in a "good" state.
var cms = new SignedCms(content);
cms.ComputeSignature(signer);
_signature = cms;
}
示例11: SignManifestFile
private void SignManifestFile(PassGeneratorRequest request)
{
Trace.TraceInformation("Signing the manifest file...");
X509Certificate2 card = GetCertificate(request);
if (card == null)
throw new FileNotFoundException("Certificate could not be found. Please ensure the thumbprint and cert location values are correct.");
X509Certificate2 appleCA = GetAppleCertificate(request);
if (appleCA == null)
throw new FileNotFoundException("Apple Certificate could not be found. Please download it from http://www.apple.com/certificateauthority/ and install it into your LOCAL MACHINE certificate store.");
try
{
ContentInfo contentInfo = new ContentInfo(manifestFile);
SignedCms signing = new SignedCms(contentInfo, true);
CmsSigner signer = new CmsSigner(SubjectIdentifierType.SubjectKeyIdentifier, card)
{
IncludeOption = X509IncludeOption.None
};
Trace.TraceInformation("Fetching Apple Certificate for signing..");
Trace.TraceInformation("Constructing the certificate chain..");
signer.Certificates.Add(appleCA);
signer.Certificates.Add(card);
signer.SignedAttributes.Add(new Pkcs9SigningTime());
Trace.TraceInformation("Processing the signature..");
signing.ComputeSignature(signer);
signatureFile = signing.Encode();
Trace.TraceInformation("The file has been successfully signed!");
}
catch (Exception exp)
{
Trace.TraceError("Failed to sign the manifest file: [{0}]", exp.Message);
throw new ManifestSigningException("Failed to sign manifest", exp);
}
}
示例12: EncodeCMS
/// <summary>
/// Signs a data hash and returns the signature
/// </summary>
/// <param name="x">Certificate used to sign the data</param>
/// <param name="hashedData">Data digest to be signed</param>
/// <returns>Returns a string containing a PKCS#7 signature</returns>
private String EncodeCMS(X509Certificate2 x, byte[] hashedData)
{
//we are creating a CMS/PKCS#7 message
Oid digestOid = new Oid("1.2.840.113549.1.7.2");
ContentInfo contentInfo = new ContentInfo(digestOid, hashedData);
//true: signature is detached and will be added to the file
SignedCms signedCms = new SignedCms(contentInfo, true);
CmsSigner cmsSigner = new CmsSigner(x);
// false will prompt the user to enter the pin if a PIV is used
signedCms.ComputeSignature(cmsSigner, false);
byte[] encode = signedCms.Encode();
return Convert.ToBase64String(encode);
}
示例13: ToStream
/// <summary>
/// Stores MIME entity body to the specified stream.
/// </summary>
/// <param name="stream">Stream where to store body data.</param>
/// <param name="headerWordEncoder">Header 8-bit words ecnoder. Value null means that words are not encoded.</param>
/// <param name="headerParmetersCharset">Charset to use to encode 8-bit header parameters. Value null means parameters not encoded.</param>
/// <param name="headerReencode">If true always specified encoding is used for header. If false and header field value not modified,
/// original encoding is kept.</param>
/// <exception cref="ArgumentNullException">Is raised when <b>stream</b> is null reference.</exception>
internal protected override void ToStream(Stream stream,MIME_Encoding_EncodedWord headerWordEncoder,Encoding headerParmetersCharset,bool headerReencode)
{
// We have signer certificate, sign this entity.
if(this.BodyParts.Count > 0 && m_pSignerCert != null){
// Remove old signature if there is any.
if(this.BodyParts.Count > 1){
this.BodyParts.Remove(1);
}
// Store entity to tmp stream.
MemoryStream tmpDataEntityStream = new MemoryStream();
this.BodyParts[0].ToStream(tmpDataEntityStream,null,null,false);
// Compute PKCS #7 message.
SignedCms signedCms = new SignedCms(new ContentInfo(tmpDataEntityStream.ToArray()),true);
signedCms.ComputeSignature(new CmsSigner(m_pSignerCert));
byte[] pkcs7 = signedCms.Encode();
// Create PKCS 7 entity.
MIME_Entity entity_application_pkcs7 = new MIME_Entity();
MIME_b_Application application_pkcs7 = new MIME_b_Application(MIME_MediaTypes.Application.x_pkcs7_signature);
entity_application_pkcs7.Body = application_pkcs7;
application_pkcs7.SetData(new MemoryStream(pkcs7),MIME_TransferEncodings.Base64);
entity_application_pkcs7.ContentType.Param_Name = "smime.p7s";
entity_application_pkcs7.ContentDescription = "S/MIME Cryptographic Signature";
this.BodyParts.Add(entity_application_pkcs7);
signedCms.Decode(application_pkcs7.Data);
signedCms.CheckSignature(true);
}
base.ToStream(stream,headerWordEncoder,headerParmetersCharset,headerReencode);
}
示例14: SignMsg
public byte[] SignMsg(byte[] msg, X509Certificate2 signerCert)
{
byte[] buffer;
try
{
ContentInfo contentInfo = new ContentInfo(msg);
SignedCms cms = null;
cms = new SignedCms(contentInfo, true);
CmsSigner signer = new CmsSigner(signerCert);
signer.IncludeOption = X509IncludeOption.EndCertOnly;//TuyenHM
cms.ComputeSignature(signer, false);
buffer = cms.Encode();
}
catch (Exception exception)
{
throw exception;
}
return buffer;
}
示例15: FirmaBytesMensaje
public byte[] FirmaBytesMensaje(byte[] argBytesMsg, X509Certificate2 argCertFirmante)
{
try
{
// Pongo el mensaje en un objeto ContentInfo (requerido para construir el obj SignedCms)
ContentInfo infoCOntenido = new System.Security.Cryptography.Pkcs.ContentInfo(argBytesMsg);
SignedCms cmsFirmado = new SignedCms(infoCOntenido);
// Creo objeto CmsSigner que tiene las caracteristicas del firmante
CmsSigner cmsFirmante = new CmsSigner(argCertFirmante);
cmsFirmante.IncludeOption = X509IncludeOption.EndCertOnly;
// Firmo el mensaje PKCS #7
cmsFirmado.ComputeSignature(cmsFirmante);
// Encodeo el mensaje PKCS #7.
return (cmsFirmado.Encode());
}
catch (Exception excepcionAlFirmar)
{
throw new Exception("***Error al firmar: FirmaBytesMensaje: " + excepcionAlFirmar.Message);
}
}