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


C# SignedCms.CheckSignature方法代码示例

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


在下文中一共展示了SignedCms.CheckSignature方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: CheckSig

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

示例2: CheckSig

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

示例3: Verify

 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));
 }
开发者ID:NomadPL,项目名称:Nomad,代码行数:14,代码来源:PkiSignatureAlgorithm.cs

示例4: CheckFileSignature

        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";
            }
        }
开发者ID:myagincourt,项目名称:SimpleSmevSigner,代码行数:17,代码来源:Signer.cs

示例5: Sign

        public static SignatureResponse Sign(byte[] data)
        {
            // TODO:
            // padding configuration
            // algorithm configuration
            // encoding configuration
            /*
            SHA1Managed sha1 = new SHA1Managed();
            byte[] hash = sha1.ComputeHash(data);

            var sig = csp.SignHash(hash, CryptoConfig.MapNameToOID("SHA1"));
            //sig = csp.SignData(Encoding.UTF8.GetBytes(text), CryptoConfig.MapNameToOID("SHA1"));

            MessageBox.Show("SignData");
            */

            var content = new ContentInfo(data);
            var cms = new SignedCms(content, true); // TODO detached config
            var signer = new CmsSigner();
            signer.IncludeOption = X509IncludeOption.EndCertOnly;

            cms.ComputeSignature(signer, false);
            var sig = cms.Encode();

            //ensure my signature is correct before continuing.
            cms.CheckSignature(true);

            var newCMS = new SignedCms(content, false);
            newCMS.Decode(sig);
            newCMS.CheckSignature(true);

            var cert = cms.Certificates[0];
            CheckSig(sig, data);
            return new SignatureResponse
            {
                publicKey = Convert.ToBase64String(cert.PublicKey.EncodedKeyValue.RawData),
                signature = Convert.ToBase64String(sig),
                fullSig = null // TODO
            };
        }
开发者ID:CACBridge,项目名称:ChromeCAC,代码行数:40,代码来源:CAC.cs

示例6: GetTimestampInformation

        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;
        }
开发者ID:nlh774,项目名称:DotNetReferenceSource,代码行数:46,代码来源:ManifestSignedXml.cs

示例7: ToStream

        /// <summary>
        /// Stores MIME entity body to the specified stream.
        /// </summary>
        /// <param name="stream">Stream where to store body data.</param>
        /// <param name="headerWordEncoder">Header 8-bit words ecnoder. Value null means that words are not encoded.</param>
        /// <param name="headerParmetersCharset">Charset to use to encode 8-bit header parameters. Value null means parameters not encoded.</param>
        /// <param name="headerReencode">If true always specified encoding is used for header. If false and header field value not modified, 
        /// original encoding is kept.</param>
        /// <exception cref="ArgumentNullException">Is raised when <b>stream</b> is null reference.</exception>
        internal protected override void ToStream(Stream stream,MIME_Encoding_EncodedWord headerWordEncoder,Encoding headerParmetersCharset,bool headerReencode)
        {
            // We have signer certificate, sign this entity.
            if(this.BodyParts.Count > 0 && m_pSignerCert != null){
                // Remove old signature if there is any.
                if(this.BodyParts.Count > 1){
                    this.BodyParts.Remove(1);
                }

                // Store entity to tmp stream.
                MemoryStream tmpDataEntityStream = new MemoryStream();
                this.BodyParts[0].ToStream(tmpDataEntityStream,null,null,false);
        
                // Compute PKCS #7 message.
                SignedCms signedCms = new SignedCms(new ContentInfo(tmpDataEntityStream.ToArray()),true);
                signedCms.ComputeSignature(new CmsSigner(m_pSignerCert));
                byte[] pkcs7 = signedCms.Encode();
   
                // Create PKCS 7 entity.
                MIME_Entity entity_application_pkcs7 = new MIME_Entity();
                MIME_b_Application application_pkcs7 = new MIME_b_Application(MIME_MediaTypes.Application.x_pkcs7_signature);
                entity_application_pkcs7.Body = application_pkcs7;
                application_pkcs7.SetData(new MemoryStream(pkcs7),MIME_TransferEncodings.Base64);
                entity_application_pkcs7.ContentType.Param_Name = "smime.p7s";
                entity_application_pkcs7.ContentDescription = "S/MIME Cryptographic Signature";
                this.BodyParts.Add(entity_application_pkcs7);

                signedCms.Decode(application_pkcs7.Data);
                signedCms.CheckSignature(true);
            }

            base.ToStream(stream,headerWordEncoder,headerParmetersCharset,headerReencode);
        }
开发者ID:DJGosnell,项目名称:LumiSoft.Net,代码行数:42,代码来源:MIME_b_MultipartSigned.cs

示例8: CheckSignAndGetCertificate

 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;
 }
开发者ID:Synerdocs,项目名称:synerdocs-sdk,代码行数:24,代码来源:Shell.cs

示例9: VerifyAndRemoveSignature

        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;
        }
开发者ID:virajs,项目名称:klWCFSecurity,代码行数:15,代码来源:klWCFCryptoHelper.cs

示例10: VerifyMsg

        //  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;
        }
开发者ID:bluecrystalsign,项目名称:bluecrystal-signer-DESCONTINUADO-,代码行数:43,代码来源:IttruActiveXObject.cs

示例11: LoadEncryptedAndMeabySignedMessage

            /// <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));
                }
            }
开发者ID:tonyqus,项目名称:MSGReader,代码行数:50,代码来源:Message.cs

示例12: CheckSignatureDetachedSignedCms

		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);
		}
开发者ID:nlhepler,项目名称:mono,代码行数:12,代码来源:SignedCmsTest.cs

示例13: ExtractMIMEParts


//.........这里部分代码省略.........
                    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");
开发者ID:ramazanaktolu,项目名称:OpaqueMail,代码行数:67,代码来源:MimePart.cs

示例14: GetSignerCertificate

        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;
        }
开发者ID:mono,项目名称:ikvm,代码行数:71,代码来源:Authenticode.cs

示例15: CheckSignature

		public bool CheckSignature (SignedCms cms)
		{
			try {
				cms.CheckSignature (false);
				return true;
			}
			catch {
			}
			return false;
		}
开发者ID:nlhepler,项目名称:mono,代码行数:10,代码来源:PkitsTest.cs


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