Example usage for java.security.cert X509Certificate getExtensionValue

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

Introduction

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

Prototype

public byte[] getExtensionValue(String oid);

Source Link

Document

Gets the DER-encoded OCTET string for the extension value (extnValue) identified by the passed-in oid String.

Usage

From source file:org.josso.auth.scheme.X509CertificateAuthScheme.java

private byte[] getOIDBitStringValueFromCert(X509Certificate cert, String oid) throws Exception {

    byte[] derEncodedValue = cert.getExtensionValue(oid);
    byte[] extensionValue = null;

    DerValue dervalue = new DerValue(derEncodedValue);
    if (dervalue == null) {
        throw new IllegalArgumentException("extension not found for OID : " + oid);
    }//from  w  w w.  ja  va  2  s . c  o  m
    if (dervalue.tag != DerValue.tag_BitString) {
        throw new IllegalArgumentException("extension vaue for OID not of type BIT_STRING: " + oid);
    }

    extensionValue = dervalue.getBitString();

    byte extensionValueBytes[] = new byte[extensionValue.length - 2];

    System.arraycopy(extensionValue, 2, extensionValueBytes, 0, extensionValueBytes.length);

    return extensionValueBytes;
}

From source file:org.atricore.idbus.capabilities.clientcertauthn.X509CertificateAuthScheme.java

private byte[] getOIDBitStringValueFromCert(X509Certificate cert, String oid) throws Exception {

    byte[] derEncodedValue = cert.getExtensionValue(oid);
    byte[] extensionValue = null;

    DerValue dervalue = new DerValue(derEncodedValue);
    if (dervalue == null) {
        throw new IllegalArgumentException("extension not found for OID : " + oid);
    }//from ww w  .  j  a v  a 2 s. c  o m
    if (dervalue.tag != DerValue.tag_BitString) {
        throw new IllegalArgumentException("extension value for OID not of type BIT_STRING: " + oid);
    }

    extensionValue = dervalue.getBitString();

    byte extensionValueBytes[] = new byte[extensionValue.length - 2];

    System.arraycopy(extensionValue, 2, extensionValueBytes, 0, extensionValueBytes.length);

    return extensionValueBytes;
}

From source file:org.codice.ddf.security.ocsp.checker.OcspChecker.java

/**
 * Attempts to grab additional OCSP server urls off of the given {@param cert}.
 *
 * @param - the {@link X509Certificate} to check.
 * @return {@link List} of additional OCSP server urls found on the given {@param cert}.
 *//*from   w w  w  .  ja  v  a  2  s .com*/
private List<String> getOcspUrlsFromCert(X509Certificate cert) {
    List<String> ocspUrls = new ArrayList<>();

    try {
        byte[] authorityInfoAccess = cert.getExtensionValue(Extension.authorityInfoAccess.getId());

        if (authorityInfoAccess == null) {
            return ocspUrls;
        }

        AuthorityInformationAccess authorityInformationAccess = AuthorityInformationAccess
                .getInstance(X509ExtensionUtil.fromExtensionValue(authorityInfoAccess));

        if (authorityInformationAccess == null) {
            return ocspUrls;
        }

        for (AccessDescription description : authorityInformationAccess.getAccessDescriptions()) {
            GeneralName accessLocation = description.getAccessLocation();
            if (accessLocation.getTagNo() == GeneralName.uniformResourceIdentifier)
                ocspUrls.add(((DERIA5String) accessLocation.getName()).getString());
        }
    } catch (IOException e) {
        LOGGER.debug("Problem retrieving the OCSP server url(s) from the certificate." + CONTINUING_MSG, e);
    }

    return ocspUrls;
}

From source file:com.alfaariss.oa.profile.aselect.ws.security.OACrypto.java

/**
 * Validate a given certificate chain./*from  ww w  .  j  a  v a  2 s.  co  m*/
 * @see Crypto#validateCertPath(java.security.cert.X509Certificate[])
 */
public boolean validateCertPath(X509Certificate[] certs) throws WSSecurityException {
    boolean ok = false;
    try {
        // Generate cert path
        List<X509Certificate> certList = Arrays.asList(certs);
        CertPath path = this.getCertificateFactory().generateCertPath(certList);

        HashSet<TrustAnchor> set = new HashSet<TrustAnchor>();

        if (certs.length == 1) // Use factory certs
        {
            String alias = _factory.getAliasForX509Cert(certs[0].getIssuerDN().getName(),
                    certs[0].getSerialNumber());
            if (alias == null) {
                _logger.debug("Certificate not trusted");
                return false;
            }

            X509Certificate cert = (X509Certificate) _factory.getCertificate(alias);
            TrustAnchor anchor = new TrustAnchor(cert, cert.getExtensionValue("2.5.29.30"));
            set.add(anchor);
        } else {
            // Add certificates from the keystore
            Enumeration aliases = _factory.getAliases();
            while (aliases.hasMoreElements()) {
                String alias = (String) aliases.nextElement();
                X509Certificate cert = (X509Certificate) _factory.getCertificate(alias);
                TrustAnchor anchor = new TrustAnchor(cert, cert.getExtensionValue("2.5.29.30"));
                set.add(anchor);
            }
        }

        PKIXParameters param = new PKIXParameters(set);
        param.setRevocationEnabled(false);
        Provider provider = _factory.getKeyStore().getProvider();
        String sProvider = null;
        CertPathValidator certPathValidator = null;
        if (provider != null) {
            sProvider = provider.getName();
        }
        if (sProvider == null || sProvider.length() == 0) {
            certPathValidator = CertPathValidator.getInstance("PKIX");
        } else {
            certPathValidator = CertPathValidator.getInstance("PKIX", sProvider);
        }
        certPathValidator.validate(path, param);
        ok = true;
    } catch (NoSuchProviderException e) {
        _logger.warn("No such provider", e);
        throw new WSSecurityException(WSSecurityException.FAILURE, "certpath", new Object[] { e.getMessage() },
                e);
    } catch (NoSuchAlgorithmException e) {
        _logger.warn("No such algorithm", e);
        throw new WSSecurityException(WSSecurityException.FAILURE, "certpath", new Object[] { e.getMessage() },
                e);
    } catch (InvalidAlgorithmParameterException e) {
        _logger.warn("Invalid algorithm param", e);
        throw new WSSecurityException(WSSecurityException.FAILURE, "certpath", new Object[] { e.getMessage() },
                e);
    } catch (CertificateException e) {
        _logger.warn("Invalid certificate", e);
        throw new WSSecurityException(WSSecurityException.FAILURE, "certpath", new Object[] { e.getMessage() },
                e);
    } catch (ClassCastException e) {
        _logger.warn("Certificate is not an X509Certificate", e);
        throw new WSSecurityException(WSSecurityException.FAILURE, "certpath", new Object[] { e.getMessage() },
                e);
    } catch (CertPathValidatorException e) {
        _logger.warn("Could not validate Cert Path", e);
        throw new WSSecurityException(WSSecurityException.FAILURE, "certpath", new Object[] { e.getMessage() },
                e);
    } catch (CryptoException e) {
        throw new WSSecurityException(WSSecurityException.FAILURE, "certpath", new Object[] { e.getMessage() },
                e);
    }
    return ok;
}

From source file:com.netscape.cms.servlet.cert.RenewalProcessor.java

private BigInteger getSerialNumberFromCert(HttpServletRequest request) throws EBaseException {

    SSLClientCertProvider sslCCP = new SSLClientCertProvider(request);
    X509Certificate[] certs = sslCCP.getClientCertificateChain();

    if (certs == null || certs.length == 0) {
        CMS.debug("RenewalProcessor: missing SSL client certificate chain");
        throw new BadRequestException("Missing SSL client certificate chain");
    }/*from w  w w. jav a 2s  .  c  o  m*/

    CMS.debug("RenewalProcessor: has SSL client cert chain");
    // shouldn't expect leaf cert to be always at the
    // same location

    X509Certificate clientCert = null;
    for (X509Certificate cert : certs) {

        CMS.debug("RenewalProcessor: cert " + cert.getSubjectDN());
        clientCert = cert;

        byte[] extBytes = clientCert.getExtensionValue("2.5.29.19");

        // try to see if this is a leaf cert
        // look for BasicConstraint extension
        if (extBytes == null) {
            // found leaf cert
            CMS.debug("RenewalProcessor: found leaf cert");
            break;
        }

        CMS.debug("RenewalProcessor: found cert having BasicConstraints ext");
        // it's got BasicConstraints extension
        // so it's not likely to be a leaf cert,
        // however, check the isCA field regardless

        try {
            BasicConstraintsExtension bce = new BasicConstraintsExtension(true, extBytes);
            if (!(Boolean) bce.get("is_ca")) {
                CMS.debug("RenewalProcessor: found CA cert in chain");
                break;
            } // else found a ca cert, continue

        } catch (Exception e) {
            CMS.debug("RenewalProcessor: Invalid certificate extension:" + e);
            throw new BadRequestException("Invalid certificate extension: " + e.getMessage(), e);
        }
    }

    // clientCert cannot be null here

    return clientCert.getSerialNumber();
}

From source file:org.opensaml.security.x509.X509SupportTest.java

/**
 * Test 1 alt name: IP.//from w  ww.  j av  a2s  . c om
 * 
 * @throws SecurityException
 * @throws CertificateParsingException
 */
@Test
public void testGetSubjectAltNames1NameIP() throws SecurityException, CertificateParsingException {
    X509Certificate cert = entityCert1AltNameIP;
    // Sanity checks
    byte[] extensionValue = cert.getExtensionValue(subjectAltNameExtensionOID);
    Assert.assertNotNull(extensionValue, "Entity cert's Java native getExtensionValue() was null");
    Assert.assertTrue(extensionValue.length > 0, "Entity cert's extension value was empty");

    Set<Integer> nameTypes = new HashSet<>();
    nameTypes.add(altNameTypeIP);

    List altNames = getAltNames(cert, nameTypes);
    Assert.assertNotNull(altNames, "X509Support.getAltNames() returned null");

    Assert.assertTrue(altNames.contains(altNameIP), "Failed to find expected KeyName value");
}

From source file:org.opensaml.security.x509.X509SupportTest.java

/**
 * Test 1 alt name: DNS./*  w w w. j  a  v a2 s . c  o  m*/
 * 
 * @throws SecurityException
 * @throws CertificateParsingException
 */
@Test
public void testGetSubjectAltNames1NameDNS() throws SecurityException, CertificateParsingException {
    X509Certificate cert = entityCert1AltNameDNS;
    // Sanity checks
    byte[] extensionValue = cert.getExtensionValue(subjectAltNameExtensionOID);
    Assert.assertNotNull(extensionValue, "Entity cert's Java native getExtensionValue() was null");
    Assert.assertTrue(extensionValue.length > 0, "Entity cert's extension value was empty");

    Set<Integer> nameTypes = new HashSet<>();
    nameTypes.add(altNameTypeDNS);

    List altNames = getAltNames(cert, nameTypes);
    Assert.assertNotNull(altNames, "X509Support.getAltNames() returned null");

    Assert.assertTrue(altNames.contains(altNameDNS), "Failed to find expected KeyName value");
}

From source file:org.opensaml.security.x509.X509SupportTest.java

/**
 * Test 1 alt name: URI (URN)./* w w w.  j  a  va  2s  .  c o m*/
 * 
 * @throws SecurityException
 * @throws CertificateParsingException
 */
@Test
public void testGetSubjectAltNames1NameURN() throws SecurityException, CertificateParsingException {
    X509Certificate cert = entityCert1AltNameURN;
    // Sanity checks
    byte[] extensionValue = cert.getExtensionValue(subjectAltNameExtensionOID);
    Assert.assertNotNull(extensionValue, "Entity cert's Java native getExtensionValue() was null");
    Assert.assertTrue(extensionValue.length > 0, "Entity cert's extension value was empty");

    Set<Integer> nameTypes = new HashSet<>();
    nameTypes.add(altNameTypeURI);

    List altNames = getAltNames(cert, nameTypes);
    Assert.assertNotNull(altNames, "X509Support.getAltNames() returned null");

    Assert.assertTrue(altNames.contains(altNameURN), "Failed to find expected KeyName value");
}

From source file:org.opensaml.security.x509.X509SupportTest.java

/**
 * Test 1 alt name: URI (URL).// w  w w . ja  va2s.c o  m
 * 
 * @throws SecurityException
 * @throws CertificateParsingException
 */
@Test
public void testGetSubjectAltNames1NameURL() throws SecurityException, CertificateParsingException {
    X509Certificate cert = entityCert1AltNameURL;
    // Sanity checks
    byte[] extensionValue = cert.getExtensionValue(subjectAltNameExtensionOID);
    Assert.assertNotNull(extensionValue, "Entity cert's Java native getExtensionValue() was null");
    Assert.assertTrue(extensionValue.length > 0, "Entity cert's extension value was empty");

    Set<Integer> nameTypes = new HashSet<>();
    nameTypes.add(altNameTypeURI);

    List altNames = getAltNames(cert, nameTypes);
    Assert.assertNotNull(altNames, "X509Support.getAltNames() returned null");

    Assert.assertTrue(altNames.contains(altNameURL), "Failed to find expected KeyName value");
}

From source file:org.opensaml.xml.security.x509.X509UtilTest.java

/**
 * Test 1 alt name: IP./*from  w  ww .  j  av  a 2 s  . c  o m*/
 * @throws SecurityException
 * @throws CertificateParsingException 
 */
public void testGetSubjectAltNames1NameIP() throws SecurityException, CertificateParsingException {
    X509Certificate cert = entityCert1AltNameIP;
    // Sanity checks
    byte[] extensionValue = cert.getExtensionValue(subjectAltNameExtensionOID);
    assertNotNull("Entity cert's Java native getExtensionValue() was null", extensionValue);
    assertTrue("Entity cert's extension value was empty", extensionValue.length > 0);

    Set<Integer> nameTypes = new HashSet<Integer>();
    nameTypes.add(altNameTypeIP);

    List altNames = getAltNames(cert, nameTypes);
    assertNotNull("X509Util.getAltNames() returned null", altNames);

    assertTrue("Failed to find expected KeyName value", altNames.contains(altNameIP));
}