Example usage for java.security.cert X509Certificate getKeyUsage

List of usage examples for java.security.cert X509Certificate getKeyUsage

Introduction

In this page you can find the example usage for java.security.cert X509Certificate getKeyUsage.

Prototype

public abstract boolean[] getKeyUsage();

Source Link

Document

Gets a boolean array representing bits of the KeyUsage extension, (OID = 2.5.29.15).

Usage

From source file:be.fedict.eidviewer.lib.X509Utilities.java

public static boolean hasDigitalSignatureConstraint(X509Certificate certificate) {
    return certificate.getKeyUsage()[CONSTRAINT_DIGITALSIGNATURE];
}

From source file:be.fedict.eidviewer.lib.X509Utilities.java

public static boolean hasNonRepudiationConstraint(X509Certificate certificate) {
    return certificate.getKeyUsage()[CONSTRAINT_NONREPUDIATION];
}

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

/**
 * Returns a (possibly empty) set of key usages of the given certificate or
 * null if there are no KeyUsages.//from  w  ww.j  a  v a2s .  c  o  m
 */
public static Set<KeyUsageType> getKeyUsage(X509Certificate certificate) {
    Set<KeyUsageType> keyUsages = null;

    boolean[] keyUsageArray = certificate.getKeyUsage();

    if (keyUsageArray != null) {
        keyUsages = new HashSet<KeyUsageType>();

        for (int tag = 0; tag < keyUsageArray.length; tag++) {
            if (keyUsageArray[tag] == true) {
                KeyUsageType keyUsage = KeyUsageType.fromTag(tag);

                if (keyUsage != null) {
                    keyUsages.add(keyUsage);
                }
            }
        }
    }

    return keyUsages;
}

From source file:be.fedict.eid.tsl.Tsl2PdfExporter.java

private static List<String> getKeyUsage(final X509Certificate cert) {
    final boolean[] keyUsage = cert.getKeyUsage();
    if (keyUsage != null) {
        final List<String> ret = new LinkedList<String>();
        for (int i = 0; i < keyUsage.length; ++i) {
            if (keyUsage[i]) {
                if (i < keyUsageLabels.length) {
                    ret.add(keyUsageLabels[i]);
                } else {
                    ret.add(String.valueOf(i));
                }//from   w w w.j  a  v  a2 s .co  m
            }
        }
        return ret;
    } else {
        return null;
    }
}

From source file:be.fedict.trust.constraints.KeyUsageCertificateConstraint.java

public boolean check(X509Certificate certificate) {
    boolean[] keyUsage = certificate.getKeyUsage();
    if (null == keyUsage) {
        LOG.debug("no key usage extension for certificate: " + certificate.getSubjectX500Principal());
        return false;
    }//from  ww  w .  j a v  a 2  s .c  om
    for (int idx = 0; idx < this.mask.length; idx++) {
        Boolean flag = this.mask[idx];
        if (null == flag) {
            continue;
        }
        if (false == flag) {
            if (keyUsage[idx]) {
                LOG.debug("should not have key usage: " + idx);
                return false;
            }
        } else {
            if (false == keyUsage[idx]) {
                LOG.debug("missing key usage: " + idx);
                return false;
            }
        }
    }
    LOG.debug("key usage checked");
    return true;
}

From source file:be.fedict.trust.crl.CrlTrustLinker.java

/**
 * Checks the integrity of the given X509 CRL.
 * //from w  ww  .  j  av a2  s.c om
 * @param x509crl
 *            the X509 CRL to verify the integrity.
 * @param issuerCertificate
 *            the assumed issuer of the given X509 CRL.
 * @param validationDate
 *            the validate date.
 * @return <code>true</code> if integrity is OK, <code>false</code>
 *         otherwise.
 */
public static boolean checkCrlIntegrity(X509CRL x509crl, X509Certificate issuerCertificate,
        Date validationDate) {
    if (false == x509crl.getIssuerX500Principal().equals(issuerCertificate.getSubjectX500Principal())) {
        return false;
    }
    try {
        x509crl.verify(issuerCertificate.getPublicKey());
    } catch (Exception e) {
        return false;
    }
    Date thisUpdate = x509crl.getThisUpdate();
    LOG.debug("validation date: " + validationDate);
    LOG.debug("CRL this update: " + thisUpdate);
    if (thisUpdate.after(validationDate)) {
        LOG.warn("CRL too young");
        return false;
    }
    LOG.debug("CRL next update: " + x509crl.getNextUpdate());
    if (validationDate.after(x509crl.getNextUpdate())) {
        LOG.debug("CRL too old");
        return false;
    }

    // assert cRLSign KeyUsage bit
    if (null == issuerCertificate.getKeyUsage()) {
        LOG.debug("No KeyUsage extension for CRL issuing certificate");
        return false;
    }

    if (false == issuerCertificate.getKeyUsage()[6]) {
        LOG.debug("cRLSign bit not set for CRL issuing certificate");
        return false;
    }

    return true;
}

From source file:eu.europa.ejusticeportal.dss.applet.model.token.CertificateDisplayUtils.java

/**
 * Get the information from the certificate to allow it to be displayed in human readable form.
 * /*from w  w w.  j av  a  2 s  . co  m*/
 * @param keyEntry the DSSPrivateKeyEntry
 * @return the CertificateDisplayName
 */
public static CertificateDisplayDetails getDisplayDetails(DSSPrivateKeyEntry keyEntry, CardProfile cp) {
    final X509Certificate cert = (X509Certificate) keyEntry.getCertificate();
    String subjectDN = cert.getSubjectDN().getName();
    Map<String, String> parts = parseLdapName(subjectDN);
    if (parts.get("CN") != null) {
        subjectDN = parts.get("CN");
    }
    String issuerDN = cert.getIssuerX500Principal() == null ? "" : cert.getIssuerX500Principal().getName();

    parts = parseLdapName(issuerDN);
    String issuerCountry = parts.get("C") == null ? "" : parts.get("C");

    String issuerName = parts.get("CN") == null ? "" : parts.get("CN");
    if (parts.get("O") != null) {
        issuerName += ", " + parts.get("O");
    }
    String serialNumber = formatSerialNumber(cert.getSerialNumber());
    CertificateDisplayDetails cdd = new CertificateDisplayDetails(subjectDN, issuerName, issuerCountry,
            serialNumber, digest(cert), qualified(cert), sscd(cert), cert.getKeyUsage(), cert, cp,
            extensions(cert));
    //check the expiration/start date
    valid(cdd);
    cdd.setSummaryInfo(summaryInfo(subjectDN, issuerName, issuerCountry, serialNumber, cdd.getStartDate(),
            cdd.getExpirationDate()));
    return cdd;
}

From source file:net.sf.jsignpdf.utils.KeyStoreUtils.java

/**
 * Returns list of key aliases in given keystore.
 * /*from  w ww  .  j  ava2 s .c o m*/
 * @param aKs
 * @param options
 * @return
 */
private static List<String> getAliasesList(final KeyStore aKs, final BasicSignerOptions options) {
    if (options == null) {
        throw new NullPointerException("Options are empty.");
    }
    if (aKs == null) {
        throw new NullPointerException(RES.get("error.keystoreNull"));
    }
    final List<String> tmpResult = new ArrayList<String>();
    try {
        LOGGER.info(RES.get("console.getAliases"));
        final Enumeration<String> tmpAliases = aKs.aliases();
        final boolean checkValidity = ConfigProvider.getInstance().getAsBool("certificate.checkValidity", true);
        final boolean checkKeyUsage = ConfigProvider.getInstance().getAsBool("certificate.checkKeyUsage", true);
        final boolean checkCriticalExtensions = ConfigProvider.getInstance()
                .getAsBool("certificate.checkCriticalExtensions", true);
        while (tmpAliases.hasMoreElements()) {
            String tmpAlias = tmpAliases.nextElement();
            if (aKs.isKeyEntry(tmpAlias)) {
                final Certificate tmpCert = aKs.getCertificate(tmpAlias);
                boolean tmpAddAlias = true;
                if (tmpCert instanceof X509Certificate) {
                    final X509Certificate tmpX509 = (X509Certificate) tmpCert;
                    if (checkValidity) {
                        try {
                            tmpX509.checkValidity();
                        } catch (CertificateExpiredException e) {
                            LOGGER.info(RES.get("console.certificateExpired", tmpAlias));
                            tmpAddAlias = false;
                        } catch (CertificateNotYetValidException e) {
                            LOGGER.info(RES.get("console.certificateNotYetValid", tmpAlias));
                            tmpAddAlias = false;
                        }
                    }
                    if (checkKeyUsage) {
                        // check if the certificate is supposed to be
                        // used for digital signatures
                        final boolean keyUsage[] = tmpX509.getKeyUsage();
                        if (keyUsage != null && keyUsage.length > 0) {
                            // KeyUsage ::= BIT STRING {
                            // digitalSignature (0),
                            // nonRepudiation (1),
                            // keyEncipherment (2),
                            // dataEncipherment (3),
                            // keyAgreement (4),
                            // keyCertSign (5),
                            // cRLSign (6),
                            // encipherOnly (7),
                            // decipherOnly (8) }
                            if (!(keyUsage[0] || keyUsage[1])) {
                                LOGGER.info(RES.get("console.certificateNotForSignature", tmpAlias));
                                tmpAddAlias = false;
                            }
                        }
                    }
                    // check critical extensions
                    if (checkCriticalExtensions) {
                        final Set<String> criticalExtensionOIDs = tmpX509.getCriticalExtensionOIDs();
                        if (criticalExtensionOIDs != null) {
                            for (String oid : criticalExtensionOIDs) {
                                if (!Constants.SUPPORTED_CRITICAL_EXTENSION_OIDS.contains(oid)) {
                                    LOGGER.info(
                                            RES.get("console.criticalExtensionNotSupported", tmpAlias, oid));
                                    tmpAddAlias = false;
                                }
                            }
                        }
                    }
                }
                if (tmpAddAlias) {
                    tmpResult.add(tmpAlias);
                }
            }
        }
    } catch (Exception e) {
        LOGGER.error(RES.get("console.exception"), e);
    }
    return tmpResult;
}

From source file:com.lastdaywaiting.example.kalkan.service.SecureManager.java

/**
 * ?   ? ?? ?? '?'. /*from   ww  w  .  j ava2s .c  o  m*/
 * @param signers
 * @param clientCerts
 * @return
 * @throws CertStoreException 
 */
private boolean isBadKeyUsage(SignerInformationStore signers, CertStore clientCerts) throws CertStoreException {
    if (signers.getSigners().size() == 0) {
        verifyErrorMsg = "    ?.";
        return true;
    }
    Iterator it = signers.getSigners().iterator();
    while (it.hasNext()) {
        SignerInformation signer = (SignerInformation) it.next();
        X509CertSelector signerConstraints = signer.getSID();
        Collection certCollection = clientCerts.getCertificates(signerConstraints);
        Iterator certIt = certCollection.iterator();
        if (certCollection.size() == 0) {
            verifyErrorMsg = "    ?  ? .";
            return true;
        }
        while (certIt.hasNext()) {
            X509Certificate cert = (X509Certificate) certIt.next();
            if (cert.getKeyUsage()[0] && cert.getKeyUsage()[1]) {
                continue;
            } else {
                verifyErrorMsg = "? ??   ? ? c  '??'.";
                return true;
            }
        }
    }
    return false;
}

From source file:eu.europa.ec.markt.dss.validation.crl.OnlineCRLSource.java

@Override
public X509CRL findCrl(final X509Certificate cert, final X509Certificate issuerCert) throws DSSException {

    final String crlURL = getCrlUri(cert);
    LOG.info("CRL's URL for " + CertificateIdentifier.getIdAsString(cert) + " : " + crlURL);
    if (crlURL == null) {

        return null;
    }/*from   w  ww .  ja va2 s . com*/
    X509CRL x509CRL;
    boolean http = crlURL.startsWith("http://") || crlURL.startsWith("https://");
    if (dataLoader != null && http) {

        x509CRL = downloadCrlFromHTTP(crlURL);
    } else if (http || crlURL.startsWith("ftp://")) {

        x509CRL = downloadCRLFromURL(crlURL);
    } else if (crlURL.startsWith("ldap://")) {

        x509CRL = downloadCRLFromLDAP_(crlURL);
    } else {

        LOG.warning("DSS framework only supports HTTP, HTTPS, FTP and LDAP CRL's url.");
        return null;
    }
    if (x509CRL == null) {

        return null;
    }
    try {

        x509CRL.verify(issuerCert.getPublicKey());
    } catch (Exception e) {

        LOG.warning("The CRL signature is not valid!");
        return null;
    }
    // assert CRLSign KeyUsage bit
    final boolean[] keyUsage = issuerCert.getKeyUsage();
    if (keyUsage == null || (keyUsage != null && !keyUsage[6])) {

        LOG.warning("No KeyUsage extension for CRL issuing certificate!");
        return null;
    }
    return x509CRL;
}