public void T1_ValidSignature ()
		{
			byte[] data = GetData ("SignedValidSignaturesTest1.eml");
			SignedCms cms = new SignedCms ();
			cms.Decode (data);
			Assert.IsTrue (CheckHash (cms), "CheckHash");
			Assert.IsTrue (CheckSignature (cms), "CheckSignature");

			X509Certificate2 ee = GetCertificate ("ValidCertificatePathTest1EE.crt");
			// certificates aren't in any particuliar order
			Assert.IsTrue (cms.Certificates.Contains (ee), "EE");
			Assert.IsTrue (cms.Certificates.Contains (GoodCACert), "GoodCACert");
			Assert.IsFalse (cms.Detached, "Detached");
			Assert.AreEqual (1, cms.Version, "Version");
			Assert.AreEqual ("1.2.840.113549.1.7.1", cms.ContentInfo.ContentType.Value, "ContentInfo.Oid");
			Assert.AreEqual ("43-6F-6E-74-65-6E-74-2D-54-79-70-65-3A-20-74-65-78-74-2F-70-6C-61-69-6E-3B-20-63-68-61-72-73-65-74-3D-69-73-6F-2D-38-38-35-39-2D-31-0D-0A-43-6F-6E-74-65-6E-74-2D-54-72-61-6E-73-66-65-72-2D-45-6E-63-6F-64-69-6E-67-3A-20-37-62-69-74-0D-0A-0D-0A-54-68-69-73-20-69-73-20-61-20-73-61-6D-70-6C-65-20-73-69-67-6E-65-64-20-6D-65-73-73-61-67-65-2E", BitConverter.ToString (cms.ContentInfo.Content), "ContentInfo.Content");
			Assert.AreEqual (1, cms.SignerInfos.Count, "SignerInfos.Count");
			Assert.AreEqual (ee, cms.SignerInfos[0].Certificate, "SignerInfos[0].Certificate");
			Assert.AreEqual (0, cms.SignerInfos[0].CounterSignerInfos.Count, "SignerInfos[0].CounterSignerInfos.Count");
			Assert.AreEqual ("1.3.14.3.2.26", cms.SignerInfos[0].DigestAlgorithm.Value, "cms.SignerInfos[0].DigestAlgorithm");
			Assert.AreEqual (0, cms.SignerInfos[0].SignedAttributes.Count, "SignerInfos[0].SignedAttributes.Count");
			Assert.AreEqual (SubjectIdentifierType.IssuerAndSerialNumber, cms.SignerInfos[0].SignerIdentifier.Type, "SignerInfos[0].SignerIdentifier.Type");
			X509IssuerSerial xis = (X509IssuerSerial) cms.SignerInfos[0].SignerIdentifier.Value;
			Assert.AreEqual ("CN=Good CA, O=Test Certificates, C=US", xis.IssuerName, "SignerInfos[0].SignerIdentifier.Value.IssuerName");
			Assert.AreEqual ("01", xis.SerialNumber, "SignerInfos[0].SignerIdentifier.Value.SerialNumber");
			Assert.AreEqual (0, cms.SignerInfos[0].UnsignedAttributes.Count, "SignerInfos[0].UnsignedAttributes.Count");
			Assert.AreEqual (1, cms.SignerInfos[0].Version, "SignerInfos[0].Version");
		}
Ejemplo n.º 2
2
		private void DefaultProperties (SignedCms sp, int version) 
		{
			// unaffected by constructors
			Assert.AreEqual (0, sp.Certificates.Count, "Certificates");
			Assert.AreEqual (0, sp.SignerInfos.Count, "SignerInfos");
			Assert.AreEqual (version, sp.Version, "Version");
		}
Ejemplo n.º 3
1
        protected string CheckSig()
        {
            var formData = Request.Form;
            var text = formData["txtSign"];
            var sig = formData["txtSig"];

            string output = "INVALID!";

            if (!string.IsNullOrEmpty(sig))
            {
                try
                {
                    ContentInfo contentInfo = new ContentInfo(Encoding.UTF8.GetBytes(text));

                    SignedCms signedCms = new SignedCms(contentInfo, true);

                    signedCms.Decode(Convert.FromBase64String(sig));

                    // This checks if the signature is valid, but doensn't actually verify the cert (TODO)
                    signedCms.CheckSignature(true);

                    output = "Signature valid.";

                    signedCms.CheckSignature(false);

                    output += "<br>Cert valid";
                }
                catch (Exception e)
                {
                    output += "<br>" + e.ToString();
                }
            }

            return output;
        }
Ejemplo n.º 4
1
        public bool ValidateToken(byte[] token, byte[] nonce, byte[] certificate, byte[] signature)
        {
            SignedCms cms = new SignedCms();
            cms.Decode(certificate);

            var certificates = cms.Certificates.Cast<X509Certificate2>().ToArray();

            var leaf = certificates.Single(cert => cert.Extensions.Cast<X509Extension>().Any(usage =>
            {
                var eku = usage as X509EnhancedKeyUsageExtension;
                if (eku != null)
                {
                    return eku.EnhancedKeyUsages.Cast<Oid>().Any(oid => oid.Value == "1.3.6.1.4.1.311.10.5.40");
                }
                return false;
            }));

            var signedData = nonce.Concat(token).ToArray();

            var publicKeyProvider = leaf.PublicKey.Key as System.Security.Cryptography.RSACryptoServiceProvider;

            return publicKeyProvider.VerifyData(signedData, CryptoConfig.MapNameToOID("SHA1"), signature);

            // not working either (same results)
            //
            //SHA1Managed hash = new SHA1Managed();
            //byte[] hashedData;
            //hashedData = hash.ComputeHash(signedData);

            //if (!publicKeyProvider.VerifyHash(hashedData, CryptoConfig.MapNameToOID("SHA1"), signature))
            //    throw new Exception("Invalid or Corrupted HardwareToken");
        }
Ejemplo n.º 5
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);
            }
        }
 internal SignerInfo(SignedCms signedCms, System.Security.Cryptography.SafeLocalAllocHandle pbCmsgSignerInfo)
 {
     this.m_signedCms = signedCms;
     this.m_parentSignerInfo = null;
     this.m_encodedSignerInfo = null;
     this.m_pbCmsgSignerInfo = pbCmsgSignerInfo;
     this.m_cmsgSignerInfo = (System.Security.Cryptography.CAPI.CMSG_SIGNER_INFO) Marshal.PtrToStructure(pbCmsgSignerInfo.DangerousGetHandle(), typeof(System.Security.Cryptography.CAPI.CMSG_SIGNER_INFO));
 }
Ejemplo n.º 8
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);
 }
Ejemplo n.º 9
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();
 }
Ejemplo n.º 10
0
        internal SignerInfo (SignedCms signedCms, SafeLocalAllocHandle pbCmsgSignerInfo) {
            // Sanity check.
            Debug.Assert(signedCms != null && pbCmsgSignerInfo != null && !pbCmsgSignerInfo.IsInvalid);

            m_signedCms = signedCms;
            m_parentSignerInfo = null;
            m_encodedSignerInfo = null;
            m_pbCmsgSignerInfo = pbCmsgSignerInfo;
            m_cmsgSignerInfo = (CAPI.CMSG_SIGNER_INFO) Marshal.PtrToStructure(pbCmsgSignerInfo.DangerousGetHandle(), typeof(CAPI.CMSG_SIGNER_INFO));
        }
        /// <summary>
        /// Gets certificates contained in pkcs 7.
        /// </summary>
        /// <returns>Returns certificates contained in pkcs 7. Returns null if no certificates.</returns>
        public X509Certificate2Collection GetCertificates()
        {
            if(this.Data == null){
                return null;
            }

            SignedCms signedCms = new SignedCms();
            signedCms.Decode(this.Data);

            return signedCms.Certificates;
        }
Ejemplo n.º 12
0
        public static void CheckSig(byte[] sig, byte[] data)
        {
            ContentInfo contentInfo = new ContentInfo(data);

            SignedCms signedCms = new SignedCms(contentInfo, true);

            signedCms.Decode(sig);

            // This checks if the signature is valid, but doensn't actually verify the cert (TODO)
            signedCms.CheckSignature(true);

            signedCms.CheckSignature(false);
        }
Ejemplo n.º 13
0
 public static bool VerifySign(byte[] data)
 {
     try
     {
         SignedCms signed = new SignedCms();
         signed.Decode(data);
     }
     catch
     {
         return false; // Arquivo não assinado
     }
     return true;
 }
Ejemplo n.º 14
0
 public bool Verify(byte[] data, byte[] signature)
 {
     var signedCms = new SignedCms();
     signedCms.Decode(signature);
     try
     {
         signedCms.CheckSignature(_certificate2Collection, false);
     }
     catch(Exception e)
     {
         return false;
     }
     return signedCms.ContentInfo.Content.SequenceEqual(_md5.ComputeHash(data));
 }
        /// <summary>
        /// Gets signed mime content. Value null means no content.
        /// </summary>
        /// <returns>Returns signed mime content. Value null means no content.</returns>
        /// <remarks>This method is valid only if <b>Content-Type</b> parameter <b>smime-type=signed-data</b>.</remarks>
        /// <exception cref="InvalidOperationException">Is raised when <b>smime-type != signed-data</b>.</exception>
        public MIME_Message GetSignedMime()
        {
            if(!string.Equals(this.Entity.ContentType.Parameters["smime-type"],"signed-data",StringComparison.InvariantCultureIgnoreCase)){
                throw new InvalidOperationException("The VerifySignature method is only valid if Content-Type parameter smime-type=signed-data.");
            }

            if(this.Data != null){
                SignedCms signedCms = new SignedCms();
                signedCms.Decode(this.Data);

                return MIME_Message.ParseFromStream(new MemoryStream(signedCms.ContentInfo.Content));
            }
            else{
                return null;
            }
        }
Ejemplo n.º 16
0
        public static String CheckFileSignature(ContentInfo content, byte[] signature)
        {
            var verifyCms = new SignedCms(content, true);
            verifyCms.Decode(signature);

            var cert = verifyCms.SignerInfos[0].Certificate;

            try
            {
                verifyCms.CheckSignature(new X509Certificate2Collection(cert), false);
                return @"Signature is valid";
            }
            catch (CryptographicException)
            {
                return @"Signature is not valid for content";
            }
        }
 internal unsafe SignerInfo(SignedCms signedCms, SignerInfo parentSignerInfo, byte[] encodedSignerInfo)
 {
     uint cbDecodedValue = 0;
     System.Security.Cryptography.SafeLocalAllocHandle invalidHandle = System.Security.Cryptography.SafeLocalAllocHandle.InvalidHandle;
     fixed (byte* numRef = encodedSignerInfo)
     {
         if (!System.Security.Cryptography.CAPI.DecodeObject(new IntPtr(500L), new IntPtr((void*) numRef), (uint) encodedSignerInfo.Length, out invalidHandle, out cbDecodedValue))
         {
             throw new CryptographicException(Marshal.GetLastWin32Error());
         }
     }
     this.m_signedCms = signedCms;
     this.m_parentSignerInfo = parentSignerInfo;
     this.m_encodedSignerInfo = (byte[]) encodedSignerInfo.Clone();
     this.m_pbCmsgSignerInfo = invalidHandle;
     this.m_cmsgSignerInfo = (System.Security.Cryptography.CAPI.CMSG_SIGNER_INFO) Marshal.PtrToStructure(invalidHandle.DangerousGetHandle(), typeof(System.Security.Cryptography.CAPI.CMSG_SIGNER_INFO));
 }
        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();
        }
Ejemplo n.º 19
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;
        }
        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;
        }
Ejemplo n.º 21
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="message"></param>
        /// <param name="signingCertificate"></param>
        /// <param name="encryptionCertificate"></param>
        /// <returns></returns>
        internal static byte[] GetSignature(Byte[] message, X509Certificate2 signingCertificate, X509Certificate2 encryptionCertificate)
        {
            SignedCms signedCms = new SignedCms(new ContentInfo(message), true);

            CmsSigner cmsSigner = new CmsSigner(SubjectIdentifierType.IssuerAndSerialNumber, signingCertificate);
            cmsSigner.IncludeOption = X509IncludeOption.WholeChain;

            if (encryptionCertificate != null)
            {
                cmsSigner.Certificates.Add(encryptionCertificate);
            }

            Pkcs9SigningTime signingTime = new Pkcs9SigningTime();
            cmsSigner.SignedAttributes.Add(signingTime);

            signedCms.ComputeSignature(cmsSigner, false);

            return signedCms.Encode();
        }
Ejemplo n.º 22
0
        internal static SignedCms RequestTimestamp(byte[] data, string hashAlgorithmOid, Uri timestampingAuthorityUrl)
        {
            var para = new CRYPT_TIMESTAMP_PARA()
            {
                fRequestCerts = true
            };

            IntPtr unmanagedContext = IntPtr.Zero;
            byte[] encodedResponse;
            try
            {
                NativeUtils.ThrowIfFailed(NativeMethods.CryptRetrieveTimeStamp(
                    wszUrl: timestampingAuthorityUrl.ToString(),
                    dwRetrievalFlags: NativeMethods.TIMESTAMP_VERIFY_CONTEXT_SIGNATURE,
                    dwTimeout: 5 * 1000 /* 5 second timeout */,
                    pszHashId: hashAlgorithmOid,
                    pPara: ref para,
                    pbData: data,
                    cbData: (uint)data.Length,
                    ppTsContext: out unmanagedContext,
                    ppTsSigner: IntPtr.Zero,
                    phStore: IntPtr.Zero));

                // Copy the encoded response out
                var context = (CRYPT_TIMESTAMP_CONTEXT)Marshal.PtrToStructure(unmanagedContext, typeof(CRYPT_TIMESTAMP_CONTEXT));
                encodedResponse = new byte[context.cbEncoded];
                Marshal.Copy(context.pbEncoded, encodedResponse, 0, (int)context.cbEncoded);
            }
            finally
            {
                if (unmanagedContext != IntPtr.Zero)
                {
                    NativeMethods.CryptMemFree(unmanagedContext);
                }
            }

            SignedCms cms = new SignedCms();
            cms.Decode(encodedResponse);
            return cms;
        }
Ejemplo n.º 23
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
            };
        }
Ejemplo n.º 24
0
        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);
            }
        }
Ejemplo n.º 25
0
        internal unsafe SignerInfo (SignedCms signedCms, SignerInfo parentSignerInfo, byte[] encodedSignerInfo) {
            // Sanity check.
            Debug.Assert(signedCms != null && encodedSignerInfo != null && encodedSignerInfo.Length > 0);

            uint cbCmsgSignerInfo = 0;
            SafeLocalAllocHandle pbCmsgSignerInfo = SafeLocalAllocHandle.InvalidHandle;

            fixed (byte * pEncodedSignerInfo = &encodedSignerInfo[0]) {
                if (!CAPI.DecodeObject(new IntPtr(CAPI.PKCS7_SIGNER_INFO),
                                       new IntPtr(pEncodedSignerInfo),
                                       (uint) encodedSignerInfo.Length,
                                       out pbCmsgSignerInfo,
                                       out cbCmsgSignerInfo))
                    throw new CryptographicException(Marshal.GetLastWin32Error());
            }

            m_signedCms = signedCms;
            m_parentSignerInfo = parentSignerInfo;
            m_encodedSignerInfo = (byte[]) encodedSignerInfo.Clone();
            m_pbCmsgSignerInfo = pbCmsgSignerInfo;
            m_cmsgSignerInfo = (CAPI.CMSG_SIGNER_INFO) Marshal.PtrToStructure(pbCmsgSignerInfo.DangerousGetHandle(), typeof(CAPI.CMSG_SIGNER_INFO));
        }
Ejemplo n.º 26
0
        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);
                }
            }
        }
Ejemplo n.º 27
0
        public static bool VerifyDetached(byte[] data, byte[] signature)
        {
            ContentInfo content = new ContentInfo(data);

            SignedCms signedMessage = new SignedCms(content, true);

            signedMessage.Decode(signature);

            try
            {
                signedMessage.CheckSignature(false);
                return true;
            }
            catch
            {
                return false;
            }
        }
Ejemplo n.º 28
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()
                });
            }
        }
Ejemplo n.º 29
0
        private Rfc3161RequestResponseStatus ValidateResponse(
            Rfc3161TimestampToken token,
            bool shouldThrow)
        {
            Debug.Assert(token != null);

            // This method validates the acceptance criteria sprinkled throughout the
            // field descriptions in https://tools.ietf.org/html/rfc3161#section-2.4.1 and
            // https://tools.ietf.org/html/rfc3161#section-2.4.2

            if (!token.VerifyHash(GetMessageHash().Span, HashAlgorithmId.Value))
            {
                if (shouldThrow)
                {
                    throw new CryptographicException(SR.Cryptography_BadHashValue);
                }

                return(Rfc3161RequestResponseStatus.HashMismatch);
            }

            Rfc3161TimestampTokenInfo tokenInfo = token.TokenInfo;

            // We only understand V1 messaging and validation
            if (tokenInfo.Version != 1)
            {
                if (shouldThrow)
                {
                    throw new CryptographicException(SR.Cryptography_TimestampReq_BadResponse);
                }

                return(Rfc3161RequestResponseStatus.VersionTooNew);
            }

            // reqPolicy is what the policy SHOULD be, so we can't reject it here.

            ReadOnlyMemory <byte>?requestNonce  = GetNonce();
            ReadOnlyMemory <byte>?responseNonce = tokenInfo.GetNonce();

            // The RFC says that if a nonce was in the request it MUST be present in
            // the response and it MUST be equal.
            //
            // It does not say that if no nonce was requested that the response MUST NOT include one, so
            // don't check anything if no nonce was requested.
            if (requestNonce != null)
            {
                if (responseNonce == null ||
                    !requestNonce.Value.Span.SequenceEqual(responseNonce.Value.Span))
                {
                    if (shouldThrow)
                    {
                        throw new CryptographicException(SR.Cryptography_TimestampReq_BadNonce);
                    }

                    return(Rfc3161RequestResponseStatus.NonceMismatch);
                }
            }

            SignedCms tokenCms = token.AsSignedCms();

            if (RequestSignerCertificate)
            {
                // If the certificate was requested it
                // A) MUST be present in token.AsSignedCms().Certificates
                // B) the ESSCertID(2) identifier MUST be correct.
                //
                // Other certificates are permitted, and will not be validated.

                if (tokenCms.SignerInfos[0].Certificate == null)
                {
                    if (shouldThrow)
                    {
                        throw new CryptographicException(SR.Cryptography_TimestampReq_NoCertFound);
                    }

                    return(Rfc3161RequestResponseStatus.RequestedCertificatesMissing);
                }
            }
            else
            {
                // If no certificate was requested then the CMS Certificates collection
                // MUST be empty.

                if (tokenCms.Certificates.Count != 0)
                {
                    if (shouldThrow)
                    {
                        throw new CryptographicException(SR.Cryptography_TimestampReq_UnexpectedCertFound);
                    }

                    return(Rfc3161RequestResponseStatus.UnexpectedCertificates);
                }
            }

            return(Rfc3161RequestResponseStatus.Accepted);
        }
        private void GetSignature()
        {
            if (_vbaPart == null)
            {
                return;
            }
            var rel = _vbaPart.GetRelationshipsByType(schemaRelVbaSignature).FirstOrDefault();

            if (rel != null)
            {
                Uri  = UriHelper.ResolvePartUri(rel.SourceUri, rel.TargetUri);
                Part = _vbaPart.Package.GetPart(Uri);

                var          stream             = Part.GetStream();
                BinaryReader br                 = new BinaryReader(stream);
                uint         cbSignature        = br.ReadUInt32();
                uint         signatureOffset    = br.ReadUInt32(); //44 ??
                uint         cbSigningCertStore = br.ReadUInt32();
                uint         certStoreOffset    = br.ReadUInt32();
                uint         cbProjectName      = br.ReadUInt32();
                uint         projectNameOffset  = br.ReadUInt32();
                uint         fTimestamp         = br.ReadUInt32();
                uint         cbTimestampUrl     = br.ReadUInt32();
                uint         timestampUrlOffset = br.ReadUInt32();
                byte[]       signature          = br.ReadBytes((int)cbSignature);
                uint         version            = br.ReadUInt32();
                uint         fileType           = br.ReadUInt32();

                uint id = br.ReadUInt32();
                while (id != 0)
                {
                    uint encodingType = br.ReadUInt32();
                    uint length       = br.ReadUInt32();
                    if (length > 0)
                    {
                        byte[] value = br.ReadBytes((int)length);
                        switch (id)
                        {
                        //Add property values here...
                        case 0x20:
                            Certificate = new X509Certificate2(value);
                            break;

                        default:
                            break;
                        }
                    }
                    id = br.ReadUInt32();
                }
                uint   endel1 = br.ReadUInt32(); //0
                uint   endel2 = br.ReadUInt32(); //0
                ushort rgchProjectNameBuffer = br.ReadUInt16();
                ushort rgchTimestampBuffer   = br.ReadUInt16();
#if Core
                Verifier = new EnvelopedCms();
#else
                Verifier = new System.Security.Cryptography.Pkcs.SignedCms();
#endif
                Verifier.Decode(signature);
            }
            else
            {
                Certificate = null;
                Verifier    = null;
            }
        }
Ejemplo n.º 31
0
        /// <summary>
        /// Extracts the original message from the S/MIME envelope and exposes the SignedCms object containing signature informations via the Message.Signatures.Smime property.
        /// </summary>
        /// <returns>A Message object representing the message as it was before signing.</returns>
        /// <example>
        /// <code>
        /// [C#]
        /// 
        /// // We retrieved a Message object by some means and have a reference to it in variable message.
        /// Message originalMessage = message.SmimeDevelopeAndExposeSignature();
        /// 
        /// // Check the signature. The "true" argument indicates that we don't want to verify the signe's certificates at this time, but only the signature itself.
        /// try
        /// {
        ///     originalMessage.Signatures.Smime.CheckSignature(true);
        /// }
        /// catch(CryptographicException ex)
        /// {
        ///     // Signature is invalid, do something.
        /// }
        /// </code>
        /// </example>
        #if !PocketPC
        public Message SmimeDevelopeAndExposeSignature()
        {
            if (!this.HasSmimeSignature) throw new InvalidOperationException("This message doesn't seem to be signed, or the signing method is unknown.");
            else
            {
                SignedCms cms = new SignedCms();
                cms.Decode(this.PartTreeRoot.BinaryContent);

                Message sub = Parser.ParseMessage(cms.ContentInfo.Content);

                sub.Signatures.Smime = cms;

                return sub;
            }
        }
Ejemplo n.º 32
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;
        }
Ejemplo n.º 33
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;
        }
Ejemplo n.º 34
0
        public static bool IsTimestamped(string filename) {
            try {
                int encodingType;
                int contentType;
                int formatType;
                IntPtr certStore = IntPtr.Zero;
                IntPtr cryptMsg = IntPtr.Zero;
                IntPtr context = IntPtr.Zero;

                if (!WinCrypt.CryptQueryObject(
                    WinCrypt.CERT_QUERY_OBJECT_FILE,
                    Marshal.StringToHGlobalUni(filename),
                    WinCrypt.CERT_QUERY_CONTENT_FLAG_ALL,
                    WinCrypt.CERT_QUERY_FORMAT_FLAG_ALL,
                    0,
                    out encodingType,
                    out contentType,
                    out formatType,
                    ref certStore,
                    ref cryptMsg,
                    ref context)) {
                    throw new Win32Exception(Marshal.GetLastWin32Error());
                }

                //expecting contentType=10; CERT_QUERY_CONTENT_PKCS7_SIGNED_EMBED 
                //Logger.LogInfo(string.Format("Querying file '{0}':", filename));
                //Logger.LogInfo(string.Format("  Encoding Type: {0}", encodingType));
                //Logger.LogInfo(string.Format("  Content Type: {0}", contentType));
                //Logger.LogInfo(string.Format("  Format Type: {0}", formatType));
                //Logger.LogInfo(string.Format("  Cert Store: {0}", certStore.ToInt32()));
                //Logger.LogInfo(string.Format("  Crypt Msg: {0}", cryptMsg.ToInt32()));
                //Logger.LogInfo(string.Format("  Context: {0}", context.ToInt32()));

                // Get size of the encoded message.
                int cbData = 0;
                if (!WinCrypt.CryptMsgGetParam(
                    cryptMsg,
                    WinCrypt.CMSG_ENCODED_MESSAGE, //Crypt32.CMSG_SIGNER_INFO_PARAM,
                    0,
                    IntPtr.Zero,
                    ref cbData)) {
                    throw new Win32Exception(Marshal.GetLastWin32Error());
                }

                var vData = new byte[cbData];

                // Get the encoded message.
                if (!WinCrypt.CryptMsgGetParam(
                    cryptMsg,
                    WinCrypt.CMSG_ENCODED_MESSAGE, //Crypt32.CMSG_SIGNER_INFO_PARAM,
                    0,
                    vData,
                    ref cbData)) {
                    throw new Win32Exception(Marshal.GetLastWin32Error());
                }

                var signedCms = new SignedCms();
                signedCms.Decode(vData);

                foreach (var signerInfo in signedCms.SignerInfos) {
                    foreach (var unsignedAttribute in signerInfo.UnsignedAttributes) {
                        if (unsignedAttribute.Oid.Value == WinCrypt.szOID_RSA_counterSign) {
                            foreach (var counterSignInfo in signerInfo.CounterSignerInfos) {
                                foreach (var signedAttribute in counterSignInfo.SignedAttributes) {
                                    if (signedAttribute.Oid.Value == WinCrypt.szOID_RSA_signingTime) {
                                        var fileTime = new FILETIME();
                                        int fileTimeSize = Marshal.SizeOf(fileTime);
                                        IntPtr fileTimePtr = Marshal.AllocCoTaskMem(fileTimeSize);
                                        Marshal.StructureToPtr(fileTime, fileTimePtr, true);

                                        var buffdata = new byte[fileTimeSize];
                                        Marshal.Copy(fileTimePtr, buffdata, 0, fileTimeSize);

                                        var buffSize = (uint)buffdata.Length;

                                        uint encoding = WinCrypt.X509_ASN_ENCODING | WinCrypt.PKCS_7_ASN_ENCODING;

                                        var rsaSigningTime = (UIntPtr)(uint)Marshal.StringToHGlobalAnsi(WinCrypt.szOID_RSA_signingTime);

                                        byte[] pbData = signedAttribute.Values[0].RawData;
                                        var ucbData = (uint)pbData.Length;

                                        bool workie = WinCrypt.CryptDecodeObject(encoding, rsaSigningTime, pbData, ucbData, 0, buffdata, ref buffSize);

                                        if (workie) {
                                            IntPtr fileTimePtr2 = Marshal.AllocCoTaskMem(buffdata.Length);
                                            Marshal.Copy(buffdata, 0, fileTimePtr2, buffdata.Length);
                                            var fileTime2 = (FILETIME)Marshal.PtrToStructure(fileTimePtr2, typeof (FILETIME));

                                            long hFT2 = (((long)fileTime2.dwHighDateTime) << 32) + ((uint)fileTime2.dwLowDateTime);

                                            DateTime dte = DateTime.FromFileTime(hFT2);
                                            Console.WriteLine(dte.ToString());
                                        } else {
                                            throw new Win32Exception(Marshal.GetLastWin32Error());
                                        }
                                    }
                                }
                            }

                            return true;
                        }
                    }
                }
            } catch (Exception) {
                // no logging
            }

            return false;
        }
Ejemplo n.º 35
0
        public static bool TryDecode(ReadOnlyMemory <byte> source, out Rfc3161TimestampToken token, out int bytesConsumed)
        {
            bytesConsumed = 0;
            token         = null;

            try
            {
                ContentInfoAsn contentInfo =
                    AsnSerializer.Deserialize <ContentInfoAsn>(source, AsnEncodingRules.BER, out int bytesActuallyRead);

                // https://tools.ietf.org/html/rfc3161#section-2.4.2
                //
                // A TimeStampToken is as follows.  It is defined as a ContentInfo
                // ([CMS]) and SHALL encapsulate a signed data content type.
                //
                // TimeStampToken::= ContentInfo
                //   --contentType is id-signedData([CMS])
                //   --content is SignedData ([CMS])
                if (contentInfo.ContentType != Oids.Pkcs7Signed)
                {
                    return(false);
                }

                SignedCms cms = new SignedCms();
                cms.Decode(source);

                // The fields of type EncapsulatedContentInfo of the SignedData
                // construct have the following meanings:
                //
                // eContentType is an object identifier that uniquely specifies the
                // content type.  For a time-stamp token it is defined as:
                //
                // id-ct-TSTInfo  OBJECT IDENTIFIER ::= { iso(1) member-body(2)
                // us(840) rsadsi(113549) pkcs(1) pkcs-9(9) smime(16) ct(1) 4}
                //
                // eContent is the content itself, carried as an octet string.
                // The eContent SHALL be the DER-encoded value of TSTInfo.
                if (cms.ContentInfo.ContentType.Value != Oids.TstInfo)
                {
                    return(false);
                }

                // RFC3161:
                // The time-stamp token MUST NOT contain any signatures other than the
                // signature of the TSA.  The certificate identifier (ESSCertID) of the
                // TSA certificate MUST be included as a signerInfo attribute inside a
                // SigningCertificate attribute.

                // RFC5816 says that ESSCertIDv2 should be allowed instead.

                SignerInfoCollection signerInfos = cms.SignerInfos;

                if (signerInfos.Count != 1)
                {
                    return(false);
                }

                SignerInfo  signer = signerInfos[0];
                EssCertId   certId;
                EssCertIdV2 certId2;

                if (!TryGetCertIds(signer, out certId, out certId2))
                {
                    return(false);
                }

                X509Certificate2 signerCert = signer.Certificate;

                if (signerCert == null &&
                    signer.SignerIdentifier.Type == SubjectIdentifierType.IssuerAndSerialNumber)
                {
                    // If the cert wasn't provided, but the identifier was IssuerAndSerialNumber,
                    // and the ESSCertId(V2) has specified an issuerSerial value, ensure it's a match.
                    X509IssuerSerial issuerSerial = (X509IssuerSerial)signer.SignerIdentifier.Value;

                    if (certId?.IssuerSerial != null)
                    {
                        if (!IssuerAndSerialMatch(
                                certId.IssuerSerial.Value,
                                issuerSerial.IssuerName,
                                issuerSerial.SerialNumber))
                        {
                            return(false);
                        }
                    }

                    if (certId2?.IssuerSerial != null)
                    {
                        if (!IssuerAndSerialMatch(
                                certId2.IssuerSerial.Value,
                                issuerSerial.IssuerName,
                                issuerSerial.SerialNumber))
                        {
                            return(false);
                        }
                    }
                }

                Rfc3161TimestampTokenInfo tokenInfo;

                if (Rfc3161TimestampTokenInfo.TryDecode(cms.ContentInfo.Content, out tokenInfo, out _))
                {
                    if (signerCert != null &&
                        !CheckCertificate(signerCert, signer, certId, certId2, tokenInfo))
                    {
                        return(false);
                    }

                    token = new Rfc3161TimestampToken
                    {
                        _parsedDocument = cms,
                        _signerInfo     = signer,
                        _essCertId      = certId,
                        _essCertIdV2    = certId2,
                        TokenInfo       = tokenInfo,
                    };

                    bytesConsumed = bytesActuallyRead;
                    return(true);
                }
            }
            catch (CryptographicException)
            {
            }

            return(false);
        }