コード例 #1
0
        /// <summary>
        /// Checks the validity of the certificate, and calls the next
        /// verifier in the chain, if any.
        /// </summary>
        /// <param name="signCert">the certificate that needs to be checked</param>
        /// <param name="issuerCert">its issuer</param>
        /// <param name="signDate">the date the certificate needs to be valid</param>
        /// <returns>
        /// a list of <code>VerificationOK</code> objects.
        /// The list will be empty if the certificate couldn't be verified.
        /// </returns>
        /// <exception cref="Org.BouncyCastle.Security.GeneralSecurityException"/>
        /// <exception cref="System.IO.IOException"/>
        public virtual IList <VerificationOK> Verify(X509Certificate signCert, X509Certificate issuerCert, DateTime
                                                     signDate)
        {
            // Check if the certificate is valid on the signDate
            if (signDate != null)
            {
                signCert.CheckValidity(signDate);
            }
            // Check if the signature is valid
            if (issuerCert != null)
            {
                signCert.Verify(issuerCert.GetPublicKey());
            }
            else
            {
                // Also in case, the certificate is self-signed
                signCert.Verify(signCert.GetPublicKey());
            }
            IList <VerificationOK> result = new List <VerificationOK>();

            if (verifier != null)
            {
                result.AddAll(verifier.Verify(signCert, issuerCert, signDate));
            }
            return(result);
        }
        /// <summary>
        ///
        /// </summary>
        public X509Certificate RetrieveAndVerifyCertificate(string certChainUrl)
        {
            // making requests to externally-supplied URLs is an open invitation to DoS
            // so restrict host to an Alexa controlled subdomain/path
            if (!VerifyCertificateUrl(certChainUrl))
            {
                return(null);
            }

            WebClient webClient = new WebClient();
            string    content   = webClient.DownloadString(certChainUrl);

            Org.BouncyCastle.OpenSsl.PemReader pemReader = new Org.BouncyCastle.OpenSsl.PemReader(new StringReader(content));
            X509Certificate cert = (X509Certificate)pemReader.ReadObject();

            try
            {
                cert.CheckValidity();
                if (!CheckCertSubjectNames(cert))
                {
                    return(null);
                }
            }
            catch (CertificateExpiredException)
            {
                return(null);
            }
            catch (CertificateNotYetValidException)
            {
                return(null);
            }

            return(cert);
        }
コード例 #3
0
        public static X509Certificate MakeCertificate(IAsymmetricCipherKeyPair _subKP,
                                                      string _subDN, IAsymmetricCipherKeyPair _issKP, string _issDN, string algorithm, bool _ca)
        {
            IAsymmetricKeyParameter _subPub  = _subKP.Public;
            IAsymmetricKeyParameter _issPriv = _issKP.Private;
            IAsymmetricKeyParameter _issPub  = _issKP.Public;

            X509V3CertificateGenerator _v3CertGen = new X509V3CertificateGenerator();

            _v3CertGen.Reset();
            _v3CertGen.SetSerialNumber(allocateSerialNumber());
            _v3CertGen.SetIssuerDN(new X509Name(_issDN));
            _v3CertGen.SetNotBefore(DateTime.UtcNow);
            _v3CertGen.SetNotAfter(DateTime.UtcNow.AddDays(100));
            _v3CertGen.SetSubjectDN(new X509Name(_subDN));
            _v3CertGen.SetPublicKey(_subPub);
            _v3CertGen.SetSignatureAlgorithm(algorithm);

            _v3CertGen.AddExtension(X509Extensions.SubjectKeyIdentifier, false,
                                    createSubjectKeyId(_subPub));

            _v3CertGen.AddExtension(X509Extensions.AuthorityKeyIdentifier, false,
                                    createAuthorityKeyId(_issPub));

            _v3CertGen.AddExtension(X509Extensions.BasicConstraints, false,
                                    new BasicConstraints(_ca));

            X509Certificate _cert = _v3CertGen.Generate(_issPriv);

            _cert.CheckValidity(DateTime.UtcNow);
            _cert.Verify(_issPub);

            return(_cert);
        }
コード例 #4
0
        private static bool VerifyCertificate(X509Certificate cert, X509Certificate rootCert, X509Certificate middleCert, bool ifValidateCNName)
        {
            var cn = GetIdentitiesFromCertficate(cert);

            try
            {
                cert.CheckValidity();                                    //验证有效期
                if (!VerifyCertificateChain(cert, rootCert, middleCert)) //验证书链
                {
                    return(false);
                }
            }
            catch
            {
                return(false);
            }

            if (ifValidateCNName)
            {
                // 验证公钥是否属于银联
                if (UNIONPAY_CNNAME != cn)
                {
                    return(false);
                }
            }
            else
            {
                if (UNIONPAY_CNNAME != cn && "00040000:SIGN" != cn)
                {
                    return(false);
                }
            }

            return(true);
        }
コード例 #5
0
        private static bool VerifyCertificate(X509Certificate x509Cert)
        {
            string cn = GetIdentitiesFromCertficate(x509Cert);

            try
            {
                x509Cert.CheckValidity();              //验证有效期
                if (!VerifyCertificateChain(x509Cert)) //验证书链
                {
                    return(false);
                }
            }
            catch
            {
                return(false);
            }

            string unionpayCnName = "中国银联股份有限公司";

            if (!unionpayCnName.Equals(cn) && !"00040000:SIGN".Equals(cn))
            {
                return(false);
            }

            return(true);
        }
コード例 #6
0
        internal static AsymmetricKeyParameter CreatePublicKeyFromCertificateBytes(byte[] certificate)
        {
            X509CertificateParser parser = new X509CertificateParser();
            X509Certificate       cert   = parser.ReadCertificate(certificate);

            cert.CheckValidity();
            return(cert.GetPublicKey());
        }
コード例 #7
0
 public bool Verify(X509Certificate cert)
 {
     Org.BouncyCastle.Asn1.Cms.Time signingTime = this.GetSigningTime();
     if (signingTime != null)
     {
         cert.CheckValidity(signingTime.Date);
     }
     return(this.DoVerify(cert.GetPublicKey()));
 }
コード例 #8
0
 /// <summary>
 /// Test if the signed x509 certificate has been expired.
 /// </summary>
 /// <param name="certificate">x509 certificate instance to validate.</param>
 /// <returns></returns>
 public static bool IsExpired(X509Certificate certificate)
 {
     try {
         certificate.CheckValidity(DateTime.Now);
         return(false);
     }
     catch (Exception) {
         return(true);
     }
 }
コード例 #9
0
 public void Validate(X509Certificate cert)
 {
     try
     {
         byte[] b = DigestUtilities.CalculateDigest(certID.GetHashAlgorithmName(), cert.GetEncoded());
         if (!Arrays.ConstantTimeAreEqual(certID.GetCertHash(), b))
         {
             throw new TspValidationException("certificate hash does not match certID hash.");
         }
         if (certID.IssuerSerial != null)
         {
             if (!certID.IssuerSerial.Serial.Value.Equals(cert.SerialNumber))
             {
                 throw new TspValidationException("certificate serial number does not match certID for signature.");
             }
             GeneralName[] names = certID.IssuerSerial.Issuer.GetNames();
             X509Name      issuerX509Principal = PrincipalUtilities.GetIssuerX509Principal(cert);
             bool          flag = false;
             for (int i = 0; i != names.Length; i++)
             {
                 if (names[i].TagNo == 4 && X509Name.GetInstance(names[i].Name).Equivalent(issuerX509Principal))
                 {
                     flag = true;
                     break;
                 }
             }
             if (!flag)
             {
                 throw new TspValidationException("certificate name does not match certID for signature. ");
             }
         }
         TspUtil.ValidateCertificate(cert);
         cert.CheckValidity(tstInfo.GenTime);
         if (!tsaSignerInfo.Verify(cert))
         {
             throw new TspValidationException("signature not created by certificate.");
         }
     }
     catch (CmsException ex)
     {
         if (ex.InnerException != null)
         {
             throw new TspException(ex.Message, ex.InnerException);
         }
         throw new TspException("CMS exception: " + ex, ex);
     }
     catch (CertificateEncodingException ex2)
     {
         throw new TspException("problem processing certificate: " + ex2, ex2);
     }
     catch (SecurityUtilityException ex3)
     {
         throw new TspException("cannot find algorithm: " + ex3.Message, ex3);
     }
 }
コード例 #10
0
ファイル: ExpirationRule.cs プロジェクト: ooleoole/hyperway
 public void Validate(X509Certificate certificate)
 {
     try
     {
         certificate.CheckValidity(DateTime.Now);
     }
     catch (Exception e) when(e is CertificateNotYetValidException || e is CertificateExpiredException)
     {
         throw new FailedValidationException("Certificate does not have a valid expiration date.");
     }
 }
コード例 #11
0
        /**
         * verify that the given certificate successfully handles and confirms
         * the signature associated with this signer and, if a signingTime
         * attribute is available, that the certificate was valid at the time the
         * signature was generated.
         */
        public bool Verify(
            X509Certificate cert)
        {
            Asn1.Cms.Time signingTime = GetSigningTime();
            if (signingTime != null)
            {
                cert.CheckValidity(signingTime.Date);
            }

            return(DoVerify(cert.GetPublicKey()));
        }
コード例 #12
0
        public static bool ValidateSelfSignedCert(X509Certificate cert, ICipherParameters pubKey)
        {
            cert.CheckValidity(DateTime.UtcNow);
            var tbsCert = cert.GetTbsCertificate();
            var sig     = cert.GetSignature();

            var signer = SignerUtilities.GetSigner(cert.SigAlgName);

            signer.Init(false, pubKey);
            signer.BlockUpdate(tbsCert, 0, tbsCert.Length);
            return(signer.VerifySignature(sig));
        }
コード例 #13
0
 /// <summary>
 /// Checks the certificate in this same date and time.
 /// </summary>
 /// <returns>
 /// <c>true</c>, if is valid now, <c>false</c> otherwise.
 /// </returns>
 /// <param name='BCCert'>
 /// BouncyCastle cert to check.
 /// </param>
 private static bool CertIsValidNow(X509Certificate BCCert)
 {
     try
     {
         BCCert.CheckValidity();
         return(BCCert.IsValidNow);
     }catch (CertificateExpiredException ce) {
         SystemLogger.Log(SystemLogger.Module.PLATFORM, "*************** Certificate Validation: Certificate has expired");
     }catch (CertificateNotYetValidException cex) {
         SystemLogger.Log(SystemLogger.Module.PLATFORM, "*************** Certificate Validation: Certificate is not yet valid");
     }
     return(false);
 }
コード例 #14
0
 /// <summary>
 /// Generate subject certificate.
 /// </summary>
 /// <param name="signatureAlgorithmName">Signature algorithm name.</param>
 /// <param name="issuerPrivateKey">The asymmetric private key of issuer.</param>
 /// <param name="issuerCert">The certificate of issuer.</param>
 /// <param name="subjectPublicKey">The asymmetric public key of subject.</param>
 /// <param name="subjectDN">The distinct name of subject.</param>
 /// <param name="subjectExtensions">Extensions of subject.</param>
 /// <param name="start">Start time.</param>
 /// <param name="days">The valid days from the start time.</param>
 /// <returns></returns>
 /// <exception cref="Exception"/>
 public static X509Certificate GenerateSubjectCert(string signatureAlgorithmName,
                                                   AsymmetricKeyParameter issuerPrivateKey,
                                                   X509Certificate issuerCert,
                                                   AsymmetricKeyParameter subjectPublicKey,
                                                   X509Name subjectDN,
                                                   X509Extensions subjectExtensions,
                                                   DateTime start,
                                                   int days)
 {
     if (issuerPrivateKey is null)
     {
         throw new ArgumentNullException(nameof(issuerPrivateKey));
     }
     if (issuerCert is null)
     {
         throw new ArgumentNullException(nameof(issuerCert));
     }
     if (subjectPublicKey is null)
     {
         throw new ArgumentNullException(nameof(subjectPublicKey));
     }
     try
     {
         issuerCert.CheckValidity();
     }
     catch
     {
         throw new CryptographicException("The issuer's certificate has expired.");
     }
     try
     {
         issuerCert.CheckValidity(start.AddDays(days));
     }
     catch
     {
         throw new CryptographicException("The end time exceeds the validity of the issuer certificate.");
     }
     return(GenerateCert(signatureAlgorithmName, issuerPrivateKey, issuerCert.SubjectDN, subjectPublicKey, subjectDN, subjectExtensions, start, days));
 }
コード例 #15
0
 /// <summary>
 /// Checks the ca cert is valid.
 /// </summary>
 /// <param name="issuingCaCert">The issuing ca cert.</param>
 /// <returns>True if valid, false if not</returns>
 protected bool checkCaCertValid(X509Certificate issuingCaCert)
 {
     try
     {
         caCertificate.CheckValidity();
         caCertificate.Verify(issuingCaCert.GetPublicKey());
     }
     catch (Exception ex)
     {
         logEvent(LogEvent.EventType.Error, "CA " + ex.Message);
         return(false);
     }
     return(true);
 }
コード例 #16
0
        private static bool VerifyCertificate(X509Certificate x509Cert)
        {
            var cn = GetIdentitiesFromCertficate(x509Cert);

            x509Cert.CheckValidity();              //验证有效期
            if (!VerifyCertificateChain(x509Cert)) //验证书链
            {
                return(false);
            }

            var unionpayCnName = "中国银联股份有限公司";

            return(unionpayCnName.Equals(cn) || "00040000:SIGN".Equals(cn));
        }
コード例 #17
0
        public void ShowCertificateInfo(X509Certificate cert, DateTime signDate)
        {
            Console.WriteLine("Issuer: " + cert.IssuerDN);
            Console.WriteLine("Subject: " + cert.SubjectDN);
            Console.WriteLine("Valid from: " + cert.NotBefore.ToUniversalTime().ToString("yyyy-MM-dd"));
            Console.WriteLine("Valid to: " + cert.NotAfter.ToUniversalTime().ToString("yyyy-MM-dd"));

            // Check if a certificate was valid on the signing date
            try
            {
                cert.CheckValidity(signDate);
                Console.WriteLine("The certificate was valid at the time of signing.");
            }
            catch (CertificateExpiredException)
            {
                Console.WriteLine("The certificate was expired at the time of signing.");
            }
            catch (CertificateNotYetValidException)
            {
                Console.WriteLine("The certificate wasn't valid yet at the time of signing.");
            }

            // Check if a certificate is still valid now
            try
            {
                cert.CheckValidity();
                Console.WriteLine("The certificate is still valid.");
            }
            catch (CertificateExpiredException)
            {
                Console.WriteLine("The certificate has expired.");
            }
            catch (CertificateNotYetValidException)
            {
                Console.WriteLine("The certificate isn't valid yet.");
            }
        }
コード例 #18
0
ファイル: CMSTestUtil.cs プロジェクト: TangoCS/BouncyCastle
        public static X509Certificate MakeV1Certificate(AsymmetricCipherKeyPair subKP,
                                                        string _subDN, AsymmetricCipherKeyPair issKP, string _issDN)
        {
            AsymmetricKeyParameter subPub  = subKP.Public;
            AsymmetricKeyParameter issPriv = issKP.Private;
            AsymmetricKeyParameter issPub  = issKP.Public;

            X509V1CertificateGenerator v1CertGen = new X509V1CertificateGenerator();

            v1CertGen.Reset();
            v1CertGen.SetSerialNumber(AllocateSerialNumber());
            v1CertGen.SetIssuerDN(new X509Name(_issDN));
            v1CertGen.SetNotBefore(DateTime.UtcNow);
            v1CertGen.SetNotAfter(DateTime.UtcNow.AddDays(100));
            v1CertGen.SetSubjectDN(new X509Name(_subDN));
            v1CertGen.SetPublicKey(subPub);

            if (issPub is RsaKeyParameters)
            {
                v1CertGen.SetSignatureAlgorithm("SHA1WithRSA");
            }
            else if (issPub is DsaPublicKeyParameters)
            {
                v1CertGen.SetSignatureAlgorithm("SHA1withDSA");
            }
            else if (issPub is ECPublicKeyParameters)
            {
                ECPublicKeyParameters ecPub = (ECPublicKeyParameters)issPub;
                if (ecPub.AlgorithmName == "ECGOST3410")
                {
                    v1CertGen.SetSignatureAlgorithm("GOST3411withECGOST3410");
                }
                else
                {
                    v1CertGen.SetSignatureAlgorithm("SHA1withECDSA");
                }
            }
            else
            {
                v1CertGen.SetSignatureAlgorithm("GOST3411WithGOST3410");
            }

            X509Certificate _cert = v1CertGen.Generate(issPriv);

            _cert.CheckValidity(DateTime.UtcNow);
            _cert.Verify(issPub);

            return(_cert);
        }
        private async Task <X509Certificate> RetrieveAndVerifyCertificateAsync(string certChainUrl)
        {
            // making requests to externally-supplied URLs is an open invitation to DoS
            // so restrict host to an Alexa controlled subdomain/path
            if (!VerifyCertificateUrl(certChainUrl))
            {
                return(null);
            }
            X509Certificate     foundCert       = null;
            HttpResponseMessage responseMessage = null;


            using (HttpClient client = new HttpClient())
            {
                responseMessage = await client.GetAsync(certChainUrl);
            }

            if (responseMessage.IsSuccessStatusCode)
            {
                string certText = await responseMessage.Content.ReadAsStringAsync();

                foundCert = TextToCert(certText);
                try
                {
                    foundCert.CheckValidity();
                    if (!CheckCertSubjectNames(foundCert))
                    {
                        return(null);
                    }
                    else
                    {
                        await StoreCertAsync(certChainUrl, certText);
                    }
                }
                catch (CertificateExpiredException)
                {
                    _logger.LogError("Certificate expired");
                    return(null);
                }
                catch (CertificateNotYetValidException)
                {
                    _logger.LogError("Certificate not yet valid");
                    return(null);
                }
            }

            return(foundCert);
        }
コード例 #20
0
 /// <summary>
 /// Checks the certificates in a certificate chain:
 /// are they valid on a specific date, and
 /// do they chain up correctly?
 /// </summary>
 /// <param name="chain">the certificate chain</param>
 /// <exception cref="Org.BouncyCastle.Security.GeneralSecurityException"/>
 public virtual void VerifyChain(X509Certificate[] chain)
 {
     // Loop over the certificates in the chain
     for (int i = 0; i < chain.Length; i++)
     {
         X509Certificate cert = (X509Certificate)chain[i];
         // check if the certificate was/is valid
         cert.CheckValidity(signDate);
         // check if the previous certificate was issued by this certificate
         if (i > 0)
         {
             chain[i - 1].Verify(chain[i].GetPublicKey());
         }
     }
     LOGGER.Info("All certificates are valid on " + signDate.ToString());
 }
コード例 #21
0
        /// <summary>
        /// Test if the signed x509 certificate has been expired.
        /// </summary>
        /// <param name="data">PEM formatted certificate byte array.</param>
        /// <returns></returns>
        /// <exception cref="CertificateIOException">Thrown when the
        /// <see cref="data"/> is either null or zero length.</exception>
        public static bool IsExpired(byte[] data)
        {
            if (data == null || data.Length == 0)
            {
                throw new Exception();
            }
            X509Certificate certificate = DeserializeCert(data);

            try {
                certificate.CheckValidity(DateTime.Now);
                return(false);
            }
            catch (Exception) {
                return(true);
            }
        }
コード例 #22
0
        public void TestX509CertificateConversion()
        {
            BigInteger DSAParaG    = new BigInteger(Base64.Decode("AL0fxOTq10OHFbCf8YldyGembqEu08EDVzxyLL29Zn/t4It661YNol1rnhPIs+cirw+yf9zeCe+KL1IbZ/qIMZM="));
            BigInteger DSAParaP    = new BigInteger(Base64.Decode("AM2b/UeQA+ovv3dL05wlDHEKJ+qhnJBsRT5OB9WuyRC830G79y0R8wuq8jyIYWCYcTn1TeqVPWqiTv6oAoiEeOs="));
            BigInteger DSAParaQ    = new BigInteger(Base64.Decode("AIlJT7mcKL6SUBMmvm24zX1EvjNx"));
            BigInteger DSAPublicY  = new BigInteger(Base64.Decode("TtWy2GuT9yGBWOHi1/EpCDa/bWJCk2+yAdr56rAcqP0eHGkMnA9s9GJD2nGU8sFjNHm55swpn6JQb8q0agrCfw=="));
            BigInteger DsaPrivateX = new BigInteger(Base64.Decode("MMpBAxNlv7eYfxLTZ2BItJeD31A="));

            DsaParameters           para    = new DsaParameters(DSAParaP, DSAParaQ, DSAParaG);
            DsaPrivateKeyParameters dsaPriv = new DsaPrivateKeyParameters(DsaPrivateX, para);
            DsaPublicKeyParameters  dsaPub  = new DsaPublicKeyParameters(DSAPublicY, para);

            IDictionary attrs = new Hashtable();

            attrs[X509Name.C]  = "AU";
            attrs[X509Name.O]  = "The Legion of the Bouncy Castle";
            attrs[X509Name.L]  = "Melbourne";
            attrs[X509Name.ST] = "Victoria";
            attrs[X509Name.E]  = "*****@*****.**";

            IList ord = new ArrayList(attrs.Keys);

            X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();

            certGen.SetSerialNumber(BigInteger.One);

            certGen.SetIssuerDN(new X509Name(ord, attrs));
            certGen.SetNotBefore(DateTime.UtcNow.AddDays(-1));
            certGen.SetNotAfter(DateTime.UtcNow.AddDays(1));
            certGen.SetSubjectDN(new X509Name(ord, attrs));
            certGen.SetPublicKey(dsaPub);
            certGen.SetSignatureAlgorithm("SHA1WITHDSA");

            X509Certificate cert = certGen.Generate(dsaPriv);

            cert.CheckValidity();
            cert.Verify(dsaPub);

            SystemX509.X509Certificate dotNetCert = DotNetUtilities.ToX509Certificate(cert);

            X509Certificate certCopy = DotNetUtilities.FromX509Certificate(dotNetCert);

            Assert.AreEqual(cert, certCopy);

            certCopy.CheckValidity();
            certCopy.Verify(dsaPub);
        }
コード例 #23
0
ファイル: PKCS12Example.cs プロジェクト: 894880010/MP
        /**
         * we generate the CA's certificate
         */
        public static X509CertificateEntry CreateMasterCert(
            AsymmetricKeyParameter pubKey,
            AsymmetricKeyParameter privKey)
        {
            //
            // signers name
            //
            string issuer = "C=AU, O=The Legion of the Bouncy Castle, OU=Bouncy Primary Certificate";

            //
            // subjects name - the same as we are self signed.
            //
            string subject = "C=AU, O=The Legion of the Bouncy Castle, OU=Bouncy Primary Certificate";

            //
            // create the certificate - version 1
            //

            v1CertGen.SetSerialNumber(BigInteger.One);
            v1CertGen.SetIssuerDN(new X509Name(issuer));
            v1CertGen.SetNotBefore(DateTime.UtcNow.AddMonths(-1));
            v1CertGen.SetNotAfter(DateTime.UtcNow.AddMonths(1));
            v1CertGen.SetSubjectDN(new X509Name(subject));
            v1CertGen.SetPublicKey(pubKey);
            v1CertGen.SetSignatureAlgorithm("SHA1WithRSAEncryption");

            X509Certificate cert = v1CertGen.Generate(privKey);

            cert.CheckValidity(DateTime.UtcNow);

            cert.Verify(pubKey);

//			PKCS12BagAttributeCarrier   bagAttr = (PKCS12BagAttributeCarrier)cert;
            IDictionary bagAttr = new Hashtable();

            //
            // this is actually optional - but if you want to have control
            // over setting the friendly name this is the way to do it...
            //
//			bagAttr.setBagAttribute(
//				PKCSObjectIdentifiers.pkcs_9_at_friendlyName,
//				new DERBMPString("Bouncy Primary Certificate"));
            bagAttr.Add(PkcsObjectIdentifiers.Pkcs9AtFriendlyName.Id,
                        new DerBmpString("Bouncy Primary Certificate"));

            return(new X509CertificateEntry(cert, bagAttr));
        }
コード例 #24
0
	    /**
	     * Checks the validity of the certificate, and calls the next
	     * verifier in the chain, if any.
	     * @param signCert	the certificate that needs to be checked
	     * @param issuerCert	its issuer
	     * @param signDate		the date the certificate needs to be valid
	     * @return a list of <code>VerificationOK</code> objects.
	     * The list will be empty if the certificate couldn't be verified.
	     * @throws GeneralSecurityException
	     * @throws IOException
	     */
	    virtual public List<VerificationOK> Verify(X509Certificate signCert, X509Certificate issuerCert, DateTime signDate) {
		    // Check if the certificate is valid on the signDate
		    //if (signDate != null)
			    signCert.CheckValidity(signDate);
		    // Check if the signature is valid
		    if (issuerCert != null) {
			    signCert.Verify(issuerCert.GetPublicKey());
		    }
		    // Also in case, the certificate is self-signed
		    else {
			    signCert.Verify(signCert.GetPublicKey());
		    }
		    List<VerificationOK> result = new List<VerificationOK>();
		    if (verifier != null)
			    result.AddRange(verifier.Verify(signCert, issuerCert, signDate));
		    return result;
	    }
コード例 #25
0
ファイル: TSPTestUtil.cs プロジェクト: ekr/hacrypto
        public static X509Certificate MakeCertificate(AsymmetricCipherKeyPair _subKP,
                                                      string _subDN, AsymmetricCipherKeyPair _issKP, string _issDN, bool _ca)
        {
            AsymmetricKeyParameter _subPub  = _subKP.Public;
            AsymmetricKeyParameter _issPriv = _issKP.Private;
            AsymmetricKeyParameter _issPub  = _issKP.Public;

            X509V3CertificateGenerator _v3CertGen = new X509V3CertificateGenerator();

            _v3CertGen.Reset();
            _v3CertGen.SetSerialNumber(allocateSerialNumber());
            _v3CertGen.SetIssuerDN(new X509Name(_issDN));
            _v3CertGen.SetNotBefore(DateTime.UtcNow);
            _v3CertGen.SetNotAfter(DateTime.UtcNow.AddDays(100));
            _v3CertGen.SetSubjectDN(new X509Name(_subDN));
            _v3CertGen.SetPublicKey(_subPub);
            _v3CertGen.SetSignatureAlgorithm("MD5WithRSAEncryption");

            _v3CertGen.AddExtension(X509Extensions.SubjectKeyIdentifier, false,
                                    createSubjectKeyId(_subPub));

            _v3CertGen.AddExtension(X509Extensions.AuthorityKeyIdentifier, false,
                                    createAuthorityKeyId(_issPub));

            if (_ca)
            {
                _v3CertGen.AddExtension(X509Extensions.BasicConstraints, false,
                                        new BasicConstraints(_ca));
            }
            else
            {
                _v3CertGen.AddExtension(X509Extensions.ExtendedKeyUsage, true,
                                        ExtendedKeyUsage.GetInstance(new DerSequence(KeyPurposeID.IdKPTimeStamping)));
            }

            X509Certificate _cert = _v3CertGen.Generate(_issPriv);

            _cert.CheckValidity(DateTime.UtcNow);
            _cert.Verify(_issPub);

            return(_cert);
        }
コード例 #26
0
        /**
         * verify that the given certificate succesfully handles and confirms
         * the signature associated with this signer and, if a signingTime
         * attribute is available, that the certificate was valid at the time the
         * signature was generated.
         */
        public bool Verify(
            X509Certificate cert)
        {
            Asn1.Cms.AttributeTable attr = this.SignedAttributes;

            if (attr != null)
            {
                Asn1.Cms.Attribute t = attr[CmsAttributes.SigningTime];

                if (t != null)
                {
                    Asn1.Cms.Time time = Asn1.Cms.Time.GetInstance(
                        t.AttrValues[0].ToAsn1Object());

                    cert.CheckValidity(time.Date);
                }
            }

            return(DoVerify(cert.GetPublicKey(), attr));
        }
        /// <summary>
        ///
        /// </summary>
        public async Task <X509Certificate> RetrieveAndVerifyCertificateAsync(string certChainUrl)
        {
            // making requests to externally-supplied URLs is an open invitation to DoS
            // so restrict host to an Alexa controlled subdomain/path
            if (!VerifyCertificateUrl(certChainUrl))
            {
                return(null);
            }

            HttpClient          httpClient   = new HttpClient();
            HttpResponseMessage httpResponse = await httpClient.GetAsync(certChainUrl);

            string content = await httpResponse.Content.ReadAsStringAsync();

            if (string.IsNullOrEmpty(content))
            {
                return(null);
            }

            Org.BouncyCastle.OpenSsl.PemReader pemReader = new Org.BouncyCastle.OpenSsl.PemReader(new StringReader(content));
            X509Certificate cert = (X509Certificate)pemReader.ReadObject();

            try
            {
                cert.CheckValidity();
                if (!CheckCertSubjectNames(cert))
                {
                    return(null);
                }
            }
            catch (CertificateExpiredException)
            {
                return(null);
            }
            catch (CertificateNotYetValidException)
            {
                return(null);
            }

            return(cert);
        }
コード例 #28
0
        private void CheckCertificateValidity(X509Certificate cert)
        {
            cert.CheckValidity();

            var caCert = GetRootCert();

            var gst = GetSigner();

            gst.Init(false, caCert.GetPublicKey());

            var tbsCertificate = cert.GetTbsCertificate();

            gst.BlockUpdate(tbsCertificate, 0, tbsCertificate.Length);

            var t = gst.VerifySignature(cert.GetSignature());

            if (!t)
            {
                throw new CryptographicException("Cannot verify signature");
            }
        }
コード例 #29
0
        /// <summary>
        /// Deserializes a PEM formatted certificate byte array into
        /// a <see cref="X509Certificate"/> instance.
        /// </summary>
        /// <param name="data">PEM formatted certificate byte array.</param>
        /// <returns><see cref="X509Certificate"/> instance.</returns>
        /// <exception cref="CertificateIOException">Thrown when the
        /// <see cref="data"/> is either null or zero length.</exception>
        public static X509Certificate DeserializeCert(byte[] data)
        {
            if (data == null || data.Length == 0)
            {
                throw new Exception();
            }
            using (MemoryStream stream = new MemoryStream(data)) {
                using (StreamReader reader = new StreamReader(stream)) {
                    PemReader       pemReader = new PemReader(reader);
                    X509Certificate cert      = (X509Certificate)pemReader.ReadObject();
                    pemReader.Reader.Close();

                    try {
                        cert.CheckValidity();
                        return(cert);
                    }
                    catch (Exception) {
                        return(null);
                    }
                }
            }
        }
コード例 #30
0
        private static Boolean VerifyCertificate(X509Certificate x509Cert)
        {
            string cn = GetIdentitiesFromCertficate(x509Cert);

            try
            {
                x509Cert.CheckValidity();              //验证有效期
                                                       // x509Cert.Verify(rootCert.GetPublicKey());
                if (!VerifyCertificateChain(x509Cert)) //验证书链
                {
                    return(false);
                }
            }
            catch (Exception e)
            {
                Log.Error("verifyCertificate fail", e);
                return(false);
            }

            if (!"false".Equals(SdkConfig.IfValidateCNName))
            {
                // 验证公钥是否属于银联
                if (!UNIONPAY_CNNAME.Equals(cn))
                {
                    Log.Error("cer owner is not CUP:" + cn);
                    return(false);
                }
            }
            else
            {
                if (!UNIONPAY_CNNAME.Equals(cn) && !"00040000:SIGN".Equals(cn))
                {
                    Log.Error("cer owner is not CUP:" + cn);
                    return(false);
                }
            }
            return(true);
        }