protected string CheckSig() { var formData = Request.Form; var text = formData["txtSign"]; var sig = formData["txtSig"]; string output = "INVALID!"; if (!string.IsNullOrEmpty(sig)) { try { ContentInfo contentInfo = new ContentInfo(Encoding.UTF8.GetBytes(text)); SignedCms signedCms = new SignedCms(contentInfo, true); signedCms.Decode(Convert.FromBase64String(sig)); // This checks if the signature is valid, but doensn't actually verify the cert (TODO) signedCms.CheckSignature(true); output = "Signature valid."; signedCms.CheckSignature(false); output += "<br>Cert valid"; } catch (Exception e) { output += "<br>" + e.ToString(); } } return output; }
public EnvelopedCms (ContentInfo contentInfo) : this () { if (contentInfo == null) throw new ArgumentNullException ("contentInfo"); _content = contentInfo; }
public sealed override byte[] Encrypt(CmsRecipientCollection recipients, ContentInfo contentInfo, AlgorithmIdentifier contentEncryptionAlgorithm, X509Certificate2Collection originatorCerts, CryptographicAttributeObjectCollection unprotectedAttributes) { using (SafeCryptMsgHandle hCryptMsg = EncodeHelpers.CreateCryptMsgHandleToEncode(recipients, contentInfo.ContentType, contentEncryptionAlgorithm, originatorCerts, unprotectedAttributes)) { byte[] encodedContent; if (contentInfo.ContentType.Value.Equals(Oids.Pkcs7Data, StringComparison.OrdinalIgnoreCase)) { unsafe { byte[] content = contentInfo.Content; fixed (byte* pContent = content) { DATA_BLOB blob = new DATA_BLOB((IntPtr)pContent, (uint)(content.Length)); encodedContent = Interop.Crypt32.CryptEncodeObjectToByteArray(CryptDecodeObjectStructType.X509_OCTET_STRING, &blob); } } } else { encodedContent = contentInfo.Content; } if (encodedContent.Length > 0) { if (!Interop.Crypt32.CryptMsgUpdate(hCryptMsg, encodedContent, encodedContent.Length, fFinal: true)) throw Marshal.GetLastWin32Error().ToCryptographicException(); } byte[] encodedMessage = hCryptMsg.GetMsgParamAsByteArray(CryptMsgParamType.CMSG_CONTENT_PARAM); return encodedMessage; } }
/// <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); } }
public void ConstructorNonPkcs7Oid () { Oid o = new Oid ("1.2.3.4"); ContentInfo ci = new ContentInfo (o, asnNull); Assert.AreEqual (asnNull, ci.Content, "Content"); Assert.AreEqual ("1.2.3.4", ci.ContentType.Value, "ContentType.Value"); }
/// <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); } }
public void ConstructorContent () { ContentInfo ci = new ContentInfo (asnNull); Assert.AreEqual (asnNull, ci.Content, "Content"); Assert.AreEqual (defaultName, ci.ContentType.FriendlyName, "ContentType.FriendlyName"); Assert.AreEqual (defaultOid, ci.ContentType.Value, "ContentType.Value"); }
public EnvelopedCms (SubjectIdentifierType recipientIdentifierType, ContentInfo contentInfo) : this (contentInfo) { _idType = recipientIdentifierType; if (_idType == SubjectIdentifierType.SubjectKeyIdentifier) _version = 2; }
public EnvelopedCms (ContentInfo contentInfo, AlgorithmIdentifier encryptionAlgorithm) : this (contentInfo) { if (encryptionAlgorithm == null) throw new ArgumentNullException ("encryptionAlgorithm"); _identifier = encryptionAlgorithm; }
private byte[] Sign(byte[] messageBytes) { Pkcs.ContentInfo content = new Pkcs.ContentInfo(messageBytes); Pkcs.SignedCms signed = new Pkcs.SignedCms(content); Pkcs.CmsSigner signer = new Pkcs.CmsSigner(_signerCert); signed.ComputeSignature(signer); byte[] signedBytes = signed.Encode(); return(signedBytes); }
public byte[] encrypt(byte[] plainTest) { envelopedContentInfo = new ContentInfo(plainTest); envelopedCms = new EnvelopedCms(envelopedContentInfo); envelopeCmsResipient = new CmsRecipient(SubjectIdentifierType.IssuerAndSerialNumber, cryptographyClientCert); envelopedCms.Encrypt(envelopeCmsResipient); return envelopedCms.Encode(); }
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(); }
public SignedCms (ContentInfo content, bool detached) : this () { if (content == null) throw new ArgumentNullException ("content"); _content = content; _detached = detached; }
private byte[] EncryptedBytes(byte[] bytes) { var contentInfo = new ContentInfo(bytes); var encryptAlgoOid = new Oid("2.16.840.1.101.3.4.1.42"); // AES-256-CBC var envelopedCms = new EnvelopedCms(contentInfo, new AlgorithmIdentifier(encryptAlgoOid)); var recipient = new CmsRecipient(CryptographicCertificate); envelopedCms.Encrypt(recipient); return envelopedCms.Encode(); }
/// <summary> /// Encrypts the specified string. /// </summary> /// <param name="plaintext">The plaintext to be encrypted.</param> /// <param name="certificate">The certificate to be used for encryption.</param> /// <returns>The encrypted text.</returns> public static string Encrypt(this string plaintext, X509Certificate2 certificate) { var contentInfo = new ContentInfo(Encoding.UTF8.GetBytes(plaintext)); var envelopedCms = new EnvelopedCms(contentInfo); var cmsRecipient = new CmsRecipient(certificate); envelopedCms.Encrypt(cmsRecipient); return Convert.ToBase64String(envelopedCms.Encode()); }
private byte[] Envelope(byte[] contentBytes) { Pkcs.ContentInfo content = new Pkcs.ContentInfo(contentBytes); Pkcs.EnvelopedCms envMsg = new Pkcs.EnvelopedCms(content); Pkcs.CmsRecipient recipient = new Pkcs.CmsRecipient(Pkcs.SubjectIdentifierType.IssuerAndSerialNumber, _recipientCert); envMsg.Encrypt(recipient); byte[] encryptedBytes = envMsg.Encode(); return(encryptedBytes); }
public static byte[] Encode(byte[] arMessage, object signerCert, string signerPassword) { X509Certificate2 cert = signerCert is X509Certificate2 ? (X509Certificate2)signerCert : new X509Certificate2((string)signerCert, signerPassword); ContentInfo contentInfo = new ContentInfo(arMessage); SignedCms signedCms = new SignedCms(contentInfo, true); // <- true detaches the signature CmsSigner cmsSigner = new CmsSigner(cert); signedCms.ComputeSignature(cmsSigner); byte[] signature = signedCms.Encode(); return(signature); }
public static void DecodeAlgorithmDes_RoundTrip() { AlgorithmIdentifier algorithm = new AlgorithmIdentifier(new Oid(Oids.Des)); ContentInfo contentInfo = new ContentInfo(new byte[] { 1, 2, 3 }); EnvelopedCms ecms = new EnvelopedCms(contentInfo, algorithm); using (X509Certificate2 cert = Certificates.RSAKeyTransfer1.GetCertificate()) { CmsRecipient cmsRecipient = new CmsRecipient(cert); ecms.Encrypt(cmsRecipient); } byte[] encodedMessage = ecms.Encode(); VerifyAlgorithmDes(encodedMessage); }
public static void CheckSig(byte[] sig, byte[] data) { ContentInfo contentInfo = new ContentInfo(data); SignedCms signedCms = new SignedCms(contentInfo, true); signedCms.Decode(sig); // This checks if the signature is valid, but doensn't actually verify the cert (TODO) signedCms.CheckSignature(true); signedCms.CheckSignature(false); }
public static void DecodeCertificates0_RoundTrip() { ContentInfo contentInfo = new ContentInfo(new byte[] { 1, 2, 3 }); EnvelopedCms ecms = new EnvelopedCms(contentInfo); using (X509Certificate2 cert = Certificates.RSAKeyTransfer1.GetCertificate()) { CmsRecipient cmsRecipient = new CmsRecipient(cert); ecms.Encrypt(cmsRecipient); } byte[] encodedMessage = ecms.Encode(); VerifyCertificates0(encodedMessage); }
public static void DecodeRecipients3_RoundTrip() { ContentInfo contentInfo = new ContentInfo(new byte[] { 1, 2, 3 }); EnvelopedCms ecms = new EnvelopedCms(contentInfo); CmsRecipientCollection recipients = new CmsRecipientCollection(); foreach (X509Certificate2 cert in s_certs) { recipients.Add(new CmsRecipient(cert)); } ecms.Encrypt(recipients); byte[] encodedMessage = ecms.Encode(); VerifyRecipients3(encodedMessage); }
public EnvelopedCms(ContentInfo contentInfo, AlgorithmIdentifier encryptionAlgorithm) { if (contentInfo == null) throw new ArgumentNullException(nameof(contentInfo)); if (encryptionAlgorithm == null) throw new ArgumentNullException(nameof(encryptionAlgorithm)); Version = 0; // It makes little sense to ask for a version before you've decoded, but since the desktop returns 0 in that case, we will too. ContentInfo = contentInfo; ContentEncryptionAlgorithm = encryptionAlgorithm; Certificates = new X509Certificate2Collection(); UnprotectedAttributes = new CryptographicAttributeObjectCollection(); _decryptorPal = null; _lastCall = LastCall.Ctor; }
public static String CheckFileSignature(ContentInfo content, byte[] signature) { var verifyCms = new SignedCms(content, true); verifyCms.Decode(signature); var cert = verifyCms.SignerInfos[0].Certificate; try { verifyCms.CheckSignature(new X509Certificate2Collection(cert), false); return @"Signature is valid"; } catch (CryptographicException) { return @"Signature is not valid for content"; } }
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(); }
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; }
public static void ZeroLengthContent_RoundTrip() { ContentInfo contentInfo = new ContentInfo(Array.Empty<byte>()); EnvelopedCms ecms = new EnvelopedCms(contentInfo); using (X509Certificate2 cert = Certificates.RSAKeyTransfer1.GetCertificate()) { CmsRecipient cmsRecipient = new CmsRecipient(cert); try { ecms.Encrypt(cmsRecipient); } catch (CryptographicException e) { throw new Exception("ecms.Encrypt() threw " + e.Message + ".\nIf you're running on the desktop CLR, this is actually an expected result."); } } byte[] encodedMessage = ecms.Encode(); ValidateZeroLengthContent(encodedMessage); }
public SignedCms (SubjectIdentifierType signerIdentifierType, ContentInfo contentInfo, bool detached) { if (contentInfo == null) throw new ArgumentNullException("contentInfo"); if (contentInfo.Content == null) throw new ArgumentNullException("contentInfo.Content"); // Reset all states. if (signerIdentifierType != SubjectIdentifierType.SubjectKeyIdentifier && signerIdentifierType != SubjectIdentifierType.IssuerAndSerialNumber && signerIdentifierType != SubjectIdentifierType.NoSignature) { signerIdentifierType = SubjectIdentifierType.IssuerAndSerialNumber; } m_safeCryptMsgHandle = SafeCryptMsgHandle.InvalidHandle; m_signerIdentifierType = signerIdentifierType; m_version = 0; m_contentInfo = contentInfo; m_detached = detached; }
public static byte[] FirmaFileBouncy(byte[] data, X509Certificate2 cert) { try { SHA256Managed hashSha256 = new SHA256Managed(); byte[] certHash = hashSha256.ComputeHash(cert.RawData); EssCertIDv2 essCert1 = new EssCertIDv2(new Org.BouncyCastle.Asn1.X509.AlgorithmIdentifier("2.16.840.1.101.3.4.2.1"), certHash); SigningCertificateV2 scv2 = new SigningCertificateV2(new EssCertIDv2[] { essCert1 }); Org.BouncyCastle.Asn1.Cms.Attribute CertHAttribute = new Org.BouncyCastle.Asn1.Cms.Attribute(Org.BouncyCastle.Asn1.Pkcs.PkcsObjectIdentifiers.IdAASigningCertificateV2, new DerSet(scv2)); Asn1EncodableVector v = new Asn1EncodableVector(); v.Add(CertHAttribute); Org.BouncyCastle.Asn1.Cms.AttributeTable AT = new Org.BouncyCastle.Asn1.Cms.AttributeTable(v); CmsSignedDataGenWithRsaCsp cms = new CmsSignedDataGenWithRsaCsp(); var rsa = (RSACryptoServiceProvider)cert.PrivateKey; Org.BouncyCastle.X509.X509Certificate certCopy = DotNetUtilities.FromX509Certificate(cert); cms.MyAddSigner(rsa, certCopy, "1.2.840.113549.1.1.1", "2.16.840.1.101.3.4.2.1", AT, null); ArrayList certList = new ArrayList(); certList.Add(certCopy); Org.BouncyCastle.X509.Store.X509CollectionStoreParameters PP = new Org.BouncyCastle.X509.Store.X509CollectionStoreParameters(certList); Org.BouncyCastle.X509.Store.IX509Store st1 = Org.BouncyCastle.X509.Store.X509StoreFactory.Create("CERTIFICATE/COLLECTION", PP); cms.AddCertificates(st1); //mi ricavo il file da firmare CmsSignedData Firmato = cms.Generate(new CmsProcessableByteArray(data), false); CmsSigner cmsSigner = new CmsSigner(cert); cmsSigner.IncludeOption = X509IncludeOption.EndCertOnly; System.Security.Cryptography.Pkcs.ContentInfo contentInfo = new System.Security.Cryptography.Pkcs.ContentInfo(Firmato.GetEncoded()); SignedCms signedCms = new SignedCms(); signedCms.Decode(Firmato.GetEncoded()); byte[] ret = signedCms.Encode(); return(ret); } catch { return(null); } }
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 }; }
public static byte[] Encrypt(byte[] message, object recipientCert, string encryptionAlgorithm) { if (!string.Equals(encryptionAlgorithm, EncryptionAlgorithm.DES3) && !string.Equals(encryptionAlgorithm, EncryptionAlgorithm.RC2)) { throw new ArgumentException("encryptionAlgorithm argument must be 3DES or RC2 - value specified was:" + encryptionAlgorithm); } X509Certificate2 cert = recipientCert is X509Certificate2 ? (X509Certificate2)recipientCert : new X509Certificate2((string)recipientCert); ContentInfo contentInfo = new ContentInfo(message); EnvelopedCms envelopedCms = new EnvelopedCms(contentInfo, new AlgorithmIdentifier(new System.Security.Cryptography.Oid(encryptionAlgorithm))); // should be 3DES or RC2 CmsRecipient recipient = new CmsRecipient(SubjectIdentifierType.IssuerAndSerialNumber, cert); envelopedCms.Encrypt(recipient); byte[] encoded = envelopedCms.Encode(); return(encoded); }
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); } }
internal static DecryptorPalWindows Decode( byte[] encodedMessage, out int version, out ContentInfo contentInfo, out AlgorithmIdentifier contentEncryptionAlgorithm, out X509Certificate2Collection originatorCerts, out CryptographicAttributeObjectCollection unprotectedAttributes ) { SafeCryptMsgHandle hCryptMsg = Interop.Crypt32.CryptMsgOpenToDecode(MsgEncodingType.All, 0, 0, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero); if (hCryptMsg == null || hCryptMsg.IsInvalid) throw Marshal.GetLastWin32Error().ToCryptographicException(); if (!Interop.Crypt32.CryptMsgUpdate(hCryptMsg, encodedMessage, encodedMessage.Length, fFinal: true)) throw Marshal.GetLastWin32Error().ToCryptographicException(); CryptMsgType cryptMsgType = hCryptMsg.GetMessageType(); if (cryptMsgType != CryptMsgType.CMSG_ENVELOPED) throw ErrorCode.CRYPT_E_INVALID_MSG_TYPE.ToCryptographicException(); version = hCryptMsg.GetVersion(); contentInfo = hCryptMsg.GetContentInfo(); using (SafeHandle sh = hCryptMsg.GetMsgParamAsMemory(CryptMsgParamType.CMSG_ENVELOPE_ALGORITHM_PARAM)) { unsafe { CRYPT_ALGORITHM_IDENTIFIER* pCryptAlgorithmIdentifier = (CRYPT_ALGORITHM_IDENTIFIER*)(sh.DangerousGetHandle()); contentEncryptionAlgorithm = (*pCryptAlgorithmIdentifier).ToAlgorithmIdentifier(); } } originatorCerts = hCryptMsg.GetOriginatorCerts(); unprotectedAttributes = hCryptMsg.GetUnprotectedAttributes(); RecipientInfoCollection recipientInfos = CreateRecipientInfos(hCryptMsg); return new DecryptorPalWindows(hCryptMsg, recipientInfos); }
/// <summary> /// Подписание данных (файла) с помощью сертификата ЭП /// </summary> /// <param name="certificate">Сертификат Электронной Подписи, которым будет подписан файл</param> /// <returns>Файл с подписью (в случае прикрепленной подписи будет файл с данными и подписью) </returns> public byte[] Sign(ICertificate certificate) { //создаем контейнер с данными, которые будут подписываться var content = new ContentInfo(this.Original); //создаем пакет, в который помещаем контейнер с данными и параметры подписи //это основной объект, в рамках которого формируются проверки и преобразования подписи var cms = new SignedCms(content, this.Detached); //создаем подписанта (объект на основе сертификата, который будет подписывать) var signer = new CmsSigner(certificate.CertificateX509); //с помощью подписанта подписываем пакет так, //что теперь в пакете находятся не сами данные, //а именно подписанные данные, то есть: // - сама подпись в случае отсоединенной подписи // - подпись с оригинальными данными в случае присоединенной подписи cms.ComputeSignature(signer, false); // сохраняем подписанный пакет byte[] result = cms.Encode(); return result; }
public SignedCms(ContentInfo content) : this(content, false) { }
public SignedCms(SubjectIdentifierType signerIdentifierType, ContentInfo content) : this(content, false) { _type = signerIdentifierType; }
public SignedCms(SubjectIdentifierType signerIdentifierType, ContentInfo content, bool detached) : this(content, detached) { _type = signerIdentifierType; }
public SignedCms(ContentInfo contentInfo, bool detached) : this(SubjectIdentifierType.IssuerAndSerialNumber, contentInfo, detached) { }
public static byte[] SignDetached(byte[] data, X509Certificate2 signingCert) { ContentInfo content = new ContentInfo(data); SignedCms signedMessage = new SignedCms(content, true); CmsSigner signer = new CmsSigner(signingCert); signedMessage.ComputeSignature(signer); byte[] signedBytes = signedMessage.Encode(); return signedBytes; }
public void Decode(byte[] encodedMessage) { PKCS7.ContentInfo ci = new PKCS7.ContentInfo(encodedMessage); if (ci.ContentType != PKCS7.Oid.signedData) { throw new Exception(""); } PKCS7.SignedData sd = new PKCS7.SignedData(ci.Content); SubjectIdentifierType type = SubjectIdentifierType.Unknown; object o = null; X509Certificate2 x509 = null; if (sd.SignerInfo.Certificate != null) { x509 = new X509Certificate2(sd.SignerInfo.Certificate.RawData); } else if ((sd.SignerInfo.IssuerName != null) && (sd.SignerInfo.SerialNumber != null)) { byte[] serial = sd.SignerInfo.SerialNumber; Array.Reverse(serial); // ??? type = SubjectIdentifierType.IssuerAndSerialNumber; X509IssuerSerial xis = new X509IssuerSerial(); xis.IssuerName = sd.SignerInfo.IssuerName; xis.SerialNumber = ToString(serial, true); o = xis; // TODO: move to a FindCertificate (issuer, serial, collection) foreach (Mono.Security.X509.X509Certificate x in sd.Certificates) { if (x.IssuerName == sd.SignerInfo.IssuerName) { if (ToString(x.SerialNumber, true) == xis.SerialNumber) { x509 = new X509Certificate2(x.RawData); break; } } } } else if (sd.SignerInfo.SubjectKeyIdentifier != null) { string ski = ToString(sd.SignerInfo.SubjectKeyIdentifier, false); type = SubjectIdentifierType.SubjectKeyIdentifier; o = (object)ski; // TODO: move to a FindCertificate (ski, collection) foreach (Mono.Security.X509.X509Certificate x in sd.Certificates) { if (ToString(GetKeyIdentifier(x), false) == ski) { x509 = new X509Certificate2(x.RawData); break; } } } SignerInfo si = new SignerInfo(sd.SignerInfo.HashName, x509, type, o, sd.SignerInfo.Version); // si.AuthenticatedAttributes // si.UnauthenticatedAttributes _info.Add(si); ASN1 content = sd.ContentInfo.Content; Oid oid = new Oid(sd.ContentInfo.ContentType); if (!_detached || _content == null) { if (content[0] == null) { throw new ArgumentException("ContentInfo has no content. Detached signature ?"); } _content = new ContentInfo(oid, content[0].Value); } foreach (Mono.Security.X509.X509Certificate x in sd.Certificates) { _certs.Add(new X509Certificate2(x.RawData)); } _version = sd.Version; }
public EnvelopedCms(ContentInfo contentInfo) : this(contentInfo, new AlgorithmIdentifier(Oid.FromOidValue(Oids.TripleDesCbc, OidGroup.EncryptionAlgorithm))) { }
public EnvelopedCms(ContentInfo contentInfo) : this(contentInfo, new AlgorithmIdentifier(Oids.Aes256CbcOid.CopyOid())) { }
public SignedCms(SubjectIdentifierType signerIdentifierType, ContentInfo contentInfo) : this(signerIdentifierType, contentInfo, false) { }
public static bool VerifyDetached(byte[] data, byte[] signature) { ContentInfo content = new ContentInfo(data); SignedCms signedMessage = new SignedCms(content, true); signedMessage.Decode(signature); try { signedMessage.CheckSignature(false); return true; } catch { return false; } }
public SignedCms(ContentInfo contentInfo) : this(SubjectIdentifierType.IssuerAndSerialNumber, contentInfo, false) { }