示例#1
0
        /// <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);
            }
        }
        /// <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
0
 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);
 }
示例#4
0
 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();
 }
        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();
        }
示例#6
0
        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;
        }
示例#7
0
        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[] 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);
            }
        }
示例#9
0
        /// <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;
        }
示例#10
0
		public void ComputeEmptySignature ()
		{
			SignedCms sp = new SignedCms ();
			sp.ComputeSignature ();
		}
示例#11
0
        /// <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;
        }
        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);
            }
        }
示例#13
0
        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();
        }
示例#14
0
        InputSigner IAvalaraReturnSigner.Sign(InputSigner inputSigner)
        {
            try
            {
                InputSigner objBookDetails = new InputSigner();

                List <X509Certificate2> certificates = new List <X509Certificate2>();
                X509Store store  = new X509Store(StoreName.My, StoreLocation.CurrentUser);
                X509Store store1 = new X509Store(StoreName.TrustedPublisher, StoreLocation.CurrentUser);
                store.Open(OpenFlags.OpenExistingOnly);
                foreach (X509Certificate2 cert in store.Certificates)
                {
                    certificates.Add(cert);
                }
                X509Certificate2           certificate = new X509Certificate2();
                X509Certificate2Collection cers        = store.Certificates.Find(X509FindType.FindBySubjectName, inputSigner.ClientCertificateName, false);
                if (cers.Count > 0)
                {
                    certificate = cers[0];
                }
                else
                {
                    return(new InputSigner()
                    {
                        Message = "Please connect your hardware digial signature (USB Token) Or Check the digital signature authority name you provided.",
                        ClientToolVersion = "1.0",
                        SignedPayload = string.Empty,
                        SignSucess = false,
                        ClientToolException = string.Empty
                    });
                }

                String      text        = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(inputSigner.SummaryPayload));
                ContentInfo contentInfo = new ContentInfo(System.Text.Encoding.UTF8.GetBytes(text));
                System.Security.Cryptography.Pkcs.SignedCms cms = new System.Security.Cryptography.Pkcs.SignedCms(contentInfo, false);
                CmsSigner signer = new CmsSigner(certificate);
                // signer.IncludeOption = X509IncludeOption.None;
                signer.DigestAlgorithm = new Oid("SHA256");
                cms.ComputeSignature(signer, false);
                byte[] signature = cms.Encode();

                return(new InputSigner()
                {
                    Message = "Payload Signed Sucessfully",
                    SignedPayload = Convert.ToBase64String(signature),
                    SummaryPayload = inputSigner.SummaryPayload,
                    ClientToolVersion = "1.0",
                    SignSucess = true,
                    ClientToolException = string.Empty
                });
            }
            catch (Exception ex)
            {
                return(new InputSigner()
                {
                    Message = "Payload Signed Sucessfylly",
                    SignedPayload = string.Empty,
                    SummaryPayload = inputSigner.SummaryPayload,
                    ClientToolVersion = "1.0",
                    SignSucess = true,
                    ClientToolException = ex.ToString()
                });
            }
        }
        /// <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);
        }
示例#16
0
 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;
 }
示例#17
0
        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);
            }
        }
示例#18
0
        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);
            }
        }
示例#19
0
        /// <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();
        }
示例#20
0
        //  Sign the message with the private key of the signer.
        private static byte[] SignMsg(Byte[] msg, X509Certificate2 signerCert, bool detached)
        {
            //  Place message in a ContentInfo object.
            //  This is required to build a SignedCms object.
            var contentInfo = new ContentInfo(msg);

            //  Instantiate SignedCms object with the ContentInfo above.
            //  Has default SubjectIdentifierType IssuerAndSerialNumber.
            var signedCms = new SignedCms(contentInfo, detached);

            //  Formulate a CmsSigner object for the signer.
            var cmsSigner = new CmsSigner(signerCert);

            // Include the following line if the top certificate in the
            // smartcard is not in the trusted list.
            cmsSigner.IncludeOption = X509IncludeOption.EndCertOnly;

            //  Sign the CMS/PKCS #7 message. The second argument is
            //  needed to ask for the pin.
            signedCms.ComputeSignature(cmsSigner, false);

            //  Encode the CMS/PKCS #7 message.
            return signedCms.Encode();
        }
示例#21
0
        /// <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);
        }
示例#22
0
        //  Sign the message with the private key of the signer.
        public byte[] SignMsg(Byte[] msg, X509Certificate2 signerCert, bool detached)
        {
            //  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.
            SignedCms signedCms = new SignedCms(contentInfo, detached);

            //  Formulate a CmsSigner object for the signer.
            CmsSigner cmsSigner = new CmsSigner(signerCert);

            // Include the following line if the top certificate in the
            // smartcard is not in the trusted list.
            cmsSigner.IncludeOption = X509IncludeOption.EndCertOnly;

            //  Sign the CMS/PKCS #7 message. The second argument is
            //  needed to ask for the pin.

            signedCms.ComputeSignature(cmsSigner, false);

            // TODO: Here the user can fail the password or cancel...what to do?

            //  Encode the CMS/PKCS #7 message.
            byte[] bb = signedCms.Encode();
            //return bb here if no timestamp is to be applied
            if (!Config.Stamp)
                return bb;

            CmsSignedData sd = new CmsSignedData(bb);
            SignerInformationStore signers = sd.GetSignerInfos();
            byte[] signature = null;
            SignerInformation signer = null;
            foreach (SignerInformation signer_ in signers.GetSigners()) {
                signer = signer_;
                break;
            }
            signature = signer.GetSignature();
            Org.BouncyCastle.Asn1.Cms.AttributeTable at = new Org.BouncyCastle.Asn1.Cms.AttributeTable(GetTimestamp(signature));
            signer = SignerInformation.ReplaceUnsignedAttributes(signer, at);
            IList signerInfos = new ArrayList();
            signerInfos.Add(signer);
            sd = CmsSignedData.ReplaceSigners(sd, new SignerInformationStore(signerInfos));
            bb = sd.GetEncoded();
            return bb;
        }
		/// <summary>
		/// Sign the content using the specified signer.
		/// </summary>
		/// <remarks>
		/// Sign the content using the specified signer.
		/// </remarks>
		/// <returns>A new <see cref="MimeKit.MimePart"/> instance
		/// containing the detached signature data.</returns>
		/// <param name="signer">The signer.</param>
		/// <param name="digestAlgo">The digest algorithm to use for signing.</param>
		/// <param name="content">The content.</param>
		/// <exception cref="System.ArgumentNullException">
		/// <para><paramref name="signer"/> is <c>null</c>.</para>
		/// <para>-or-</para>
		/// <para><paramref name="content"/> is <c>null</c>.</para>
		/// </exception>
		/// <exception cref="System.ArgumentOutOfRangeException">
		/// <paramref name="digestAlgo"/> is out of range.
		/// </exception>
		/// <exception cref="System.NotSupportedException">
		/// The specified <see cref="DigestAlgorithm"/> is not supported by this context.
		/// </exception>
		/// <exception cref="CertificateNotFoundException">
		/// A signing certificate could not be found for <paramref name="signer"/>.
		/// </exception>
		/// <exception cref="System.Security.Cryptography.CryptographicException">
		/// An error occurred in the cryptographic message syntax subsystem.
		/// </exception>
		public override MimePart Sign (MailboxAddress signer, DigestAlgorithm digestAlgo, Stream content)
		{
			if (signer == null)
				throw new ArgumentNullException ("signer");

			if (content == null)
				throw new ArgumentNullException ("content");

			var contentInfo = new ContentInfo (ReadAllBytes (content));
			var cmsSigner = GetRealCmsSigner (signer, digestAlgo);
			var signed = new SignedCms (contentInfo, true);
			signed.ComputeSignature (cmsSigner);
			var signedData = signed.Encode ();

			return new ApplicationPkcs7Signature (new MemoryStream (signedData, false));
		}
示例#24
0
        /// <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;
        }
        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();
        }
示例#26
0
		/// <summary>
		/// Populates this CMS blob with the data from signing a code directory
		/// </summary>
		public void SignCodeDirectory(X509Certificate2 SigningCert, DateTime SigningTime, CodeDirectoryBlob CodeDirectory)
		{
			// Create a signer
			CmsSigner Signer = new CmsSigner(SigningCert);
			Signer.IncludeOption = X509IncludeOption.WholeChain;
			Signer.SignerIdentifierType = SubjectIdentifierType.IssuerAndSerialNumber;
			Signer.DigestAlgorithm = new Oid(CryptoConfig.MapNameToOID("SHA1"), "SHA1");

			// A Pkcs9ContentType and Pkcs9MessageDigest will automatically be added, and it fails to
			// compute a signature if they are added manually, so only the signing time needs to be added
			Signer.SignedAttributes.Add(new Pkcs9SigningTime(SigningTime));

			// Sign the data (in a detached manner, so only the digest of the CodeDirectory is
			// stored in the CMS blob and not the whole CodeDirectory blob)
			bool bDetached = true;
			bool bSilent = true;
			ContentInfo CodeDirContentInfo = new ContentInfo(CodeDirectory.GetBlobBytes());
			SignedCms CMS = new SignedCms(CodeDirContentInfo, bDetached);
			CMS.ComputeSignature(Signer, bSilent);

			MyData = CMS.Encode();
		}
示例#27
0
        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;
        }
示例#28
0
        /// <summary>
        /// Сформировать ЭП
        /// </summary>
        /// <param name="certificate"></param>
        /// <param name="data"></param>
        /// <param name="detached"></param>
        /// <returns></returns>
        public static byte[] Sign(X509Certificate2 certificate, byte[] data, bool detached)
        {
            // то что подписываем
            var contentInfo = new ContentInfo(data);
            var signedCms = new SignedCms(contentInfo, detached);
            // сертификато для подписания

            var cmsSigner = new CmsSigner(SubjectIdentifierType.IssuerAndSerialNumber, certificate);
            signedCms.ComputeSignature(cmsSigner, true);
            // подпись
            return signedCms.Encode();
        }
示例#29
0
        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;
        }
示例#30
0
		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);
		}
示例#31
0
        /// <summary>
        /// Attaches a clear signature to the message. It is advised to do so when the receiving party might not be S/MIME capable.
        /// The content of the message is still visible, i.e. the message isn't enveloped.
        /// </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.SmimeAttachSignatureBy(signer);
        /// </code>
        /// </example>
        public void SmimeAttachSignatureBy(CmsSigner signer)
        {
            string body = this.PartTreeRoot.ToMimeString();
            byte[] tosign = Encoding.ASCII.GetBytes(body.TrimEnd('\r', '\n') + "\r\n");

            SignedCms cms = new SignedCms(new ContentInfo(tosign), true);
            cms.ComputeSignature(signer);

            MimePart envelope = new MimePart();

            this.Signatures.Smime = cms;
            envelope.ContentType.MimeType = "multipart/signed";
            envelope.ContentType.Parameters.Add("protocol", "\"application/x-pkcs7-signature\"");
            envelope.ContentType.Parameters.Add("micalg", cms.SignerInfos[0].DigestAlgorithm.FriendlyName);
            string unique = Codec.GetUniqueString();
            string boundary = "---AU_MimePart_" + unique;
            envelope.ContentType.Parameters.Add("boundary", boundary);

            envelope.SubParts.Add(this.PartTreeRoot);
            envelope.SubParts.Add(MimePart.GetSignaturePart(cms));

            this.PartTreeRoot = envelope;

            this.ContentType = this.PartTreeRoot.ContentType;
            this.ContentDisposition = this.PartTreeRoot.ContentDisposition;
            this.ContentTransferEncoding = this.PartTreeRoot.ContentTransferEncoding;
        }
示例#32
0
		public void ComputeEmptySignatureCmsSigner () 
		{
			CmsSigner signer = new CmsSigner ();
			SignedCms sp = new SignedCms ();
			sp.ComputeSignature (signer);
		}