List of usage examples for java.security.cert X509Certificate getBasicConstraints
public abstract int getBasicConstraints();
From source file:com.foundstone.certinstaller.CertInstallerActivity.java
public void OnCertsRecieved(X509Certificate[] certificates) { for (X509Certificate cert : certificates) { // Non-CA's get Int.MAX if (cert.getBasicConstraints() == Integer.MAX_VALUE) { siteCert = cert;/* w w w. j a v a 2 s . co m*/ } else { caCert = cert; } } }
From source file:org.apache.hc.client5.http.impl.auth.CredSspScheme.java
private Certificate getPeerServerCertificate() throws AuthenticationException { final Certificate[] peerCertificates; try {//from ww w . j a v a2 s . c o m peerCertificates = sslEngine.getSession().getPeerCertificates(); } catch (final SSLPeerUnverifiedException e) { throw new AuthenticationException(e.getMessage(), e); } for (final Certificate peerCertificate : peerCertificates) { if (!(peerCertificate instanceof X509Certificate)) { continue; } final X509Certificate peerX509Cerificate = (X509Certificate) peerCertificate; if (peerX509Cerificate.getBasicConstraints() != -1) { continue; } return peerX509Cerificate; } return null; }
From source file:info.guardianproject.onionkit.trust.StrongTrustManager.java
private void checkBasicConstraints(X509Certificate cert) throws GeneralSecurityException { // check basic constraints int bConLen = cert.getBasicConstraints(); if (bConLen == -1) { throw new GeneralSecurityException("Basic Constraints CA not set for issuer in chain"); } else {//from w w w. j av a2 s . c o m /* * basicConstraints=CA:TRUE basicConstraints=CA:FALSE * basicConstraints=critical,CA:TRUE, pathlen:0 */ // String OID_BASIC_CONSTRAINTS = "2.5.29.19"; try { Object bsVal = getExtensionValue(cert, X509Extensions.BasicConstraints.getId(), BasicConstraints.class); if (bsVal != null && bsVal instanceof BasicConstraints) { BasicConstraints basicConstraints = (BasicConstraints) bsVal; // BasicConstraints.getInstance(ASN1Object.fromByteArray(bsValBytes)); debug("Basic Constraints=CA:" + basicConstraints.isCA()); if (basicConstraints.getPathLenConstraint() != null) debug("Basic Constraints: pathLen=" + basicConstraints.getPathLenConstraint().intValue()); if (!basicConstraints.isCA()) throw new GeneralSecurityException( "Basic Constraints CA = true not set for issuer in chain"); } else { throw new GeneralSecurityException("Basic Constraints CA = true not set for issuer in chain"); } } catch (IOException e) { throw new GeneralSecurityException("Basic Constraints CA = error reading extension"); } } }
From source file:com.otterca.common.crypto.acceptance.X509CertificateBuilderAcceptanceTest.java
/** * Test builder with unlimited pathlength value. * /*from w w w. ja v a 2 s. c om*/ * @throws Exception */ @Test public void testBuilderCertWithUnlimitedPathLength() throws GeneralSecurityException { // create grandparent certificate populate(builder); builder.setSubject(GRANDFATHER_NAME); builder.setIssuer(GRANDFATHER_NAME); builder.setPublicKey(grandfatherKeyPair.getPublic()); builder.setBasicConstraints(true); X509Certificate grandfather = builder.build(grandfatherKeyPair.getPrivate()); assertEquals(grandfather.getBasicConstraints(), Integer.MAX_VALUE); builder.reset(); // create issuer certificate populate(builder); builder.setSubject(ISSUER_NAME); builder.setIssuer(grandfather); builder.setBasicConstraints(true, 0); builder.setPublicKey(issuerKeyPair.getPublic()); X509Certificate issuer = builder.build(issuerKeyPair.getPrivate()); assertEquals(issuer.getBasicConstraints(), 0); }
From source file:com.otterca.common.crypto.acceptance.X509CertificateBuilderAcceptanceTest.java
/** * Test builder with insufficent pathlength value. * // w w w .ja va 2 s . com * @throws Exception * // assertTrue( // * cert.getNonCriticalExtensionOIDs().contains( * X509Extensions.NameConstraints.getId()), // * "certificate does not contain expected Name Constraints extension" * ); */ @Test(expectedExceptions = X509CertificateBuilderException.class) public void testBuilderCertWithBadPathLength() throws GeneralSecurityException { // create grandparent certificate populate(builder); builder.setSubject(GRANDFATHER_NAME); builder.setIssuer(GRANDFATHER_NAME); builder.setPublicKey(grandfatherKeyPair.getPublic()); builder.setBasicConstraints(true, 0); X509Certificate grandfather = builder.build(grandfatherKeyPair.getPrivate()); assertEquals(grandfather.getBasicConstraints(), 0); builder.reset(); // create issuer certificate populate(builder); builder.setSubject(ISSUER_NAME); builder.setIssuer(grandfather); builder.setBasicConstraints(true, 0); builder.setPublicKey(issuerKeyPair.getPublic()); X509Certificate issuer = builder.build(issuerKeyPair.getPrivate()); assertEquals(issuer.getBasicConstraints(), -1); builder.reset(); // create subject certificate populate(builder); builder.setIssuer(issuer); builder.build(keyPair.getPrivate()); }
From source file:com.otterca.common.crypto.acceptance.X509CertificateBuilderAcceptanceTest.java
/** * Test builder with sufficent pathlength value. * // w ww .j ava2 s.c om * @throws Exception */ @Test public void testBuilderCertWithSufficientPathLength() throws GeneralSecurityException { // create grandparent certificate populate(builder); builder.setSubject(GRANDFATHER_NAME); builder.setIssuer(GRANDFATHER_NAME); builder.setPublicKey(grandfatherKeyPair.getPublic()); builder.setBasicConstraints(true, 1); X509Certificate grandfather = builder.build(grandfatherKeyPair.getPrivate()); assertEquals(grandfather.getBasicConstraints(), 1); builder.reset(); // create issuer certificate populate(builder); builder.setSubject(ISSUER_NAME); builder.setIssuer(grandfather); builder.setBasicConstraints(true, 0); builder.setPublicKey(issuerKeyPair.getPublic()); X509Certificate issuer = builder.build(issuerKeyPair.getPrivate()); assertEquals(issuer.getBasicConstraints(), 0); builder.reset(); // create subject certificate populate(builder); builder.setSubject(SUBJECT_NAME); builder.setIssuer(issuer); X509Certificate cert = builder.build(keyPair.getPrivate()); assertEquals(cert.getBasicConstraints(), -1); }
From source file:org.jasig.cas.adaptors.x509.authentication.handler.support.X509CredentialsAuthenticationHandler.java
protected final boolean doAuthentication(final Credentials credentials) throws AuthenticationException { final X509CertificateCredentials x509Credentials = (X509CertificateCredentials) credentials; final X509Certificate[] certificates = x509Credentials.getCertificates(); /*//from ww w. j a va 2s. com * the certificate that was fully authenticated succesfully will be set * as the user credentials for CAS last certificate that can be set is * the end-user certificate */ X509Certificate certificateCredentialsCandidate = null; // flag to check whether a trusted issuer is in the certificate chain boolean hasTrustedIssuerInChain = false; /* * reverse transversal of certificates (should be from root to end-user * cert) */ for (int i = (certificates.length - 1); i >= 0; i--) { final X509Certificate certificate = certificates[i]; try { final Principal issuerPrincipal = certificate.getIssuerDN(); // flag that is set when this cert is an end user cert (no CA // cert) boolean isEndUserCertificate = false; if (log.isDebugEnabled()) { log.debug("--examining cert[" + certificate.getSerialNumber().toString() + "] " + certificate.getSubjectDN() + "\"" + " from issuer \"" + issuerPrincipal.getName() + "\""); } // check basic validity of the current certificate certificate.checkValidity(); log.debug("certificate is valid"); // initial check for trusted issuer in certificate chain // final check is done outside for loop if (isCertificateFromTrustedIssuer(issuerPrincipal)) { hasTrustedIssuerInChain = true; log.debug("certificate was issued by trusted issuer"); } // getBasicConstraints returns pathLenContraint which is // >=0 when this is a CA cert and -1 when it's not int pathLength = certificate.getBasicConstraints(); if (pathLength != -1) { log.debug("this is a CA certificate"); // check pathLength when CA cert //if unlimited/unspecified and unlimited/unspecified not allowed: warn+stop if (pathLength == Integer.MAX_VALUE && this.maxPathLength_allowUnspecified != true) { if (log.isWarnEnabled()) { log.warn("authentication failed; cert pathLength not specified" + " and unlimited/unspecified not allowed by config [see maxPathLength_allow_unlimited]"); } return false; //else if more than allowed length but not unlimited/unspecified: warn+stop } else if (pathLength > this.maxPathLength && pathLength < Integer.MAX_VALUE) { if (log.isWarnEnabled()) { log.warn("authentication failed; cert pathLength [" + pathLength + "] is more than allowed by config [" + this.maxPathLength + "]"); } return false; } } else { isEndUserCertificate = true; log.debug("this is an end-user certificate"); } /* * set this certificate as the user credentials if there is an * issuer in the cert (always so if valid cert) and this is an * end-user or CA certificate (so not a CA cert) and optional * KeyUsage check */ if (issuerPrincipal != null && isEndUserCertificate && this.doesCertificateSubjectDnMatchPattern(certificate.getSubjectDN()) && (!this.checkKeyUsage || (this.checkKeyUsage && this.doesCertificateKeyUsageMatch(certificate)))) { if (log.isDebugEnabled()) { log.debug("cert[" + certificate.getSerialNumber().toString() + "] ok, setting as credentials candidate"); } certificateCredentialsCandidate = certificate; } } catch (final CertificateExpiredException e) { log.warn("authentication failed; certficiate expired [" + certificate.toString() + "]"); certificateCredentialsCandidate = null; } catch (final CertificateNotYetValidException e) { log.warn("authentication failed; certficate not yet valid [" + certificate.toString() + "]"); certificateCredentialsCandidate = null; } } // check whether one of the certificates in the chain was // from the trusted issuer; else => fail auth if (certificateCredentialsCandidate != null && hasTrustedIssuerInChain) { if (log.isInfoEnabled()) { log.info("authentication OK; SSL client authentication data meets criteria for cert[" + certificateCredentialsCandidate.getSerialNumber().toString() + "]"); } x509Credentials.setCertificate(certificateCredentialsCandidate); return true; } if (log.isInfoEnabled()) { if (!hasTrustedIssuerInChain) { log.info("client cert did not have trusted issuer pattern \"" + this.regExTrustedIssuerDnPattern.pattern() + "\" in chain; authentication failed"); } else { log.info("authentication failed; SSL client authentication data doesn't meet criteria"); } } return false; }
From source file:org.ejbca.util.CertTools.java
/** * Checks if a certificate is a CA certificate according to BasicConstraints (X.509), or role (CVC). * If there is no basic constraints extension on a X.509 certificate, false is returned. * * @param cert the certificate that skall be checked. * * @return boolean true if the certificate belongs to a CA. */// w ww . j a v a 2s . c o m public static boolean isCA(Certificate cert) { log.trace(">isCA"); boolean ret = false; if (cert instanceof X509Certificate) { X509Certificate x509cert = (X509Certificate) cert; if (x509cert.getBasicConstraints() > -1) { ret = true; } } else if (StringUtils.equals(cert.getType(), "CVC")) { CardVerifiableCertificate cvccert = (CardVerifiableCertificate) cert; try { CVCAuthorizationTemplate templ = cvccert.getCVCertificate().getCertificateBody() .getAuthorizationTemplate(); AuthorizationRoleEnum role = templ.getAuthorizationField().getRole(); if (role.equals(AuthorizationRoleEnum.CVCA) || role.equals(AuthorizationRoleEnum.DV_D) || role.equals(AuthorizationRoleEnum.DV_F)) { ret = true; } } catch (NoSuchFieldException e) { log.error("NoSuchFieldException: ", e); } } if (log.isTraceEnabled()) { log.trace("<isCA:" + ret); } return ret; }
From source file:test.unit.org.owasp.webscarab.util.SunCertificateUtilsTest.java
@Test public void testSign() throws Exception { // setup// w w w . ja v a2s . c om KeyPair caKeyPair = generateKeyPair(); KeyPair entityKeyPair = generateKeyPair(); X500Principal subject = new X500Principal("CN=Test"); PublicKey pubKey = entityKeyPair.getPublic(); X500Principal issuer = new X500Principal("CN=CA"); PublicKey caPubKey = caKeyPair.getPublic(); PrivateKey caKey = caKeyPair.getPrivate(); Date begin = new Date(); Date ends = new Date(begin.getTime() + (long) 1000 * 60 * 60 * 24 * 30); BigInteger serialNo = BigInteger.valueOf(1234); JcaX509ExtensionUtils jxeu = new JcaX509ExtensionUtils(); // operate X509Certificate resultCert = SunCertificateUtils.sign(subject, pubKey, issuer, caPubKey, caKey, begin, ends, serialNo, null); // verify assertNotNull(resultCert); LOG.debug("result certificate: " + resultCert); resultCert.verify(caPubKey); assertEquals(subject, resultCert.getSubjectX500Principal()); assertEquals(issuer, resultCert.getIssuerX500Principal()); assertEquals(serialNo, resultCert.getSerialNumber()); assertEquals(pubKey, resultCert.getPublicKey()); LOG.debug("expected begin: " + begin.getTime()); LOG.debug("actual begin: " + resultCert.getNotBefore().getTime()); /* * BouncyCastle drops the milliseconds. */ assertTrue(Math.abs(begin.getTime() - resultCert.getNotBefore().getTime()) < 1000); assertTrue(Math.abs(ends.getTime() - resultCert.getNotAfter().getTime()) < 1000); byte[] subjectKeyIdentifierExtValue = resultCert .getExtensionValue(X509Extension.subjectKeyIdentifier.getId()); assertNotNull(subjectKeyIdentifierExtValue); ASN1Primitive subjectKeyIdentifier = JcaX509ExtensionUtils .parseExtensionValue(subjectKeyIdentifierExtValue); ASN1Primitive expSKI = jxeu.createSubjectKeyIdentifier(pubKey).toASN1Primitive(); assertArrayEquals(expSKI.getEncoded(), subjectKeyIdentifier.getEncoded()); byte[] authorityKeyIdentifierExtValue = resultCert .getExtensionValue(X509Extension.authorityKeyIdentifier.getId()); ASN1Primitive authorityKeyIdentifier = JcaX509ExtensionUtils .parseExtensionValue(authorityKeyIdentifierExtValue); ASN1Primitive expAKI = jxeu.createAuthorityKeyIdentifier(caPubKey).toASN1Primitive(); assertArrayEquals(expAKI.getEncoded(), authorityKeyIdentifier.getEncoded()); assertEquals(-1, resultCert.getBasicConstraints()); byte[] netscapeCertTypeExtValue = resultCert .getExtensionValue(MiscObjectIdentifiers.netscapeCertType.getId()); assertNotNull(netscapeCertTypeExtValue); DERBitString netscapeCertTypeExt = (DERBitString) X509ExtensionUtil .fromExtensionValue(netscapeCertTypeExtValue); NetscapeCertType netscapeCertType = new NetscapeCertType(netscapeCertTypeExt); assertEquals(NetscapeCertType.sslClient, netscapeCertType.intValue() & NetscapeCertType.sslClient); assertEquals(NetscapeCertType.sslServer, netscapeCertType.intValue() & NetscapeCertType.sslServer); assertTrue(resultCert.getKeyUsage()[0]); assertTrue(resultCert.getKeyUsage()[2]); byte[] extendedKeyUsageExtValue = resultCert.getExtensionValue(X509Extension.extendedKeyUsage.getId()); assertNotNull(extendedKeyUsageExtValue); ExtendedKeyUsage extendedKeyUsage = ExtendedKeyUsage .getInstance(X509ExtensionUtil.fromExtensionValue(extendedKeyUsageExtValue)); assertTrue(extendedKeyUsage.hasKeyPurposeId(KeyPurposeId.id_kp_clientAuth)); assertTrue(extendedKeyUsage.hasKeyPurposeId(KeyPurposeId.id_kp_serverAuth)); }
From source file:be.fedict.trust.PublicKeyTrustLinker.java
public TrustLinkerResult hasTrustLink(X509Certificate childCertificate, X509Certificate certificate, Date validationDate, RevocationData revocationData) { if (false == childCertificate.getIssuerX500Principal().equals(certificate.getSubjectX500Principal())) { LOG.debug("child certificate issuer not the same as the issuer certificate subject"); LOG.debug("child certificate: " + childCertificate.getSubjectX500Principal()); LOG.debug("certificate: " + certificate.getSubjectX500Principal()); LOG.debug("child certificate issuer: " + childCertificate.getIssuerX500Principal()); return new TrustLinkerResult(false, TrustLinkerResultReason.INVALID_TRUST, "child certificate issuer not the same as the issuer certificate subject"); }//from w w w .j a v a 2 s. com try { childCertificate.verify(certificate.getPublicKey()); } catch (Exception e) { LOG.debug("verification error: " + e.getMessage(), e); return new TrustLinkerResult(false, TrustLinkerResultReason.INVALID_SIGNATURE, "verification error: " + e.getMessage()); } if (true == childCertificate.getNotAfter().after(certificate.getNotAfter())) { LOG.warn("child certificate validity end is after certificate validity end"); LOG.warn("child certificate validity end: " + childCertificate.getNotAfter()); LOG.warn("certificate validity end: " + certificate.getNotAfter()); } if (true == childCertificate.getNotBefore().before(certificate.getNotBefore())) { LOG.warn("child certificate validity begin before certificate validity begin"); LOG.warn("child certificate validity begin: " + childCertificate.getNotBefore()); LOG.warn("certificate validity begin: " + certificate.getNotBefore()); } if (true == validationDate.before(childCertificate.getNotBefore())) { LOG.debug("certificate is not yet valid"); return new TrustLinkerResult(false, TrustLinkerResultReason.INVALID_VALIDITY_INTERVAL, "certificate is not yet valid"); } if (true == validationDate.after(childCertificate.getNotAfter())) { LOG.debug("certificate already expired"); return new TrustLinkerResult(false, TrustLinkerResultReason.INVALID_VALIDITY_INTERVAL, "certificate already expired"); } if (-1 == certificate.getBasicConstraints()) { LOG.debug("certificate not a CA"); return new TrustLinkerResult(false, TrustLinkerResultReason.INVALID_TRUST, "certificate not a CA"); } if (0 == certificate.getBasicConstraints() && -1 != childCertificate.getBasicConstraints()) { LOG.debug("child should not be a CA"); return new TrustLinkerResult(false, TrustLinkerResultReason.INVALID_TRUST, "child should not be a CA"); } /* * SKID/AKID sanity check */ boolean isCa = isCa(certificate); boolean isChildCa = isCa(childCertificate); byte[] subjectKeyIdentifierData = certificate .getExtensionValue(X509Extensions.SubjectKeyIdentifier.getId()); byte[] authorityKeyIdentifierData = childCertificate .getExtensionValue(X509Extensions.AuthorityKeyIdentifier.getId()); if (isCa && null == subjectKeyIdentifierData) { LOG.debug("certificate is CA and MUST contain a Subject Key Identifier"); return new TrustLinkerResult(false, TrustLinkerResultReason.INVALID_TRUST, "certificate is CA and MUST contain a Subject Key Identifier"); } if (isChildCa && null == authorityKeyIdentifierData) { LOG.debug("child certificate is CA and MUST contain an Authority Key Identifier"); return new TrustLinkerResult(false, TrustLinkerResultReason.INVALID_TRUST, "child certificate is CA and MUST contain an Authority Key Identifier"); } if (null != subjectKeyIdentifierData && null != authorityKeyIdentifierData) { AuthorityKeyIdentifierStructure authorityKeyIdentifierStructure; try { authorityKeyIdentifierStructure = new AuthorityKeyIdentifierStructure(authorityKeyIdentifierData); } catch (IOException e) { LOG.debug("Error parsing authority key identifier structure"); return new TrustLinkerResult(false, TrustLinkerResultReason.INVALID_TRUST, "Error parsing authority key identifier structure"); } String akidId = new String(Hex.encodeHex(authorityKeyIdentifierStructure.getKeyIdentifier())); SubjectKeyIdentifierStructure subjectKeyIdentifierStructure; try { subjectKeyIdentifierStructure = new SubjectKeyIdentifierStructure(subjectKeyIdentifierData); } catch (IOException e) { LOG.debug("Error parsing subject key identifier structure"); return new TrustLinkerResult(false, TrustLinkerResultReason.INVALID_TRUST, "Error parsing subject key identifier structure"); } String skidId = new String(Hex.encodeHex(subjectKeyIdentifierStructure.getKeyIdentifier())); if (!skidId.equals(akidId)) { LOG.debug( "certificate's subject key identifier does not match child certificate's authority key identifier"); return new TrustLinkerResult(false, TrustLinkerResultReason.INVALID_TRUST, "certificate's subject key identifier does not match child certificate's authority key identifier"); } } /* * We don't check pathLenConstraint since this one is only there to * protect the PKI business. */ return null; }