当前位置: 首页>>代码示例>>C#>>正文


C# Pkcs.CmsSigner类代码示例

本文整理汇总了C#中System.Security.Cryptography.Pkcs.CmsSigner的典型用法代码示例。如果您正苦于以下问题:C# CmsSigner类的具体用法?C# CmsSigner怎么用?C# CmsSigner使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


CmsSigner类属于System.Security.Cryptography.Pkcs命名空间,在下文中一共展示了CmsSigner类的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);
            }
        }
开发者ID:fedepazw,项目名称:OpenReceArg,代码行数:35,代码来源:CertificadosX509.cs

示例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);
            }
        }
开发者ID:javierpernias-santex,项目名称:facturaelectronica,代码行数:39,代码来源:CertificadosX509Lib.cs

示例3: CreateBagOfCertificates

 internal static X509Certificate2Collection CreateBagOfCertificates(CmsSigner signer)
 {
     X509Certificate2Collection certificates = new X509Certificate2Collection();
     certificates.AddRange(signer.Certificates);
     if (signer.IncludeOption != X509IncludeOption.None)
     {
         if (signer.IncludeOption == X509IncludeOption.EndCertOnly)
         {
             certificates.Add(signer.Certificate);
             return certificates;
         }
         int count = 1;
         X509Chain chain = new X509Chain();
         chain.Build(signer.Certificate);
         if ((chain.ChainStatus.Length > 0) && ((chain.ChainStatus[0].Status & X509ChainStatusFlags.PartialChain) == X509ChainStatusFlags.PartialChain))
         {
             throw new CryptographicException(-2146762486);
         }
         if (signer.IncludeOption == X509IncludeOption.WholeChain)
         {
             count = chain.ChainElements.Count;
         }
         else if (chain.ChainElements.Count > 1)
         {
             count = chain.ChainElements.Count - 1;
         }
         for (int i = 0; i < count; i++)
         {
             certificates.Add(chain.ChainElements[i].Certificate);
         }
     }
     return certificates;
 }
开发者ID:pritesh-mandowara-sp,项目名称:DecompliedDotNetLibraries,代码行数:33,代码来源:PkcsUtils.cs

示例4: 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();
 }
开发者ID:NomadPL,项目名称:Nomad,代码行数:9,代码来源:PkiSignatureAlgorithm.cs

示例5: ConstructorSubjectKeyIdentifier

		public void ConstructorSubjectKeyIdentifier () 
		{
			CmsSigner ps = new CmsSigner (SubjectIdentifierType.SubjectKeyIdentifier);
			// default properties
			Assert.AreEqual (0, ps.SignedAttributes.Count, "SignedAttributes");
			Assert.IsNull (ps.Certificate, "Certificate");
			Assert.AreEqual (sha1Name, ps.DigestAlgorithm.FriendlyName, "DigestAlgorithm.FriendlyName");
			Assert.AreEqual (sha1Oid, ps.DigestAlgorithm.Value, "DigestAlgorithm.Value");
			Assert.AreEqual (X509IncludeOption.ExcludeRoot, ps.IncludeOption, "IncludeOption");
			Assert.AreEqual (SubjectIdentifierType.SubjectKeyIdentifier, ps.SignerIdentifierType, "SignerIdentifierType");
			Assert.AreEqual (0, ps.UnsignedAttributes.Count, "UnsignedAttributes");
		}
开发者ID:nlhepler,项目名称:mono,代码行数:12,代码来源:CmsSignerTest.cs

示例6: ConstructorSubjectKeyIdentifier

		public void ConstructorSubjectKeyIdentifier () 
		{
			CmsSigner ps = new CmsSigner (SubjectIdentifierType.SubjectKeyIdentifier);
			// default properties
			AssertEquals ("SignedAttributes", 0, ps.SignedAttributes.Count);
			AssertNull ("Certificate", ps.Certificate);
			AssertEquals ("DigestAlgorithm.FriendlyName", sha1Name, ps.DigestAlgorithm.FriendlyName);
			AssertEquals ("DigestAlgorithm.Value", sha1Oid, ps.DigestAlgorithm.Value);
			AssertEquals ("IncludeOption", X509IncludeOption.ExcludeRoot, ps.IncludeOption);
			AssertEquals ("SignerIdentifierType", SubjectIdentifierType.SubjectKeyIdentifier, ps.SignerIdentifierType);
			AssertEquals ("UnsignedAttributes", 0, ps.UnsignedAttributes.Count);
		}
开发者ID:jjenki11,项目名称:blaze-chem-rendering,代码行数:12,代码来源:CmsSignerTest.cs

示例7: _bSendMessage_Click

        private void _bSendMessage_Click(object sender, EventArgs e)
        {
            this.AddLogEntry("Creating message.");

            // We create the message object
            ActiveUp.Net.Mail.Message message = new ActiveUp.Net.Mail.Message();

            // We assign the sender email
            message.From.Email = this._tbFromEmail.Text;

            // We assign the recipient email
            message.To.Add(this._tbToEmail.Text);

            // We assign the subject
            message.Subject = this._tbSubject.Text;

            // We assign the body text
            message.BodyText.Text = this._tbBodyText.Text;

            // It is required to build the mime part tree before signing
            message.BuildMimePartTree();

            if (_tbCertificate.Text != string.Empty)
            {
                CmsSigner signer = new CmsSigner(new X509Certificate2(_tbCertificate.Text));

                // Here we only want the signer's certificate to be sent along. Not the whole chain.
                signer.IncludeOption = X509IncludeOption.EndCertOnly;

                message.SmimeAttachSignatureBy(signer);
            }

            // We send the email using the specified SMTP server
            this.AddLogEntry("Sending message.");

            try
            {
                message.Send(this._tbSmtpServer.Text);

                this.AddLogEntry("Message sent successfully.");
            }

            catch (SmtpException ex)
            {
                this.AddLogEntry(string.Format("Smtp Error: {0}", ex.Message));
            }

            catch (Exception ex)
            {
                this.AddLogEntry(string.Format("Failed: {0}", ex.Message));
            }
        }
开发者ID:haoasqui,项目名称:MailSystem.NET,代码行数:52,代码来源:SendingSignedEmails.cs

示例8: SignMessage

        private static byte[] SignMessage(X509Certificate2 certificate, byte[] message)
        {
            // Создание объекта для подписи сообщения
            var signedCms = new GostSignedCms(new ContentInfo(message), true);

            // Создание объектс с информацией о подписчике
            var signer = new CmsSigner(certificate);

            // Включение информации только о конечном сертификате (только для теста)
            signer.IncludeOption = X509IncludeOption.EndCertOnly;

            // Создание подписи для сообщения CMS/PKCS#7
            signedCms.ComputeSignature(signer);

            // Создание подписи CMS/PKCS#7
            return signedCms.Encode();
        }
开发者ID:kapitanov,项目名称:GostCryptography,代码行数:17,代码来源:SignedCmsDetachedSignTest.cs

示例9: 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();
        }
开发者ID:GonzaloFernandoA,项目名称:FacturacionElectronica,代码行数:18,代码来源:FirmadorDeCertificado.cs

示例10: IsSignedBy

        public static bool IsSignedBy(this X509Certificate thisCertificate, X509Certificate signerCertificate)
        {
            X509Certificate2 c = new X509Certificate2(thisCertificate.GetTbsCertificate());
            X509Certificate2 i = new X509Certificate2(signerCertificate.GetTbsCertificate());
            X509Certificate2 c2 = new X509Certificate2(@"c:\temp\der.cer");
            X509Certificate2 i2 = new X509Certificate2(@"c:\temp\cader.cer");
            /*byte[] pvSubject = thisCertificate.GetTbsCertificate();
            byte[] pvIssuer = signerCertificate.GetTbsCertificate();
            */
            System.Text.Encoding.ASCII.GetString(c.RawData);
            IntPtr pvSubject = c.Handle;
            IntPtr pvIssuer = i.Handle;
            int res = SspiProvider.CryptVerifyCertificateSignatureEx(IntPtr.Zero, X509_ASN_ENCODING,
                                                           CRYPT_VERIFY_CERT_SIGN_SUBJECT_CERT, pvSubject,
                                                           CRYPT_VERIFY_CERT_SIGN_ISSUER_CERT, pvIssuer, 0,
                                                           IntPtr.Zero);
            Marshal.GetLastWin32Error();
            CmsSigner signer = new CmsSigner(i);
            SignedCms signedMessage = new SignedCms();
            // deserialize PKCS #7 byte array

            signedMessage.Decode(thisCertificate.GetTbsCertificate());
            Log.Write("Veryfy old");
            Log.Write("EndVeryfy old");
            Log.Write("Get signer's public key");
            var publicKey = signerCertificate.GetPublicKey();
            Log.Write("Got signer's public key");
            try
            {
                Log.Write("Veryfy signature");
                //TODO: log errors
                thisCertificate.Verify(publicKey);
                Log.Write("Verified");
            }
            catch (CertificateException)
            {
                return false;
            }
            catch (InvalidKeyException)
            {
                return false;
            }
            return true;
        }
开发者ID:demonix,项目名称:CertVerifier,代码行数:44,代码来源:X509CertificateExtensions.cs

示例11: 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;
        }
开发者ID:RandyCode,项目名称:SimpleTools,代码行数:44,代码来源:Program.cs

示例12: 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
            };
        }
开发者ID:CACBridge,项目名称:ChromeCAC,代码行数:40,代码来源:CAC.cs

示例13: 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);
            }
        }
开发者ID:ozeraydin57,项目名称:Addon-SAP-B1-Default,代码行数:22,代码来源:XmlSignUtil.cs

示例14: CounterSign

 private void CounterSign(CmsSigner signer)
 {
     CspParameters parameters = new CspParameters();
     if (!System.Security.Cryptography.X509Certificates.X509Utils.GetPrivateKeyInfo(System.Security.Cryptography.X509Certificates.X509Utils.GetCertContext(signer.Certificate), ref parameters))
     {
         throw new CryptographicException(Marshal.GetLastWin32Error());
     }
     KeyContainerPermission permission = new KeyContainerPermission(KeyContainerPermissionFlags.NoFlags);
     KeyContainerPermissionAccessEntry accessEntry = new KeyContainerPermissionAccessEntry(parameters, KeyContainerPermissionFlags.Sign | KeyContainerPermissionFlags.Open);
     permission.AccessEntries.Add(accessEntry);
     permission.Demand();
     uint dwIndex = (uint) PkcsUtils.GetSignerIndex(this.m_signedCms.GetCryptMsgHandle(), this, 0);
     System.Security.Cryptography.SafeLocalAllocHandle handle = System.Security.Cryptography.CAPI.LocalAlloc(0x40, new IntPtr(Marshal.SizeOf(typeof(System.Security.Cryptography.CAPI.CMSG_SIGNER_ENCODE_INFO))));
     System.Security.Cryptography.CAPI.CMSG_SIGNER_ENCODE_INFO structure = PkcsUtils.CreateSignerEncodeInfo(signer);
     try
     {
         Marshal.StructureToPtr(structure, handle.DangerousGetHandle(), false);
         if (!System.Security.Cryptography.CAPI.CryptMsgCountersign(this.m_signedCms.GetCryptMsgHandle(), dwIndex, 1, handle.DangerousGetHandle()))
         {
             throw new CryptographicException(Marshal.GetLastWin32Error());
         }
         this.m_signedCms.ReopenToDecode();
     }
     finally
     {
         Marshal.DestroyStructure(handle.DangerousGetHandle(), typeof(System.Security.Cryptography.CAPI.CMSG_SIGNER_ENCODE_INFO));
         handle.Dispose();
         structure.Dispose();
     }
     PkcsUtils.AddCertsToMessage(this.m_signedCms.GetCryptMsgHandle(), this.m_signedCms.Certificates, PkcsUtils.CreateBagOfCertificates(signer));
 }
开发者ID:pritesh-mandowara-sp,项目名称:DecompliedDotNetLibraries,代码行数:31,代码来源:SignerInfo.cs

示例15: 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;
        }
开发者ID:hishamco,项目名称:Signing,代码行数:60,代码来源:Signature.cs


注:本文中的System.Security.Cryptography.Pkcs.CmsSigner类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。