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


C# SignedCms.ComputeSignature方法代码示例

本文整理汇总了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);
            }
        }
开发者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: 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

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

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

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

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

示例8: ComputeEmptySignature

		public void ComputeEmptySignature ()
		{
			SignedCms sp = new SignedCms ();
			sp.ComputeSignature ();
		}
开发者ID:nlhepler,项目名称:mono,代码行数:5,代码来源:SignedCmsTest.cs

示例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;
        }
开发者ID:JBTech,项目名称:MailSystem.NET,代码行数:40,代码来源:Message.cs

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

示例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);
            }
        }
开发者ID:rajankumar123,项目名称:dotnet-passbook,代码行数:45,代码来源:PassGenerator.cs

示例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);
        }
开发者ID:swarana,项目名称:DT4SM,代码行数:21,代码来源:Text4PLOT.cs

示例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);
        }
开发者ID:DJGosnell,项目名称:LumiSoft.Net,代码行数:42,代码来源:MIME_b_MultipartSigned.cs

示例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;
 }
开发者ID:huamanhtuyen,项目名称:VNACCS,代码行数:19,代码来源:SMimeFormat.cs

示例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);
            }
        }
开发者ID:javierlov,项目名称:FE,代码行数:24,代码来源:AfipConnection.cs


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