Example usage for org.bouncycastle.asn1.x509 BasicConstraints getInstance

List of usage examples for org.bouncycastle.asn1.x509 BasicConstraints getInstance

Introduction

In this page you can find the example usage for org.bouncycastle.asn1.x509 BasicConstraints getInstance.

Prototype

public static BasicConstraints getInstance(Object obj) 

Source Link

Usage

From source file:be.fedict.trust.linker.PublicKeyTrustLinker.java

License:Open Source License

private boolean isCa(X509Certificate certificate) {
    byte[] basicConstraintsValue = certificate.getExtensionValue(Extension.basicConstraints.getId());
    if (null == basicConstraintsValue) {
        return false;
    }//w  ww .j av  a 2s .  co m

    ASN1Encodable basicConstraintsDecoded;
    try {
        basicConstraintsDecoded = X509ExtensionUtil.fromExtensionValue(basicConstraintsValue);
    } catch (IOException e) {
        LOG.error("IO error", e);
        return false;
    }
    if (false == basicConstraintsDecoded instanceof ASN1Sequence) {
        LOG.debug("basic constraints extension is not an ASN1 sequence");
        return false;
    }
    ASN1Sequence basicConstraintsSequence = (ASN1Sequence) basicConstraintsDecoded;
    BasicConstraints basicConstraints = BasicConstraints.getInstance(basicConstraintsSequence);
    return basicConstraints.isCA();
}

From source file:be.fedict.trust.PublicKeyTrustLinker.java

License:Open Source License

private boolean isCa(X509Certificate certificate) {

    byte[] basicConstraintsValue = certificate.getExtensionValue(X509Extensions.BasicConstraints.getId());
    if (null == basicConstraintsValue) {
        return false;
    }/*w w w.  j  av a  2 s  .c om*/

    ASN1Encodable basicConstraintsDecoded;
    try {
        basicConstraintsDecoded = X509ExtensionUtil.fromExtensionValue(basicConstraintsValue);
    } catch (IOException e) {
        LOG.error("IO error", e);
        return false;
    }
    if (false == basicConstraintsDecoded instanceof ASN1Sequence) {
        LOG.debug("basic constraints extension is not an ASN1 sequence");
        return false;
    }
    ASN1Sequence basicConstraintsSequence = (ASN1Sequence) basicConstraintsDecoded;
    BasicConstraints basicConstraints = BasicConstraints.getInstance(basicConstraintsSequence);

    return basicConstraints.isCA();
}

From source file:eu.emi.security.authn.x509.helpers.pkipath.bc.FixedBCPKIXCertPathReviewer.java

License:Open Source License

private void checkPathLength() {
    // init/* www .j av a2  s  .  c o  m*/
    int maxPathLength = n;
    int totalPathLength = 0;

    X509Certificate cert = null;

    for (int index = certs.size() - 1; index > 0; index--) {
        cert = (X509Certificate) certs.get(index);

        // l)

        if (!isSelfIssued(cert)) {
            if (maxPathLength <= 0) {
                ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.pathLenghtExtended");
                addError(msg);
            }
            maxPathLength--;
            totalPathLength++;
        }

        // m)

        BasicConstraints bc;
        try {
            bc = BasicConstraints.getInstance(getExtensionValue(cert, BASIC_CONSTRAINTS));
        } catch (AnnotatedException ae) {
            ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.processLengthConstError");
            addError(msg, index);
            bc = null;
        }

        if (bc != null) {
            BigInteger _pathLengthConstraint = bc.getPathLenConstraint();

            if (_pathLengthConstraint != null) {
                int _plc = _pathLengthConstraint.intValue();

                if (_plc < maxPathLength) {
                    maxPathLength = _plc;
                }
            }
        }

    }

    ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.totalPathLength",
            new Object[] { new Integer(totalPathLength) });

    addNotification(msg);
}

From source file:eu.emi.security.authn.x509.helpers.pkipath.bc.FixedBCPKIXCertPathReviewer.java

License:Open Source License

private void checkSignatures() {
    // 1.6.1 - Inputs

    // d)/* ww  w .  ja  v a 2 s. c  om*/

    TrustAnchor trust = null;
    X500Principal trustPrincipal = null;

    // validation date
    {
        ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.certPathValidDate",
                new Object[] { new TrustedInput(validDate), new TrustedInput(new Date()) });
        addNotification(msg);
    }

    // find trust anchors
    try {
        X509Certificate cert = (X509Certificate) certs.get(certs.size() - 1);
        Collection trustColl = getTrustAnchors(cert, pkixParams.getTrustAnchors());
        if (trustColl.size() > 1) {
            // conflicting trust anchors                
            ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.conflictingTrustAnchors",
                    new Object[] { new Integer(trustColl.size()),
                            new UntrustedInput(cert.getIssuerX500Principal()) });
            addError(msg);
        } else if (trustColl.isEmpty()) {
            ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.noTrustAnchorFound",
                    new Object[] { new UntrustedInput(cert.getIssuerX500Principal()),
                            new Integer(pkixParams.getTrustAnchors().size()) });
            addError(msg);
        } else {
            PublicKey trustPublicKey;
            trust = (TrustAnchor) trustColl.iterator().next();
            if (trust.getTrustedCert() != null) {
                trustPublicKey = trust.getTrustedCert().getPublicKey();
            } else {
                trustPublicKey = trust.getCAPublicKey();
            }
            try {
                CertPathValidatorUtilities.verifyX509Certificate(cert, trustPublicKey,
                        pkixParams.getSigProvider());
            } catch (SignatureException e) {
                ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.trustButInvalidCert");
                addError(msg);
            } catch (Exception e) {
                // do nothing, error occurs again later
            }
        }
    } catch (CertPathReviewerException cpre) {
        addError(cpre.getErrorMessage());
    } catch (Throwable t) {
        ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.unknown",
                new Object[] { new UntrustedInput(t.getMessage()), new UntrustedInput(t) });
        addError(msg);
    }

    if (trust != null) {
        // get the name of the trustAnchor
        X509Certificate sign = trust.getTrustedCert();
        try {
            if (sign != null) {
                trustPrincipal = getSubjectPrincipal(sign);
            } else {
                trustPrincipal = new X500Principal(trust.getCAName());
            }
        } catch (IllegalArgumentException ex) {
            ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.trustDNInvalid",
                    new Object[] { new UntrustedInput(trust.getCAName()) });
            addError(msg);
        }

        // test key usages of the trust anchor
        if (sign != null) {
            boolean[] ku = sign.getKeyUsage();
            if (ku != null && !ku[5]) {
                ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.trustKeyUsage");
                addNotification(msg);
            }
        }
    }

    // 1.6.2 - Initialization

    PublicKey workingPublicKey = null;
    X500Principal workingIssuerName = trustPrincipal;

    X509Certificate sign = null;

    if (trust != null) {
        sign = trust.getTrustedCert();

        if (sign != null) {
            workingPublicKey = sign.getPublicKey();
        } else {
            workingPublicKey = trust.getCAPublicKey();
        }

        try {
            getAlgorithmIdentifier(workingPublicKey);
        } catch (CertPathValidatorException ex) {
            ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.trustPubKeyError");
            addError(msg);
        }

    }

    // Basic cert checks

    X509Certificate cert = null;
    int i;

    for (int index = certs.size() - 1; index >= 0; index--) {
        //
        // i as defined in the algorithm description
        //
        i = n - index;

        //
        // set certificate to be checked in this round
        // sign and workingPublicKey and workingIssuerName are set
        // at the end of the for loop and initialied the
        // first time from the TrustAnchor
        //
        cert = (X509Certificate) certs.get(index);

        // verify signature
        if (workingPublicKey != null) {
            try {
                CertPathValidatorUtilities.verifyX509Certificate(cert, workingPublicKey,
                        pkixParams.getSigProvider());
            } catch (GeneralSecurityException ex) {
                ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.signatureNotVerified",
                        new Object[] { ex.getMessage(), ex, ex.getClass().getName() });
                addError(msg, index);
            }
        } else if (isSelfIssued(cert)) {
            try {
                CertPathValidatorUtilities.verifyX509Certificate(cert, cert.getPublicKey(),
                        pkixParams.getSigProvider());
                ErrorBundle msg = new ErrorBundle(RESOURCE_NAME,
                        "CertPathReviewer.rootKeyIsValidButNotATrustAnchor");
                addError(msg, index);
            } catch (GeneralSecurityException ex) {
                ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.signatureNotVerified",
                        new Object[] { ex.getMessage(), ex, ex.getClass().getName() });
                addError(msg, index);
            }
        } else {
            ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.NoIssuerPublicKey");
            // if there is an authority key extension add the serial and issuer of the missing certificate
            byte[] akiBytes = cert.getExtensionValue(X509Extensions.AuthorityKeyIdentifier.getId());
            if (akiBytes != null) {
                try {
                    AuthorityKeyIdentifier aki = AuthorityKeyIdentifier
                            .getInstance(X509ExtensionUtil.fromExtensionValue(akiBytes));
                    GeneralNames issuerNames = aki.getAuthorityCertIssuer();
                    if (issuerNames != null) {
                        GeneralName name = issuerNames.getNames()[0];
                        BigInteger serial = aki.getAuthorityCertSerialNumber();
                        if (serial != null) {
                            Object[] extraArgs = { new LocaleString(RESOURCE_NAME, "missingIssuer"), " \"",
                                    name, "\" ", new LocaleString(RESOURCE_NAME, "missingSerial"), " ",
                                    serial };
                            msg.setExtraArguments(extraArgs);
                        }
                    }
                } catch (IOException e) {
                    // ignore
                }
            }
            addError(msg, index);
        }

        // certificate valid?
        try {
            cert.checkValidity(validDate);
        } catch (CertificateNotYetValidException cnve) {
            ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.certificateNotYetValid",
                    new Object[] { new TrustedInput(cert.getNotBefore()) });
            addError(msg, index);
        } catch (CertificateExpiredException cee) {
            ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.certificateExpired",
                    new Object[] { new TrustedInput(cert.getNotAfter()) });
            addError(msg, index);
        }

        // certificate revoked?
        if (pkixParams.isRevocationEnabled()) {
            try {
                checkRevocation(pkixParams, cert, validDate, sign, workingPublicKey);
            } catch (SimpleValidationErrorException e) {
                addError(e, index);
            }
        }

        // certificate issuer correct
        if (workingIssuerName != null && !cert.getIssuerX500Principal().equals(workingIssuerName)) {
            ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.certWrongIssuer",
                    new Object[] { workingIssuerName.getName(), cert.getIssuerX500Principal().getName() });
            addError(msg, index);
        }

        //
        // prepare for next certificate
        //
        if (i != n) {

            if (cert != null && cert.getVersion() == 1) {
                ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.noCACert");
                addError(msg, index);
            }

            // k)

            BasicConstraints bc;
            try {
                bc = BasicConstraints.getInstance(getExtensionValue(cert, BASIC_CONSTRAINTS));
                if (bc != null) {
                    if (!bc.isCA()) {
                        ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.noCACert");
                        addError(msg, index);
                    }
                } else {
                    ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.noBasicConstraints");
                    addError(msg, index);
                }
            } catch (AnnotatedException ae) {
                ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.errorProcesingBC");
                addError(msg, index);
            }

            // n)

            boolean[] _usage = cert.getKeyUsage();

            if ((_usage != null) && !_usage[KEY_CERT_SIGN]) {
                ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.noCertSign");
                addError(msg, index);
            }

        } // if

        // set signing certificate for next round
        sign = cert;

        // c)

        workingIssuerName = cert.getSubjectX500Principal();

        // d) e) f)

        try {
            workingPublicKey = getNextWorkingKey(certs, index);
            getAlgorithmIdentifier(workingPublicKey);
        } catch (CertPathValidatorException ex) {
            ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.pubKeyError");
            addError(msg, index);
        }

    } // for

    trustAnchor = trust;
    subjectPublicKey = workingPublicKey;
}

From source file:mitm.common.security.certificate.X509ExtensionInspector.java

License:Open Source License

/**
 * Returns the basic constraints if available. Null if not available 
 *///from w w w . j  av  a 2 s.  co  m
public static BasicConstraints getBasicConstraints(X509Extension extension) throws IOException {
    BasicConstraints basicConstraints = null;

    ASN1Object derBasicConstraints = ASN1Utils.getExtensionValue(extension,
            org.bouncycastle.asn1.x509.X509Extension.basicConstraints.getId());

    if (derBasicConstraints != null) {
        basicConstraints = BasicConstraints.getInstance(derBasicConstraints);
    }

    return basicConstraints;
}

From source file:net.ripe.rpki.commons.crypto.x509cert.X509CertificateUtil.java

License:BSD License

public static boolean isCa(X509Certificate certificate) {
    try {/*from ww w  .j  a  v a 2  s . c  o m*/
        byte[] basicConstraintsExtension = certificate
                .getExtensionValue(org.bouncycastle.asn1.x509.X509Extension.basicConstraints.getId());
        if (basicConstraintsExtension == null) {
            /**
             * The Basic Constraints extension field [...] MUST be present when
             * the Subject is a CA, and MUST NOT be present otherwise.
             * http://tools.ietf.org/html/draft-ietf-sidr-res-certs-21#section-4.9.1
             */
            return false;
        }
        BasicConstraints constraints = BasicConstraints
                .getInstance(X509ExtensionUtil.fromExtensionValue(basicConstraintsExtension));
        return constraints.isCA();
    } catch (IOException e) {
        throw new X509CertificateOperationException(e);
    }
}

From source file:net.ripe.rpki.commons.provisioning.cms.ProvisioningCmsObjectParser.java

License:BSD License

private boolean isEndEntityCertificate(X509Certificate certificate) {
    try {/*from w ww.  ja  v a2  s  .  c  o  m*/
        byte[] basicConstraintsExtension = certificate
                .getExtensionValue(X509Extension.basicConstraints.getId());
        if (basicConstraintsExtension == null) {
            /**
             * If the basic constraints extension is not present [...] then the certified public key MUST NOT be used
             * to verify certificate signatures.
             *  http://tools.ietf.org/html/rfc5280#section-4.2.1.9
             */
            return true;
        }
        BasicConstraints constraints = BasicConstraints
                .getInstance(X509ExtensionUtil.fromExtensionValue(basicConstraintsExtension));
        return !constraints.isCA();
    } catch (IOException e) {
        throw new ProvisioningCmsObjectParserException("error while reading cms object certificate", e);
    }
}

From source file:net.sf.keystore_explorer.crypto.x509.X509Ext.java

License:Open Source License

private String getBasicConstraintsStringValue(byte[] value) throws IOException {
    // @formatter:off

    /*/* w ww .j av a2  s  .  co  m*/
     * BasicConstraints ::= ASN1Sequence { cA ASN1Boolean DEFAULT FALSE,
     * pathLenConstraint ASN1Integer (0..MAX) OPTIONAL }
     */

    // @formatter:on

    /*
     * Getting the DEFAULT returns a false ASN1Boolean when no value present
     * which saves the bother of a null check
     */

    StringBuilder sb = new StringBuilder();

    BasicConstraints basicConstraints = BasicConstraints.getInstance(value);

    boolean ca = basicConstraints.isCA();
    BigInteger pathLenConstraint = basicConstraints.getPathLenConstraint();

    if (ca) {
        sb.append(res.getString("SubjectIsCa"));
        sb.append(NEWLINE);
    } else {
        sb.append(res.getString("SubjectIsNotCa"));
        sb.append(NEWLINE);
    }

    if (pathLenConstraint != null) {
        sb.append(MessageFormat.format(res.getString("PathLengthConstraint"), pathLenConstraint.intValue()));
        sb.append(NEWLINE);
    } else {
        sb.append(res.getString("NoPathLengthConstraint"));
        sb.append(NEWLINE);
    }

    return sb.toString();
}

From source file:net.sf.keystore_explorer.gui.dialogs.extensions.DBasicConstraints.java

License:Open Source License

private void prepopulateWithValue(byte[] value) throws IOException {
    BasicConstraints basicConstraints = BasicConstraints.getInstance(value);

    jcbSubjectIsCa.setSelected(basicConstraints.isCA());

    if (basicConstraints.getPathLenConstraint() != null) {
        jtfPathLengthConstraint.setText("" + basicConstraints.getPathLenConstraint().intValue());
        jtfPathLengthConstraint.setCaretPosition(0);
    }//from   w w w  .j av  a  2 s  . co m
}

From source file:net.sf.portecle.crypto.X509Ext.java

License:Open Source License

/**
 * Get Basic Constraints (2.5.29.19) extension value as a string.
 * /*from   ww  w . j  a  va 2 s . co m*/
 * <pre>
 * BasicConstraints ::= SEQUENCE {
 *     cA                      BOOLEAN DEFAULT FALSE,
 *     pathLenConstraint       INTEGER (0..MAX) OPTIONAL }
 * </pre>
 * 
 * @param bValue The octet string value
 * @return Extension value as a string
 * @throws IOException If an I/O problem occurs
 */
private String getBasicConstraintsStringValue(byte[] bValue) throws IOException {
    BasicConstraints bc = BasicConstraints.getInstance(bValue);
    StringBuilder strBuff = new StringBuilder();

    strBuff.append(RB.getString(bc.isCA() ? "SubjectIsCa" : "SubjectIsNotCa"));
    strBuff.append("<br><br>");

    BigInteger pathLen = bc.getPathLenConstraint();
    if (pathLen != null) {
        strBuff.append(MessageFormat.format(RB.getString("PathLengthConstraint"), pathLen));
    }

    return strBuff.toString();
}