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


C# SignedCms.Encode方法代码示例

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


在下文中一共展示了SignedCms.Encode方法的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: VerifyTimestamp

        internal static TimeStampToken VerifyTimestamp(byte[] data, SignedCms timestampCms)
        {
            var signer = Signer.FromSignerInfo(timestampCms.SignerInfos[0]);

            bool trusted = signer.SignerCertificate.Verify();

            var contentInfo = timestampCms.Encode();

            IntPtr unmanagedContext = IntPtr.Zero;
            try
            {
                NativeUtils.ThrowIfFailed(NativeMethods.CryptVerifyTimeStampSignature(
                    pbTSContentInfo: contentInfo,
                    cbTSContentInfo: (uint)contentInfo.Length,
                    pbData: data,
                    cbData: (uint)data.Length,
                    hAdditionalStore: IntPtr.Zero,
                    ppTsContext: out unmanagedContext,
                    ppTsSigner: IntPtr.Zero,
                    phStore: IntPtr.Zero));

                // Copy the context out
                var context = (CRYPT_TIMESTAMP_CONTEXT)Marshal.PtrToStructure(unmanagedContext, typeof(CRYPT_TIMESTAMP_CONTEXT));

                // Copy the info out
                var info = (CRYPT_TIMESTAMP_INFO)Marshal.PtrToStructure(context.pTimeStamp, typeof(CRYPT_TIMESTAMP_INFO));

                return TimeStampToken.FromTimestampInfo(info, signer, trusted);
            }
            finally
            {
                if (unmanagedContext != IntPtr.Zero)
                {
                    NativeMethods.CryptMemFree(unmanagedContext);
                }
            }
        }
开发者ID:hishamco,项目名称:Signing,代码行数:37,代码来源:RFC3161.cs

示例9: ComputeSignatureCmsSignerUnknown

		public void ComputeSignatureCmsSignerUnknown () 
		{
			ContentInfo ci = new ContentInfo (asnNull);
			SignedCms sp = new SignedCms (ci);

			CmsSigner signer = new CmsSigner (SubjectIdentifierType.Unknown, GetCertificate (true));
			signer.Certificates.Add (new X509Certificate2 (intca_cer));
			signer.Certificates.Add (new X509Certificate2 (root_cer));
			sp.ComputeSignature (signer);

			byte[] encoded = sp.Encode ();
			string s = BitConverter.ToString (encoded);
#if DEBUG
			FileStream fs = File.OpenWrite ("ComputeSignaturePkcs7SignerUnknown.der");
			fs.Write (encoded, 0, encoded.Length);
			fs.Close ();
#endif
			RoundTrip (encoded);
		}
开发者ID:nlhepler,项目名称:mono,代码行数:19,代码来源:SignedCmsTest.cs

示例10: SignMsg

        public static byte[] SignMsg(int hashAlg,
                    byte[] msg,
                    X509Certificate2 signerCert)
        {
            //  Place message in a ContentInfo object.
            //  This is required to build a SignedCms object.
            ContentInfo contentInfo = new ContentInfo(msg);

            //  Instantiate SignedCms object with the ContentInfo above.
            //  Has default SubjectIdentifierType IssuerAndSerialNumber.
            //  Has default Detached property value false, so message is
            //  included in the encoded SignedCms.
            SignedCms signedCms = new SignedCms(contentInfo, true);

            //  Formulate a CmsSigner object, which has all the needed
            //  characteristics of the signer.

            CmsSigner cmsSigner = new CmsSigner(signerCert);

            //  Sign the PKCS #7 message.
            signedCms.ComputeSignature(cmsSigner, false);
            //  Encode the PKCS #7 message.
            return signedCms.Encode();
        }
开发者ID:bluecrystalsign,项目名称:bluecrystal-signer-DESCONTINUADO-,代码行数:24,代码来源:IttruActiveXObject.cs

示例11: SignProject

        internal byte[] SignProject(ExcelVbaProject proj)
        {
            if (!Certificate.HasPrivateKey)
            {
                //throw (new InvalidOperationException("The certificate doesn't have a private key"));
                Certificate = null;
                return null;
            }
            var hash = GetContentHash(proj);

            BinaryWriter bw = new BinaryWriter(new MemoryStream());
            bw.Write((byte)0x30); //Constructed Type
            bw.Write((byte)0x32); //Total length
            bw.Write((byte)0x30); //Constructed Type
            bw.Write((byte)0x0E); //Length SpcIndirectDataContent
            bw.Write((byte)0x06); //Oid Tag Indentifier
            bw.Write((byte)0x0A); //Lenght OId
            bw.Write(new byte[] { 0x2B, 0x06, 0x01, 0x04, 0x01, 0x82, 0x37, 0x02, 0x01, 0x1D }); //Encoded Oid 1.3.6.1.4.1.311.2.1.29
            bw.Write((byte)0x04);   //Octet String Tag Identifier
            bw.Write((byte)0x00);   //Zero length

            bw.Write((byte)0x30); //Constructed Type (DigestInfo)
            bw.Write((byte)0x20); //Length DigestInfo
            bw.Write((byte)0x30); //Constructed Type (Algorithm)
            bw.Write((byte)0x0C); //length AlgorithmIdentifier
            bw.Write((byte)0x06); //Oid Tag Indentifier
            bw.Write((byte)0x08); //Lenght OId
            bw.Write(new byte[] { 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x02, 0x05 }); //Encoded Oid for 1.2.840.113549.2.5 (AlgorithmIdentifier MD5)
            bw.Write((byte)0x05);   //Null type identifier
            bw.Write((byte)0x00);   //Null length
            bw.Write((byte)0x04);   //Octet String Identifier
            bw.Write((byte)hash.Length);   //Hash length
            bw.Write(hash);                //Content hash

            ContentInfo contentInfo = new ContentInfo(((MemoryStream)bw.BaseStream).ToArray());
            contentInfo.ContentType.Value = "1.3.6.1.4.1.311.2.1.4";
            Verifier = new SignedCms(contentInfo);
            var signer = new CmsSigner(Certificate);
            Verifier.ComputeSignature(signer, false);
            return Verifier.Encode();
        }
开发者ID:ylatuya,项目名称:EPPlus,代码行数:41,代码来源:ExcelVBASignature.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: 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

示例14: SignManifestFile

        private void SignManifestFile(PassGeneratorRequest request)
        {
            Trace.TraceInformation("Signing the manifest file...");

            try
            {
                ContentInfo contentInfo = new ContentInfo(manifestFile);

                SignedCms signing = new SignedCms(contentInfo, true);

                CmsSigner signer = new CmsSigner(SubjectIdentifierType.SubjectKeyIdentifier, passCert)
                {
                    IncludeOption = X509IncludeOption.None
                };

                Trace.TraceInformation("Fetching Apple Certificate for signing..");
                Trace.TraceInformation("Constructing the certificate chain..");
                signer.Certificates.Add(appleCert);
                signer.Certificates.Add(passCert);

                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:edudutra,项目名称:dotnet-passbook,代码行数:35,代码来源:PassGenerator.cs

示例15: CreateSigned

        /// <summary>
        /// Export the given certificate collection as a SIGNED bundle 
        /// </summary>
        /// <param name="certs">Certificates to place in the bundle</param>
        /// <param name="signingCert">Signing certificate</param>
        /// <returns>p7s data</returns>
        public static byte[] CreateSigned(X509Certificate2Collection certs, X509Certificate2 signingCert)
        {
            if (signingCert == null || !signingCert.HasPrivateKey)
            {
                throw new ArgumentException("signingCert");
            }
            
            byte[] p7bData = certs.Export(X509ContentType.Pkcs7);

            SignedCms cms = new SignedCms(new ContentInfo(p7bData), false);
            CmsSigner signer = new CmsSigner(signingCert);
            signer.IncludeOption = X509IncludeOption.EndCertOnly;
            cms.ComputeSignature(signer, true);

            return cms.Encode();
        }
开发者ID:DM-TOR,项目名称:nhin-d,代码行数:22,代码来源:AnchorBundle.cs


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