Example #1
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;
        }
Example #2
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);
        }
Example #3
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));
 }
Example #4
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";
            }
        }
Example #5
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
            };
        }
        private TimestampInformation GetTimestampInformation(X509Native.AXL_AUTHENTICODE_TIMESTAMPER_INFO timestamper,
                                                             XmlElement licenseNode) {
            Debug.Assert(licenseNode != null, "licenseNode != null");

            TimestampInformation timestamp = null;

            // If the timestamper is a trusted publisher, then CAPI has done the work for us;
            // If the leaf certificate is not explicitly a trusted publisher, CAPI will not process
            // the timestamp information so we will verify it ourselves. In any other case, we will
            // return no timestamp information.
            if (timestamper.dwError == (int)SignatureVerificationResult.Valid) {
                timestamp = new TimestampInformation(timestamper);
            }
            else if (timestamper.dwError == (int)SignatureVerificationResult.CertificateNotExplicitlyTrusted ||
                     timestamper.dwError == (int)SignatureVerificationResult.MissingSignature) {

                XmlElement timestampElement = licenseNode.SelectSingleNode("r:issuer/ds:Signature/ds:Object/as:Timestamp",
                                                                           m_namespaceManager) as XmlElement;
                if (timestampElement != null) {
                    // The timestamp is held as a parameter of a base64 encoded PKCS7 message in the signature
                    byte[] timestampBlob = Convert.FromBase64String(timestampElement.InnerText);

                    try {
                        SignedCms timestampCms = new SignedCms();
                        timestampCms.Decode(timestampBlob);
                        timestampCms.CheckSignature(true);

                        // The SignedCms class does not expose a way to read arbitrary properties from the
                        // message, nor does it expose the HCRYPTMSG to P/Invoke with. We cannot access the
                        // actual timestamp because of this, so for signatures which are not created by a
                        // trusted publisher, we will return a null timestamp. This should be corrected in
                        // v3 of the CLR, as we can extend SignedCms to have the properties we need to
                        // pull all of this information.
                        timestamp = null;
                    }
                    catch (CryptographicException e) {
                        timestamp = new TimestampInformation((SignatureVerificationResult)Marshal.GetHRForException(e));
                    }
                }
            }
            else {
                timestamp = null;
            }

            return timestamp;
        }
        /// <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);
        }
Example #8
0
 private X509Certificate2 CheckSignAndGetCertificate(FullDocumentInfo documentInfo, Sign sign)
 {
     var document = documentInfo.Document;
     if (document.NeedReceipt && IsNoticeRequired(documentInfo))
     {
         UserInput.Warning("Не удалось проверить подпись документа т.к. на него запрошено УОП");
         return null;
     }
     var contentInfo = new ContentInfo(GetDocumentContent(document));
     var signedCms = new SignedCms(contentInfo, true);
     try
     {
         // проверям подпись (действительность сервтификата не проверям для простоты)
         signedCms.Decode(sign.Raw);
         signedCms.CheckSignature(true);
     }
     catch (CryptographicException)
     {
         UserInput.Error("Подпись на документ {0} недействительна", document.Id);
         return null;
     }
     var certificate = signedCms.Certificates[0];
     return certificate;
 }
        public static byte[] VerifyAndRemoveSignature(byte[] data)
        {
            SignedCms signedMessage = new SignedCms();

            signedMessage.Decode(data);

            signedMessage.CheckSignature(false);

            foreach (SignerInfo signer in signedMessage.SignerInfos)
            {
                Console.WriteLine("Subject: {0}", signer.Certificate.Subject);
            }

            return signedMessage.ContentInfo.Content;
        }
        //  Verify the encoded SignedCms message and return a Boolean
        //  value that specifies whether the verification was successful.
        //  Also return the original message that was signed, which is
        //  available as part of the SignedCms message after it
        //  is decoded.
        public static bool VerifyMsg(byte[] encodedSignedCms,
            out byte[] origMsg)
        {
            //  Prepare a SignedCms object in which to decode
            //  and verify.
            SignedCms signedCms = new SignedCms();

            signedCms.Decode(encodedSignedCms);

            //  Catch a verification exception in the event you want to
            //  advise the message recipient that security actions
            //  might be appropriate.
            try
            {
                //  Verify signature. Do not validate signer
                //  certificate for the purposes of this example.
                //  Note that in a production environment, validating
                //  the signer certificate chain will probably be
                //  necessary.
                Console.Write("Checking signature on message ... ");
                signedCms.CheckSignature(true);
                Console.WriteLine("Done.");
            }
            catch (System.Security.Cryptography.CryptographicException e)
            {
                Console.WriteLine("VerifyMsg caught exception:  {0}",
                    e.Message);
                Console.WriteLine("The message may have been modified " +
                    "in transit or storage. Authenticity of the " +
                    "message is not guaranteed.");
                origMsg = null;
                return false;
            }

            origMsg = signedCms.ContentInfo.Content;

            return true;
        }
Example #11
0
            /// <summary>
            /// Load's and parses a signed message. The signed message should be in an attachment called smime.p7m
            /// </summary>
            /// <param name="storage"></param>
            private void LoadEncryptedAndMeabySignedMessage(NativeMethods.IStorage storage)
            {
                // Create attachment from attachment storage
                var attachment = new Attachment(new Storage(storage), null);

                if (attachment.FileName.ToUpperInvariant() != "SMIME.P7M")
                    throw new MRInvalidSignedFile(
                        "The signed file is not valid, it should contain an attachment called smime.p7m but it didn't");

                // If the message is signed then it always only contains one attachment called smime.p7m
                var signedCms = new SignedCms();
                signedCms.Decode(attachment.Data);

                try
                {
                    signedCms.CheckSignature(signedCms.Certificates, false);
                    SignatureIsValid = true;
                    foreach (var cryptographicAttributeObject in signedCms.SignerInfos[0].SignedAttributes)
                    {
                        if (cryptographicAttributeObject.Values[0] is Pkcs9SigningTime)
                        {
                            var pkcs9SigningTime = (Pkcs9SigningTime)cryptographicAttributeObject.Values[0];
                            SignedOn = pkcs9SigningTime.SigningTime.ToLocalTime();
                        }
                    }

                    var certificate = signedCms.SignerInfos[0].Certificate;
                    if (certificate != null)
                        SignedBy = certificate.GetNameInfo(X509NameType.SimpleName, false);
                }
                catch (CryptographicException)
                {
                    SignatureIsValid = false;
                }

                // Get the decoded attachment
                using (var memoryStream = new MemoryStream(signedCms.ContentInfo.Content))
                {
                    var eml = Mime.Message.Load(memoryStream);
                    _bodyText = eml.TextBody.GetBodyAsText();
                    _bodyHtml = eml.HtmlBody.GetBodyAsText();

                    foreach (var emlAttachment in eml.Attachments)
                        _attachments.Add(new Attachment(emlAttachment));
                }
            }
Example #12
0
		public void CheckSignatureDetachedSignedCms ()
		{
			string path = Path.Combine ("Test", "System.Security.Cryptography.Pkcs");
			var signedBytes = File.ReadAllBytes (Path.Combine (path, "detached.data"));
			var bytes = File.ReadAllBytes (Path.Combine (path, "detached.p7"));

			var oid = new Oid ("1.2.840.113549.1.7.2");
			var contentInfo = new ContentInfo (oid, signedBytes);
			var signedCms = new SignedCms (contentInfo, true);
			signedCms.Decode (bytes);
			signedCms.CheckSignature (true);
		}
Example #13
0
        /// <summary>
        /// Extract a list of MIME parts from a multipart/* MIME encoded message.
        /// </summary>
        /// <param name="contentType">Content Type of the outermost MIME part.</param>
        /// <param name="charSet">Character set of the outermost MIME part.</param>
        /// <param name="contentTransferEncoding">Encoding of the outermost MIME part.</param>
        /// <param name="body">The outermost MIME part's contents.</param>
        /// <param name="depth">The nesting layer of this MIME part.</param>
        /// <param name="processingFlags">Flags determining whether specialized properties are returned with a MailMessage.</param>
        public static List<MimePart> ExtractMIMEParts(string contentType, string charSet, string contentTransferEncoding, string body, MailMessageProcessingFlags processingFlags, int depth)
        {
            List<MimePart> mimeParts = new List<MimePart>();

            string contentTypeToUpper = contentType.ToUpper();
            if (contentTypeToUpper.StartsWith("MULTIPART/"))
            {
                // Prepare to process each part of the multipart/* message.
                int cursor = 0;

                // Prepend and append to the body with a carriage return and linefeed for consistent boundary matching.
                body = "\r\n" + body + "\r\n";

                // Determine the outermost boundary name.
                string boundaryName = Functions.ExtractMimeParameter(contentType, "boundary");
                int boundaryNameLength = boundaryName.Length;

                // Variables used for record keeping with signed S/MIME parts.
                int signatureBlock = -1;
                List<string> mimeBlocks = new List<string>();

                cursor = body.IndexOf("\r\n--" + boundaryName, 0, StringComparison.Ordinal);
                while (cursor > -1)
                {
                    // Calculate the end boundary of the current MIME part.
                    int mimeStartPosition = cursor + boundaryNameLength + 4;
                    int mimeEndPosition = body.IndexOf("\r\n--" + boundaryName, mimeStartPosition, StringComparison.Ordinal);
                    if (mimeEndPosition > -1 && (mimeEndPosition + boundaryNameLength + 6 <= body.Length))
                    {
                        string afterBoundaryEnd = body.Substring(mimeEndPosition + 4 + boundaryNameLength, 2);
                        if (afterBoundaryEnd == "\r\n" || afterBoundaryEnd == "--")
                        {
                            string mimeContents = body.Substring(mimeStartPosition, mimeEndPosition - mimeStartPosition);

                            // Extract the header portion of the current MIME part.
                            int mimeDivider = mimeContents.IndexOf("\r\n\r\n");
                            string mimeHeaders, mimeBody;
                            if (mimeDivider > -1)
                            {
                                mimeHeaders = mimeContents.Substring(0, mimeDivider);
                                mimeBody = mimeContents.Substring(mimeDivider + 4);
                            }
                            else
                            {
                                // The following is a workaround to handle malformed MIME bodies.
                                mimeHeaders = mimeContents;
                                mimeBody = "";

                                int linePos = 0, lastLinePos = 0;
                                while (linePos > -1)
                                {
                                    lastLinePos = linePos;
                                    linePos = mimeHeaders.IndexOf("\r\n", lastLinePos);
                                    if (linePos > -1)
                                    {
                                        string currentLine = mimeContents.Substring(lastLinePos, linePos - lastLinePos);
                                        if (currentLine.Length > 0 && currentLine.IndexOf(":") < 0)
                                        {
                                            mimeBody = mimeContents.Substring(lastLinePos + 2, mimeContents.Length - lastLinePos - 4);
                                            linePos = -1;
                                        }
                                        else
                                            linePos += 2;
                                    }
                                }
                            }

                            mimeBlocks.Add(mimeContents);

                            // Divide the MIME part's headers into its components.
                            string mimeCharSet = "", mimeContentDisposition = "", mimeContentID = "", mimeContentType = "", mimeContentTransferEncoding = "", mimeFileName = "";
                            ExtractMimeHeaders(mimeHeaders, out mimeContentType, out mimeCharSet, out mimeContentTransferEncoding, out mimeContentDisposition, out mimeFileName, out mimeContentID);

                            string mimeContentTypeToUpper = mimeContentType.ToUpper();
                            if (mimeContentTypeToUpper.StartsWith("MULTIPART/"))
                            {
                                // Recurse through embedded MIME parts.
                                List<MimePart> returnedMIMEParts = ExtractMIMEParts(mimeContentType, mimeCharSet, mimeContentTransferEncoding, mimeBody, processingFlags, depth + 1);
                                foreach (MimePart returnedMIMEPart in returnedMIMEParts)
                                    mimeParts.Add(returnedMIMEPart);
                            }
                            else
                            {
                                // Keep track of whether this MIME part's body has already been processed.
                                bool processed = false;

                                if (mimeContentTypeToUpper.StartsWith("APPLICATION/PKCS7-SIGNATURE") || mimeContentTypeToUpper.StartsWith("APPLICATION/X-PKCS7-SIGNATURE"))
                                {
                                    // Unless a flag has been set to include this *.p7s block, exclude it from attachments.
                                    if ((processingFlags & MailMessageProcessingFlags.IncludeSmimeSignedData) == 0)
                                        processed = true;

                                    // Remember the signature block to use for later verification.
                                    signatureBlock = mimeBlocks.Count() - 1;
                                }
                                else if (mimeContentTypeToUpper.StartsWith("APPLICATION/PKCS7-MIME") || mimeContentTypeToUpper.StartsWith("APPLICATION/X-PKCS7-MIME"))
                                {
                                    // Unless a flag has been set to include this *.p7m block, exclude it from attachments.
                                    processed = (processingFlags & MailMessageProcessingFlags.IncludeSmimeEncryptedEnvelopeData) == 0;

                                    // Decrypt the MIME part and recurse through embedded MIME parts.
                                    List<MimePart> returnedMIMEParts = ReturnSmimeDecryptedMimeParts(mimeContentType, mimeContentTransferEncoding, mimeBody, processingFlags, depth + 1);
                                    if (returnedMIMEParts != null)
                                    {
                                        foreach (MimePart returnedMIMEPart in returnedMIMEParts)
                                            mimeParts.Add(returnedMIMEPart);
                                    }
                                    else
                                    {
                                        // If we were unable to decrypt, return this MIME part as-is.
                                        processed = false;
                                    }
                                }
                                else if (mimeContentTypeToUpper.StartsWith("APPLICATION/MS-TNEF") || mimeFileName.ToUpper() == "WINMAIL.DAT")
                                {
                                    // Process the TNEF encoded message.
                                    processed = true;
                                    TnefEncoding tnef = new TnefEncoding(Convert.FromBase64String(mimeBody));

                                    // If we were unable to extract content from this MIME, include it as an attachment.
                                    if ((tnef.Body.Length < 1 && tnef.MimeAttachments.Count < 1) || (processingFlags & MailMessageProcessingFlags.IncludeWinMailData) > 0)
                                        processed = false;
                                    else
                                    {
                                        // Unless a flag has been set to include this winmail.dat block, exclude it from attachments.
                                        if ((processingFlags & MailMessageProcessingFlags.IncludeWinMailData) > 0)
                                        {
                                            if (!string.IsNullOrEmpty(tnef.Body))
                                                mimeParts.Add(new MimePart("winmail.dat", tnef.ContentType, "", "", mimeContentTransferEncoding, Encoding.UTF8.GetBytes(tnef.Body)));
                                        }

                                        foreach (MimePart mimePart in tnef.MimeAttachments)
                                            mimeParts.Add(mimePart);
                                    }
                                }
                                else if (mimeContentTypeToUpper == "MESSAGE/RFC822")
                                {
                                    if ((processingFlags & MailMessageProcessingFlags.IncludeNestedRFC822Messages) > 0)
                                    {
                                        // Recurse through the RFC822 container.
                                        processed = true;

                                        mimeDivider = mimeBody.IndexOf("\r\n\r\n");
                                        if (mimeDivider > -1)
                                        {
                                            mimeHeaders = Functions.UnfoldWhitespace(mimeBody.Substring(0, mimeDivider));
                                            mimeBody = mimeBody.Substring(mimeDivider + 4);

                                            mimeContentType = Functions.ReturnBetween(mimeHeaders, "Content-Type:", "\r\n").Trim();
                                            mimeContentTransferEncoding = Functions.ReturnBetween(mimeHeaders, "Content-Transfer-Encoding:", "\r\n").Trim();
                                            mimeCharSet = Functions.ExtractMimeParameter(mimeContentType, "charset").Replace("\"", "");

                                            List<MimePart> returnedMIMEParts = ExtractMIMEParts(mimeContentType, mimeCharSet, mimeContentTransferEncoding, mimeBody, processingFlags, depth + 1);
                                            foreach (MimePart returnedMIMEPart in returnedMIMEParts)
                                                mimeParts.Add(returnedMIMEPart);
                                        }
                                    }
                                }

                                if (!processed)
                                {
                                    // Decode and add the message to the MIME parts collection.
                                    switch (mimeContentTransferEncoding.ToLower())
                                    {
                                        case "base64":
                                            mimeBody = mimeBody.Replace("\r\n", "");
                                            if (mimeBody.Length % 4 != 0)
                                                mimeBody += new String('=', 4 - (mimeBody.Length % 4));

                                            mimeParts.Add(new MimePart(mimeFileName, mimeContentType, mimeCharSet, mimeContentID, mimeContentTransferEncoding, Convert.FromBase64String(mimeBody)));
                                            break;
                                        case "quoted-printable":
                                            mimeParts.Add(new MimePart(mimeFileName, mimeContentType, mimeCharSet, mimeContentID, mimeContentTransferEncoding, Functions.FromQuotedPrintable(mimeBody, mimeCharSet, null)));
                                            break;
                                        case "binary":
                                        case "7bit":
                                        case "8bit":
                                        default:
                                            mimeParts.Add(new MimePart(mimeFileName, mimeContentType, mimeCharSet, mimeContentID, mimeContentTransferEncoding, mimeBody));
                                            break;
                                    }
                                }
                            }
                        }
                        cursor = mimeEndPosition;
                    }
                    else
                        cursor = -1;
                }

                // If a PKCS signature was found and there's one other MIME part, verify the signature.
                if (signatureBlock > -1 && mimeBlocks.Count == 2)
                {
                    // Verify the signature and track the signing certificates.
                    X509Certificate2Collection signingCertificates;
                    if (VerifySmimeSignature(mimeBlocks[signatureBlock], mimeBlocks[1 - signatureBlock], out signingCertificates))
                    {
                        // Stamp each MIME part found so far as signed, and if relevant, triple wrapped.
                        foreach (MimePart mimePart in mimeParts)
                        {
                            mimePart.SmimeSigningCertificates = signingCertificates;

                            if (mimePart.SmimeSigned && mimePart.SmimeEncryptedEnvelope)
                                mimePart.SmimeTripleWrapped = true;

                            mimePart.SmimeSigned = true;
                        }
                    }
                }
            }
            else if (contentTypeToUpper.StartsWith("APPLICATION/MS-TNEF"))
            {
                // Process the TNEF encoded message.
                TnefEncoding tnef = new TnefEncoding(Convert.FromBase64String(body));

                // Unless a flag has been set to include this winmail.dat block, exclude it from attachments.
                if ((processingFlags & MailMessageProcessingFlags.IncludeWinMailData) > 0)
                {
                    if (!string.IsNullOrEmpty(tnef.Body))
                        mimeParts.Add(new MimePart("winmail.dat", tnef.ContentType, "", "", "", Encoding.UTF8.GetBytes(tnef.Body)));
                }

                foreach (MimePart mimePart in tnef.MimeAttachments)
                    mimeParts.Add(mimePart);
            }
            else if (contentTypeToUpper.StartsWith("APPLICATION/PKCS7-MIME") || contentTypeToUpper.StartsWith("APPLICATION/X-PKCS7-MIME"))
            {
                // Don't attempt to decrypt if this is a signed message only.
                if (contentType.IndexOf("smime-type=signed-data") < 0)
                {
                    // Unless a flag has been set to include this *.p7m block, exclude it from attachments.
                    if ((processingFlags & MailMessageProcessingFlags.IncludeSmimeEncryptedEnvelopeData) > 0)
                        mimeParts.Add(new MimePart("smime.p7m", contentType, "", "", "", body));

                    // Decrypt the MIME part and recurse through embedded MIME parts.
                    List<MimePart> returnedMIMEParts = ReturnSmimeDecryptedMimeParts(contentType, contentTransferEncoding, body, processingFlags, depth + 1);
                    if (returnedMIMEParts != null)
                    {
                        foreach (MimePart returnedMIMEPart in returnedMIMEParts)
                            mimeParts.Add(returnedMIMEPart);
                    }
                    else
                    {
                        // If we were unable to decrypt the message, pass it along as-is.
                        mimeParts.Add(new MimePart(Functions.ReturnBetween(contentType + ";", "name=", ";").Replace("\"", ""), contentType, "", "", contentTransferEncoding, body));
                    }
                }
                else
                {
                    // Hydrate the signature CMS object.
                    SignedCms signedCms = new SignedCms();

                    try
                    {
                        // Attempt to decode the signature block and verify the passed in signature.
                        signedCms.Decode(Convert.FromBase64String(body));
                        signedCms.CheckSignature(true);

                        string mimeContents = Encoding.UTF8.GetString(signedCms.ContentInfo.Content);

                        int mimeDivider = mimeContents.IndexOf("\r\n\r\n");
                        string mimeHeaders;
                        if (mimeDivider > -1)
                            mimeHeaders = mimeContents.Substring(0, mimeDivider);
                        else
                            mimeHeaders = mimeContents;

                        if (mimeHeaders.Length > 0)
                        {
                            // Extract the body portion of the current MIME part.
                            string mimeBody = mimeContents.Substring(mimeDivider + 4);

                            string mimeCharSet = "", mimeContentDisposition = "", mimeContentID = "", mimeContentType = "", mimeContentTransferEncoding = "", mimeFileName = "";
                            ExtractMimeHeaders(mimeHeaders, out mimeContentType, out mimeCharSet, out mimeContentTransferEncoding, out mimeContentDisposition, out mimeFileName, out mimeContentID);

                            List<MimePart> returnedMIMEParts = ExtractMIMEParts(mimeContentType, mimeCharSet, mimeContentTransferEncoding, mimeBody, processingFlags, depth + 1);
                            foreach (MimePart returnedMIMEPart in returnedMIMEParts)
                                mimeParts.Add(returnedMIMEPart);
                        }
                    }
                    catch
                    {
                        // If an exception occured, the signature could not be verified.
                    }
                }
            }
            else if (contentTypeToUpper == "MESSAGE/RFC822")
            {
                int mimeDivider = body.IndexOf("\r\n\r\n");
                if (mimeDivider > -1)
                {
                    string mimeHeaders = Functions.UnfoldWhitespace(body.Substring(0, mimeDivider));
                    string mimeBody = body.Substring(mimeDivider + 4);

                    string mimeContentType = Functions.ReturnBetween(mimeHeaders, "Content-Type:", "\r\n").Trim();
                    string mimeContentTransferEncoding = Functions.ReturnBetween(mimeHeaders, "Content-Transfer-Encoding:", "\r\n").Trim();
                    string mimeCharSet = Functions.ExtractMimeParameter(mimeContentType, "charset");

                    List<MimePart> returnedMIMEParts = ExtractMIMEParts(mimeContentType, mimeCharSet, mimeContentTransferEncoding, mimeBody, processingFlags, depth + 1);
                    foreach (MimePart returnedMIMEPart in returnedMIMEParts)
                        mimeParts.Add(returnedMIMEPart);
                }
            }
            else
            {
                // Decode the message.
                switch (contentTransferEncoding.ToLower())
                {
                    case "base64":
                        body = Functions.FromBase64(body);
                        break;
                    case "quoted-printable":
                        body = Functions.FromQuotedPrintable(body, charSet, null);
                        break;
                    case "binary":
                    case "7bit":
                    case "8bit":
                        break;
                }

                // If we're beyond the first layer, process the MIME part.  Otherwise, the message isn't MIME encoded.
                if (depth > 0)
                {
                    // Extract the headers from this MIME part.
                    string mimeHeaders;
                    int mimeDivider = body.IndexOf("\r\n\r\n");
                    if (mimeDivider > -1)
                        mimeHeaders = body.Substring(0, mimeDivider);
                    else
                        mimeHeaders = body;

                    // Divide the MIME part's headers into its components.
                    string mimeCharSet = "", mimeContentDisposition = "", mimeContentID = "", mimeContentType = "", mimeContentTransferEncoding = "", mimeFileName = "";
                    ExtractMimeHeaders(mimeHeaders, out mimeContentType, out mimeCharSet, out mimeContentTransferEncoding, out mimeContentDisposition, out mimeFileName, out mimeContentID);

                    // If this MIME part's content type is null, fall back to the overall content type.
                    if ((string.IsNullOrEmpty(mimeContentType) && !string.IsNullOrEmpty(contentType)) || (contentTypeToUpper.StartsWith("MESSAGE/PARTIAL")))
                    {
                        mimeCharSet = charSet;
                        mimeContentType = contentType;
                    }
                    else
                    {
                        if (body.Length > (mimeDivider + 4))
                            body = body.Substring(mimeDivider + 4);
                        else
                            body = "";
                    }

                    // Add the message to the MIME parts collection.
                    mimeParts.Add(new MimePart(mimeFileName, mimeContentType, mimeCharSet, mimeContentID, mimeContentTransferEncoding, body));
                }
                else
                {
                    // If the content type contains a character set, extract it.
                    charSet = Functions.NormalizeCharSet(Functions.ExtractMimeParameter(contentType, "charset"));

                    int semicolonPos = contentType.IndexOf(";");
                    if (semicolonPos > -1)
                        contentType = contentType.Substring(0, semicolonPos);

                    // Add the message as-is.
                    mimeParts.Add(new MimePart("", contentType, charSet, "", contentTransferEncoding, body));
                }
            }

            return mimeParts;
        }
Example #14
0
        internal static X509Certificate GetSignerCertificate(Stream stream)
        {
            stream.Seek(60, SeekOrigin.Begin);
            BinaryReader br = new BinaryReader(stream);
            int peSignatureOffset = br.ReadInt32();
            int checksumOffset = peSignatureOffset + 24 + 64;
            // seek to the IMAGE_OPTIONAL_HEADER
            stream.Seek(peSignatureOffset + 24, SeekOrigin.Begin);
            int certificateTableDataDirectoryOffset;
            switch (br.ReadUInt16())
            {
                case IMAGE_NT_OPTIONAL_HDR32_MAGIC:
                    certificateTableDataDirectoryOffset = peSignatureOffset + 24 + (64 + 4 * 8) + 8 * 4;
                    break;
                case IMAGE_NT_OPTIONAL_HDR64_MAGIC:
                    certificateTableDataDirectoryOffset = peSignatureOffset + 24 + (64 + 4 * 8 + 16) + 8 * 4;
                    break;
                default:
                    throw new BadImageFormatException();
            }
            stream.Seek(certificateTableDataDirectoryOffset, SeekOrigin.Begin);
            int certificateTableOffset = br.ReadInt32();
            int certificateTableLength = br.ReadInt32();

            stream.Seek(certificateTableOffset, SeekOrigin.Begin);
            int dwLength = br.ReadInt32();
            short wRevision = br.ReadInt16();
            short wCertificateType = br.ReadInt16();
            if (wRevision != WIN_CERT_REVISION_2_0)
            {
                return null;
            }
            if (wCertificateType != WIN_CERT_TYPE_PKCS_SIGNED_DATA)
            {
                return null;
            }
            byte[] buf = new byte[certificateTableLength - 8];
            stream.Read(buf, 0, buf.Length);

            SignedCms cms = new SignedCms();
            try
            {
                cms.Decode(buf);
                cms.CheckSignature(false);
            }
            catch (CryptographicException)
            {
                return null;
            }
            SignerInfo signerInfo = cms.SignerInfos[0];

            int[] offsets = new int[] { checksumOffset, certificateTableDataDirectoryOffset, certificateTableOffset };
            int[] lengths = new int[] { 4, 8, certificateTableLength };
            byte[] actualHash = ComputeHashWithSkip(stream, signerInfo.DigestAlgorithm.FriendlyName, offsets, lengths);
            byte[] requiredHash = DecodeASN1(cms.ContentInfo.Content, 0, 1, 1);

            if (requiredHash == null || actualHash.Length != requiredHash.Length)
            {
                return null;
            }

            for (int i = 0; i < actualHash.Length; i++)
            {
                if (actualHash[i] != requiredHash[i])
                {
                    return null;
                }
            }

            return signerInfo.Certificate;
        }
Example #15
0
		public bool CheckSignature (SignedCms cms)
		{
			try {
				cms.CheckSignature (false);
				return true;
			}
			catch {
			}
			return false;
		}
Example #16
0
		private void RoundTrip (byte[] encoded) 
		{
			SignedCms sp = new SignedCms ();
			sp.Decode (encoded);
			sp.CheckSignature (true);
		}
Example #17
0
		public void CheckSignatureCmsSignerUnknown () 
		{
			byte[] signature = { 0x30, 0x82, 0x03, 0x4C, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x07, 0x02, 0xA0, 0x82, 0x03, 0x3D, 0x30, 0x82, 0x03, 0x39, 0x02, 0x01, 0x01, 0x31, 0x0B, 0x30, 0x09, 0x06, 0x05, 0x2B, 0x0E, 0x03, 0x02, 0x1A, 0x05, 0x00, 0x30, 0x11, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x07, 0x01, 0xA0, 0x04, 0x04, 0x02, 0x05, 0x00, 0xA0, 0x82, 0x02, 0x2E, 0x30, 0x82, 0x02, 0x2A, 0x30, 0x82, 0x01, 0x97, 0xA0, 0x03, 0x02, 0x01, 0x02, 0x02, 0x10, 0x91, 0xC4, 0x4B, 0x0D, 0xB7, 0xD8, 0x10, 0x84, 0x42, 0x26, 0x71, 0xB3, 0x97, 0xB5, 0x00, 0x97, 0x30, 0x09, 0x06, 0x05, 0x2B, 0x0E, 0x03, 0x02, 0x1D, 0x05, 0x00, 0x30, 0x28, 0x31, 0x26, 0x30, 0x24, 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, 0x1D, 0x4D, 0x6F, 0x74, 0x75, 0x73, 0x20, 0x54, 0x65, 
				0x63, 0x68, 0x6E, 0x6F, 0x6C, 0x6F, 0x67, 0x69, 0x65, 0x73, 0x20, 0x69, 0x6E, 0x63, 0x2E, 0x28, 0x74, 0x65, 0x73, 0x74, 0x29, 0x30, 0x1E, 0x17, 0x0D, 0x30, 0x33, 0x30, 0x38, 0x31, 0x33, 0x30, 0x30, 0x34, 0x33, 0x34, 0x37, 0x5A, 0x17, 0x0D, 0x33, 0x39, 0x31, 0x32, 0x33, 0x31, 0x32, 0x33, 0x35, 0x39, 0x35, 0x39, 0x5A, 0x30, 0x13, 0x31, 0x11, 0x30, 0x0F, 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, 0x08, 0x46, 0x41, 0x52, 0x53, 0x43, 0x41, 0x50, 0x45, 0x30, 0x81, 0x9F, 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01, 0x05, 0x00, 0x03, 0x81, 0x8D, 0x00, 0x30, 0x81, 0x89, 0x02, 0x81, 0x81, 0x00, 0xD2, 0xCB, 0x47, 0x21, 0xF5, 0x62, 0xDD, 0x35, 0xBF, 0x1D, 0xEC, 0x9A, 0x4C, 0x07, 0x2C, 0x01, 0xF0, 0x28, 0xC2, 0x82, 0x17, 0x8E, 0x58, 0x32, 
				0xD5, 0x4C, 0xAC, 0x86, 0xB4, 0xC9, 0xEB, 0x21, 0x26, 0xF3, 0x22, 0x30, 0xC5, 0x7A, 0xA3, 0x5A, 0xDD, 0x53, 0xAB, 0x1C, 0x06, 0x3E, 0xB2, 0x13, 0xC4, 0x05, 0x1D, 0x95, 0x8B, 0x0A, 0x71, 0x71, 0x11, 0xA7, 0x47, 0x26, 0x61, 0xF1, 0x76, 0xBE, 0x35, 0x72, 0x32, 0xC5, 0xCB, 0x47, 0xA4, 0x22, 0x41, 0x1E, 0xAD, 0x29, 0x11, 0x0D, 0x39, 0x22, 0x0C, 0x79, 0x90, 0xC6, 0x52, 0xA1, 0x10, 0xF6, 0x55, 0x09, 0x4E, 0x51, 0x26, 0x47, 0x0E, 0x94, 0xE6, 0x81, 0xF5, 0x18, 0x6B, 0x99, 0xF0, 0x76, 0xF3, 0xB2, 0x4C, 0x91, 0xE9, 0xBA, 0x3B, 0x3F, 0x6E, 0x63, 0xDA, 0x12, 0xD1, 0x0B, 0x73, 0x0E, 0x12, 0xC7, 0x70, 0x77, 0x22, 0x03, 0x9D, 0x5D, 0x02, 0x03, 0x01, 0x00, 0x01, 0xA3, 0x72, 0x30, 0x70, 0x30, 0x13, 0x06, 0x03, 0x55, 0x1D, 0x25, 0x04, 0x0C, 0x30, 0x0A, 0x06, 0x08, 0x2B, 
				0x06, 0x01, 0x05, 0x05, 0x07, 0x03, 0x01, 0x30, 0x59, 0x06, 0x03, 0x55, 0x1D, 0x01, 0x04, 0x52, 0x30, 0x50, 0x80, 0x10, 0xAE, 0xD7, 0x80, 0x88, 0xA6, 0x3D, 0xBA, 0x50, 0xA1, 0x7E, 0x57, 0xE5, 0x40, 0xC9, 0x6F, 0xC5, 0xA1, 0x2A, 0x30, 0x28, 0x31, 0x26, 0x30, 0x24, 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, 0x1D, 0x4D, 0x6F, 0x74, 0x75, 0x73, 0x20, 0x54, 0x65, 0x63, 0x68, 0x6E, 0x6F, 0x6C, 0x6F, 0x67, 0x69, 0x65, 0x73, 0x20, 0x69, 0x6E, 0x63, 0x2E, 0x28, 0x74, 0x65, 0x73, 0x74, 0x29, 0x82, 0x10, 0x9D, 0xAE, 0xA3, 0x39, 0x47, 0x0E, 0xD4, 0xA2, 0x49, 0x78, 0xEA, 0x6C, 0xBA, 0x0D, 0xDE, 0x9C, 0x30, 0x09, 0x06, 0x05, 0x2B, 0x0E, 0x03, 0x02, 0x1D, 0x05, 0x00, 0x03, 0x81, 0x81, 0x00, 0x32, 0x8A, 0x7E, 0xAD, 0xE7, 0x67, 0x9E, 0x5C, 0x4C, 0xD8, 0x33, 0x59, 0x68, 0xCF, 
				0x94, 0xC0, 0x36, 0x47, 0x7A, 0xA7, 0x85, 0xC2, 0xDD, 0xD8, 0xDA, 0x11, 0x3C, 0x66, 0xC1, 0x83, 0xE3, 0xAB, 0x33, 0x06, 0x7C, 0xE3, 0x6A, 0x15, 0x72, 0xB8, 0x83, 0x3D, 0x0B, 0xAB, 0x3C, 0xEE, 0x75, 0x13, 0xBD, 0x5C, 0x96, 0x25, 0x56, 0x36, 0x05, 0xFA, 0xAE, 0xD4, 0xF4, 0xCF, 0x52, 0xEC, 0x11, 0xB5, 0xEA, 0x9F, 0x20, 0xA3, 0xC8, 0x34, 0x72, 0x59, 0x09, 0x51, 0xE7, 0x36, 0x87, 0x86, 0x86, 0x98, 0xB5, 0x30, 0x7B, 0xFB, 0x3D, 0xCC, 0x5E, 0xE8, 0xC9, 0x49, 0xE0, 0xC6, 0xEA, 0x02, 0x76, 0x01, 0xE0, 0xBB, 0x8A, 0x70, 0xEB, 0x07, 0x86, 0xE8, 0x04, 0xE7, 0x48, 0xE4, 0x6C, 0x90, 0xE6, 0x16, 0x42, 0xB4, 0xBB, 0xC0, 0xC4, 0x82, 0x5F, 0xF8, 0xFB, 0x7E, 0xB2, 0x9E, 0xC2, 0x78, 0x26, 0x86, 0x31, 0x81, 0xE1, 0x30, 0x81, 0xDE, 0x02, 0x01, 0x01, 0x30, 0x3C, 0x30, 0x28, 
				0x31, 0x26, 0x30, 0x24, 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, 0x1D, 0x4D, 0x6F, 0x74, 0x75, 0x73, 0x20, 0x54, 0x65, 0x63, 0x68, 0x6E, 0x6F, 0x6C, 0x6F, 0x67, 0x69, 0x65, 0x73, 0x20, 0x69, 0x6E, 0x63, 0x2E, 0x28, 0x74, 0x65, 0x73, 0x74, 0x29, 0x02, 0x10, 0x91, 0xC4, 0x4B, 0x0D, 0xB7, 0xD8, 0x10, 0x84, 0x42, 0x26, 0x71, 0xB3, 0x97, 0xB5, 0x00, 0x97, 0x30, 0x09, 0x06, 0x05, 0x2B, 0x0E, 0x03, 0x02, 0x1A, 0x05, 0x00, 0x30, 0x0D, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x0D, 0x01, 0x01, 0x01, 0x05, 0x00, 0x04, 0x81, 0x80, 0x45, 0x88, 0x80, 0x58, 0xC7, 0x4F, 0xE4, 0xD8, 0x88, 0xB0, 0xC0, 0x08, 0x70, 0x84, 0xCC, 0x8E, 0xA7, 0xF1, 0xA4, 0x07, 0x41, 0x14, 0x3E, 0xF5, 0xEA, 0x6E, 0x05, 0x75, 0xB8, 0x58, 0xAA, 0x5C, 0x0E, 0xFD, 0x7A, 0x07, 0x09, 0xE1, 0x80, 0x94, 
				0xBD, 0xAA, 0x45, 0xBB, 0x55, 0x9C, 0xC2, 0xD9, 0x72, 0x14, 0x4B, 0xA4, 0x64, 0xFB, 0x38, 0x9F, 0xD3, 0x22, 0xED, 0xB3, 0x0B, 0xF7, 0xAE, 0x4D, 0xE6, 0x65, 0x4D, 0x2A, 0x31, 0x18, 0xB5, 0xB4, 0x2D, 0x9E, 0x4E, 0xD7, 0xC0, 0x44, 0x5F, 0xAC, 0x43, 0xDC, 0x4F, 0x3D, 0x6D, 0x2C, 0x8C, 0xA1, 0xFE, 0x08, 0x38, 0xB7, 0xC4, 0xC4, 0x08, 0xDB, 0xF8, 0xF0, 0xC1, 0x55, 0x54, 0x49, 0x9D, 0xA4, 0x7F, 0x76, 0xDE, 0xF4, 0x29, 0x1C, 0x0B, 0x95, 0x10, 0x90, 0xB5, 0x0A, 0x9A, 0xEC, 0xCA, 0x89, 0x9A, 0x85, 0x92, 0x76, 0x78, 0x6F, 0x97, 0x67 };
			SignedCms sp = new SignedCms ();
			sp.Decode (signature);
			sp.CheckSignature (true);
			CheckSignatureProperties (sp, 1);
		}
Example #18
0
        /// <summary>
        /// Verify the S/MIME signature.
        /// </summary>
        /// <param name="signatureBlock">The S/MIME signature block.</param>
        /// <param name="body">The message's raw body.</param>
        /// <param name="signingCertificates">Collection of certificates to be used when signing.</param>
        public static bool VerifySmimeSignature(string signatureBlock, string body, out X509Certificate2Collection signingCertificates)
        {
            // Ignore MIME headers for the signature block.
            signatureBlock = signatureBlock.Substring(signatureBlock.IndexOf("\r\n\r\n") + 4);

            // Bypass any leading carriage returns and line feeds in the body.
            int bodyOffset = 0;
            while (body.Substring(bodyOffset).StartsWith("\r\n"))
                bodyOffset += 2;

            // Hydrate the signature CMS object.
            ContentInfo contentInfo = new ContentInfo(Encoding.UTF8.GetBytes(body.Substring(bodyOffset)));
            SignedCms signedCms = new SignedCms(contentInfo, true);

            try
            {
                // Attempt to decode the signature block and verify the passed in signature.
                signedCms.Decode(Convert.FromBase64String(signatureBlock));
                signedCms.CheckSignature(true);
                signingCertificates = signedCms.Certificates;

                return true;
            }
            catch
            {
                // If an exception occured, the signature could not be verified.
                signingCertificates = null;
                return false;
            }
        }
        /// <summary>
        /// Checks if signature is valid and data not altered.
        /// </summary>
        /// <returns>Returns true if signature is valid, otherwise false.</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 bool VerifySignature()
        {
            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.");
            }

            // Check this.Data exists.
            if(this.Data == null){
               return false;
            }

            try{
                SignedCms signedCms = new SignedCms();
                signedCms.Decode(this.Data);
                signedCms.CheckSignature(true);

                return true;
            }
            catch{
            }

            return false;
        }
Example #20
0
        private bool VerifySignatureTimestamp(XmlElement signatureNode, XmlNamespaceManager nsm, out DateTime verificationTime)
        {
            verificationTime = DateTime.Now;

            XmlElement node = signatureNode.SelectSingleNode("ds:Object/as:Timestamp", nsm) as XmlElement;
            if (node != null)
            {
                string encodedMessage = node.InnerText;

                if (!string.IsNullOrEmpty(encodedMessage))
                {
                    byte[] base64DecodedMessage = null;
                    try
                    {
                        base64DecodedMessage = Convert.FromBase64String(encodedMessage);
                    }
                    catch (FormatException)
                    {
                        _authenticodeSignerInfo.ErrorCode = Win32.TRUST_E_TIME_STAMP;
                        throw new CryptographicException(Win32.TRUST_E_TIME_STAMP);
                    }
                    if (base64DecodedMessage != null)
                    {
                        // Create a new, nondetached SignedCms message.
                        SignedCms signedCms = new SignedCms();
                        signedCms.Decode(base64DecodedMessage);

                        // Verify the signature without validating the 
                        // certificate.
                        signedCms.CheckSignature(true);

                        byte[] signingTime = null;
                        CryptographicAttributeObjectCollection caos = signedCms.SignerInfos[0].SignedAttributes;
                        foreach (CryptographicAttributeObject cao in caos)
                        {
                            if (0 == string.Compare(cao.Oid.Value, Win32.szOID_RSA_signingTime, StringComparison.Ordinal))
                            {
                                foreach (AsnEncodedData d in cao.Values)
                                {
                                    if (0 == string.Compare(d.Oid.Value, Win32.szOID_RSA_signingTime, StringComparison.Ordinal))
                                    {
                                        signingTime = d.RawData;
                                        Pkcs9SigningTime time = new Pkcs9SigningTime(signingTime);
                                        verificationTime = time.SigningTime;
                                        return true;
                                    }
                                }
                            }
                        }
                    }
                }
            }

            return false;
        }
Example #21
0
        public override bool VerifyFile(string filePath, ref List< KeyValuePair<X509Certificate2, bool>> verifiedCMS)
        {
            byte[] DataDigest = new byte[0];
            byte[] EncodedCMS = new byte[0];

            //digest of the data without the signature(s)
            DataDigest = Hash(filePath);
            //signatures found in the file
            List<String> Signatures = ExtractAllSignatures(filePath);
            if (Signatures.Count < 1) throw new NoSignatureFoundException(filePath);
            //Content information created from the data digest
            ContentInfo StepContent = new ContentInfo(DataDigest);

            SignedCms SignedCMS = new SignedCms(StepContent, true);
            List<KeyValuePair<X509Certificate2, bool>> UsedCertificates = new List<KeyValuePair<X509Certificate2, bool>>();
            //B1.List<KeyValuePair<String,KeyValuePair<X509Certificate2, bool>>> UsedCertificates = new List<KeyValuePair<String, KeyValuePair<X509Certificate2, bool>>>();

            bool Validation = true;

            foreach (String Signature in Signatures)
            {
                SignedCMS.Decode(Convert.FromBase64String(Signature));
                SignerInfoEnumerator Enumerator = SignedCMS.SignerInfos.GetEnumerator();
                if (!Enumerator.MoveNext()) throw new InvalidSignerInformationException(Signature);

                try
                {
                    //after decoding the signed cms, we check the signature
                    SignedCMS.CheckSignature(true);
                    UsedCertificates.Add(new KeyValuePair<X509Certificate2, bool>(Enumerator.Current.Certificate, true));
                    //B1.UsedCertificates.Add(new KeyValuePair<string, KeyValuePair<X509Certificate2, bool>>(FilePath,new KeyValuePair<X509Certificate2, bool>(enumerator.Current.Certificate, true)));

                }
                catch (System.Security.Cryptography.CryptographicException e)
                {
                    //signature can't be verified
                    UsedCertificates.Add(new KeyValuePair<X509Certificate2, bool>(Enumerator.Current.Certificate, true));
                    //B1.UsedCertificates.Add(new KeyValuePair<string, KeyValuePair<X509Certificate2, bool>>(FilePath, new KeyValuePair<X509Certificate2, bool>(enumerator.Current.Certificate, false)));
                    Validation = false;
                }

            }
            //B1.VerifiedCMS = MoveTo(UsedCertificates, VerifiedCMS);
            verifiedCMS = UsedCertificates;
            return Validation;
        }
 private TimestampInformation GetTimestampInformation(X509Native.AXL_AUTHENTICODE_TIMESTAMPER_INFO timestamper, XmlElement licenseNode)
 {
     TimestampInformation information = null;
     if (timestamper.dwError == 0)
     {
         return new TimestampInformation(timestamper);
     }
     if ((timestamper.dwError == -2146762748) || (timestamper.dwError == -2146762496))
     {
         XmlElement element = licenseNode.SelectSingleNode("r:issuer/ds:Signature/ds:Object/as:Timestamp", this.m_namespaceManager) as XmlElement;
         if (element == null)
         {
             return information;
         }
         byte[] encodedMessage = Convert.FromBase64String(element.InnerText);
         try
         {
             SignedCms cms = new SignedCms();
             cms.Decode(encodedMessage);
             cms.CheckSignature(true);
             return null;
         }
         catch (CryptographicException exception)
         {
             return new TimestampInformation((SignatureVerificationResult) Marshal.GetHRForException(exception));
         }
     }
     return null;
 }
Example #23
0
        public override bool VerifyFile(string filePath, ref List<KeyValuePair<X509Certificate2, bool>> verifiedCMS)
        {
            byte[] DataDigest = new byte[0];
            byte[] BlockDigest = new byte[0];
            signatureBlock = new Elements(ExtractBlocks(filePath), false);

            //digest of the data without the signature(s)
            DataDigest = Hash(filePath);
            //signatures found in the file
            Dictionary<string, string> Signatures = ExtractAllSignatures(filePath);
            if (Signatures.Count < 1) throw new NoSignatureFoundException(filePath);

            List<KeyValuePair<X509Certificate2, bool>> UsedCertificates = new List<KeyValuePair<X509Certificate2, bool>>();

            bool Validation = true;

            foreach (String Signature in Signatures.Keys)
            {
                BlockDigest = HashFunction.ComputeHash(new MemoryStream(System.Text.Encoding.UTF8.GetBytes(Signatures[Signature])));
                byte[] merkleHash = new byte[DataDigest.Length + BlockDigest.Length];
                Array.Copy(DataDigest, merkleHash, DataDigest.Length);
                Array.Copy(BlockDigest, 0, merkleHash, DataDigest.Length, BlockDigest.Length);

                //Content information created from the data digest
                ContentInfo StepContent = new ContentInfo(merkleHash);

                SignedCms SignedCMS = new SignedCms(StepContent, true);
                SignedCMS.Decode(Convert.FromBase64String(Signature));
                SignerInfoEnumerator Enumerator = SignedCMS.SignerInfos.GetEnumerator();
                if (!Enumerator.MoveNext()) throw new InvalidSignerInformationException(Signature);

                try
                {
                    //after decoding the signed cms, we check the signature
                    SignedCMS.CheckSignature(true);
                    UsedCertificates.Add(new KeyValuePair<X509Certificate2, bool>(Enumerator.Current.Certificate, true));

                }
                catch (System.Security.Cryptography.CryptographicException e)
                {
                    //signature can't be verified
                    UsedCertificates.Add(new KeyValuePair<X509Certificate2, bool>(Enumerator.Current.Certificate, false));
                    Validation = false;
                }

            }
            verifiedCMS = UsedCertificates;
            return Validation;
        }
Example #24
0
 private bool VerifySig(string signeture, string message)
 {
     SignedCms cms = null;
     bool flag;
     this.CertificateErr = "";
     byte[] encodedMessage = Convert.FromBase64String(signeture);
     ContentInfo contentInfo = new ContentInfo(Encoding.UTF8.GetBytes(message));
     cms = new SignedCms(contentInfo, true);
     X509Chain ch = new X509Chain();
     try
     {
         cms.Decode(encodedMessage);
         ch.ChainPolicy.RevocationMode = X509RevocationMode.Offline;
         ch.ChainPolicy.VerificationFlags = X509VerificationFlags.IgnoreRootRevocationUnknown;
         if (ch.Build(cms.Certificates[0]))
         {
             cms.CheckSignature(true);
             return true;
         }
         string str = this.statuschk(ch);
         if (str == "CRL does not exist")
         {
             cms.CheckSignature(true);
             return true;
         }
         this.CertificateErr = str;
         flag = false;
     }
     catch (Exception exception)
     {
         throw exception;
     }
     return flag;
 }
Example #25
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;
            }
        }
        /// <summary>
        /// Checks if signature is valid and data not altered.
        /// </summary>
        /// <returns>Returns true if signature is valid, otherwise false.</returns>
        public bool VerifySignature()
        {
            // Message is signed when it's saved out.
            if(m_pSignerCert != null){
                return true;
            }
            // multipart/signed must always have only 2 entities, otherwise invalid data.
            if(this.BodyParts.Count != 2){
                return false;
            }
                
            // Get signature. It should be 2 entity.
            MIME_Entity signatureEntity = this.BodyParts[1];
                       
            // Store entity to tmp stream.              
            MemoryStream tmpDataEntityStream = new MemoryStream();
            this.BodyParts[0].ToStream(tmpDataEntityStream,null,null,false);

            try{
                SignedCms signedCms = new SignedCms(new ContentInfo(tmpDataEntityStream.ToArray()),true);
                signedCms.Decode(((MIME_b_SinglepartBase)signatureEntity.Body).Data);
                signedCms.CheckSignature(true);

                return true;
            }
            catch{
                return false;
            }
        }