Example usage for java.security.cert X509CRL getExtensionValue

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

Introduction

In this page you can find the example usage for java.security.cert X509CRL 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:be.fedict.trust.crl.CrlTrustLinker.java

private TrustLinkerResult processCrl(URI crlUri, X509Certificate childCertificate, X509Certificate certificate,
        Date validationDate, RevocationData revocationData, BigInteger baseCrlNumber) {

    LOG.debug("CRL URI: " + crlUri);
    X509CRL x509crl = this.crlRepository.findCrl(crlUri, certificate, validationDate);
    if (null == x509crl) {
        return null;
    }//from  w  w  w  .  j a v a 2  s . com

    // check CRL integrity
    boolean crlIntegrityResult = checkCrlIntegrity(x509crl, certificate, validationDate);
    if (false == crlIntegrityResult) {
        return null;
    }

    // check CRL signature
    TrustLinkerResult trustResult = TrustValidator.checkSignatureAlgorithm(x509crl.getSigAlgName());
    if (!trustResult.isValid()) {
        return trustResult;
    }

    // we don't support indirect CRLs
    if (isIndirectCRL(x509crl)) {
        LOG.debug("indirect CRL detected");
        return null;
    }

    LOG.debug("CRL number: " + getCrlNumber(x509crl));
    // check delta CRL indicator against completeCrlNuber
    if (null != baseCrlNumber) {
        BigInteger crlNumber = getDeltaCrlIndicator(x509crl);
        if (!baseCrlNumber.equals(crlNumber)) {
            LOG.error("Delta CRL indicator (" + crlNumber + ") not equals base CRL number(" + baseCrlNumber
                    + ")");
            return null;
        }
    }

    // fill up revocation data if not null with this valid CRL
    if (null != revocationData) {
        try {
            revocationData.getCrlRevocationData().add(new CRLRevocationData(x509crl.getEncoded()));
        } catch (CRLException e) {
            LOG.error("CRLException: " + e.getMessage(), e);
            throw new RuntimeException("CRLException : " + e.getMessage(), e);
        }
    }

    boolean revoked = true;
    X509CRLEntry crlEntry = x509crl.getRevokedCertificate(childCertificate.getSerialNumber());
    if (null == crlEntry) {
        LOG.debug("CRL OK for: " + childCertificate.getSubjectX500Principal());
        revoked = false;
    } else if (crlEntry.getRevocationDate().after(validationDate)) {
        LOG.debug("CRL OK for: " + childCertificate.getSubjectX500Principal() + " at " + validationDate);
        revoked = false;
    }

    if (null != x509crl.getExtensionValue(X509Extensions.DeltaCRLIndicator.getId())) {
        // Delta CRL
        if (!revoked)
            return null;

    } else {
        // Base CRL, look for delta's
        List<URI> deltaCrlUris = getDeltaCrlUris(x509crl);
        if (null != deltaCrlUris) {
            for (URI deltaCrlUri : deltaCrlUris) {
                LOG.debug("delta CRL: " + deltaCrlUri.toString());
                TrustLinkerResult result = processCrl(deltaCrlUri, childCertificate, certificate,
                        validationDate, revocationData, getCrlNumber(x509crl));
                if (null != result)
                    return result;
            }
        }
    }

    if (!revoked)
        return new TrustLinkerResult(true);

    return new TrustLinkerResult(false, TrustLinkerResultReason.INVALID_REVOCATION_STATUS,
            "certificate revoked by CRL=" + crlEntry.getSerialNumber());

}

From source file:org.candlepin.util.X509CRLStreamWriterTest.java

@Test
public void testAddEntryToEmptyCRL() throws Exception {
    Date oneHourAgo = new Date(new Date().getTime() - 60L * 60L * 1000L);
    Date oneHourHence = new Date(new Date().getTime() + 60L * 60L * 1000L);

    X509v2CRLBuilder crlBuilder = new X509v2CRLBuilder(issuer, oneHourAgo);
    crlBuilder.addExtension(X509Extension.authorityKeyIdentifier, false,
            new AuthorityKeyIdentifierStructure(keyPair.getPublic()));
    /* With a CRL number of 127, incrementing it should cause the number of bytes in the length
     * portion of the TLV to increase by one.*/
    crlBuilder.addExtension(X509Extension.cRLNumber, false, new CRLNumber(new BigInteger("127")));
    crlBuilder.setNextUpdate(oneHourHence);
    X509CRLHolder holder = crlBuilder.build(signer);

    File crlToChange = writeCRL(holder);

    File outfile = new File(folder.getRoot(), "new.crl");
    X509CRLStreamWriter stream = new X509CRLStreamWriter(crlToChange, (RSAPrivateKey) keyPair.getPrivate(),
            (RSAPublicKey) keyPair.getPublic());

    // Add enough items to cause the number of length bytes to change
    Set<BigInteger> newSerials = new HashSet<BigInteger>(Arrays.asList(new BigInteger("2358215310"),
            new BigInteger("7231352433"), new BigInteger("8233181205"), new BigInteger("1455615868"),
            new BigInteger("4323487764"), new BigInteger("6673256679")));

    for (BigInteger i : newSerials) {
        stream.add(i, new Date(), CRLReason.privilegeWithdrawn);
    }/* w  w w  .j a  v  a2 s  .  c om*/

    stream.preScan(crlToChange).lock();
    OutputStream o = new BufferedOutputStream(new FileOutputStream(outfile));
    stream.write(o);
    o.close();

    X509CRL changedCrl = readCRL();

    Set<BigInteger> discoveredSerials = new HashSet<BigInteger>();

    for (X509CRLEntry entry : changedCrl.getRevokedCertificates()) {
        discoveredSerials.add(entry.getSerialNumber());
    }

    X509CRL originalCrl = new JcaX509CRLConverter().setProvider(BC).getCRL(holder);

    assertNotNull(changedCrl.getNextUpdate());

    long changedCrlUpdateDelta = changedCrl.getNextUpdate().getTime() - changedCrl.getThisUpdate().getTime();

    // We're allowing a tolerance of a few milliseconds to deal with minor timing issues
    long deltaTolerance = 3;
    long deltaDiff = changedCrlUpdateDelta - (oneHourHence.getTime() - oneHourAgo.getTime());

    assertTrue(Math.abs(deltaDiff) <= deltaTolerance);
    assertThat(changedCrl.getThisUpdate(), greaterThan(originalCrl.getThisUpdate()));

    assertEquals(newSerials, discoveredSerials);
    assertEquals(originalCrl.getIssuerX500Principal(), changedCrl.getIssuerX500Principal());

    ASN1ObjectIdentifier crlNumberOID = X509Extension.cRLNumber;
    byte[] oldCrlNumberBytes = originalCrl.getExtensionValue(crlNumberOID.getId());
    byte[] newCrlNumberBytes = changedCrl.getExtensionValue(crlNumberOID.getId());

    DEROctetString oldOctet = (DEROctetString) DERTaggedObject.fromByteArray(oldCrlNumberBytes);
    DEROctetString newOctet = (DEROctetString) DERTaggedObject.fromByteArray(newCrlNumberBytes);
    DERInteger oldNumber = (DERInteger) DERTaggedObject.fromByteArray(oldOctet.getOctets());
    DERInteger newNumber = (DERInteger) DERTaggedObject.fromByteArray(newOctet.getOctets());
    assertEquals(oldNumber.getValue().add(BigInteger.ONE), newNumber.getValue());

    ASN1ObjectIdentifier authorityKeyOID = X509Extension.authorityKeyIdentifier;
    byte[] oldAuthorityKeyId = originalCrl.getExtensionValue(authorityKeyOID.getId());
    byte[] newAuthorityKeyId = changedCrl.getExtensionValue(authorityKeyOID.getId());
    assertArrayEquals(oldAuthorityKeyId, newAuthorityKeyId);
}

From source file:org.candlepin.util.X509CRLStreamWriterTest.java

@Test
public void testKeySizeChange() throws Exception {
    int[] sizes = { 1024, 4096 };

    for (int size : sizes) {
        X509CRLHolder holder = createCRL();
        File crlToChange = writeCRL(holder);

        generator.initialize(size);/*from   w  w  w  .  j  av  a 2s. c  o  m*/
        KeyPair differentKeyPair = generator.generateKeyPair();

        X509CRLStreamWriter stream = new X509CRLStreamWriter(crlToChange,
                (RSAPrivateKey) differentKeyPair.getPrivate(), (RSAPublicKey) differentKeyPair.getPublic());
        stream.preScan(crlToChange).lock();
        OutputStream o = new BufferedOutputStream(new FileOutputStream(outfile));
        stream.write(o);
        o.close();

        X509CRL originalCrl = new JcaX509CRLConverter().setProvider(BC).getCRL(holder);
        X509CRL changedCrl = readCRL(differentKeyPair.getPublic());

        Set<BigInteger> discoveredSerials = new HashSet<BigInteger>();

        for (X509CRLEntry entry : changedCrl.getRevokedCertificates()) {
            discoveredSerials.add(entry.getSerialNumber());
        }

        Set<BigInteger> expected = new HashSet<BigInteger>();
        expected.add(new BigInteger("100"));
        assertEquals(expected, discoveredSerials);

        // Since the key changed, the authorityKeyIdentifier must change
        byte[] oldAkiBytes = originalCrl.getExtensionValue(X509Extension.authorityKeyIdentifier.getId());
        byte[] newAkiBytes = changedCrl.getExtensionValue(X509Extension.authorityKeyIdentifier.getId());

        AuthorityKeyIdentifierStructure oldAki = new AuthorityKeyIdentifierStructure(oldAkiBytes);
        AuthorityKeyIdentifierStructure newAki = new AuthorityKeyIdentifierStructure(newAkiBytes);

        assertArrayEquals(oldAki.getKeyIdentifier(),
                new AuthorityKeyIdentifierStructure(keyPair.getPublic()).getKeyIdentifier());

        assertArrayEquals(newAki.getKeyIdentifier(),
                new AuthorityKeyIdentifierStructure(differentKeyPair.getPublic()).getKeyIdentifier());
    }
}

From source file:org.candlepin.util.X509CRLStreamWriterTest.java

@Test
public void testIncrementsExtensions() throws Exception {
    File crlToChange = writeCRL(createCRL());

    X509CRLStreamWriter stream = new X509CRLStreamWriter(crlToChange, (RSAPrivateKey) keyPair.getPrivate(),
            (RSAPublicKey) keyPair.getPublic());
    stream.preScan(crlToChange).lock();/*from  w  w  w  . j ava 2 s  . c  o m*/
    OutputStream o = new BufferedOutputStream(new FileOutputStream(outfile));
    stream.write(o);
    o.close();

    X509CRL changedCrl = readCRL();

    byte[] val = changedCrl.getExtensionValue(X509Extension.cRLNumber.getId());
    DEROctetString s = (DEROctetString) DERTaggedObject.fromByteArray(val);
    DERInteger i = (DERInteger) DERTaggedObject.fromByteArray(s.getOctets());

    assertTrue("CRL Number not incremented", i.getValue().compareTo(BigInteger.ONE) > 0);
}

From source file:org.cesecore.util.CertTools.java

/**
 * /*  w w  w  .  j a  v a 2  s . c  o m*/
 * @param crl an X509CRL
 * @param oid An OID for an extension 
 * @return an Extension ASN1Primitive from a CRL
 */
protected static ASN1Primitive getExtensionValue(X509CRL crl, String oid) {
    if (crl == null || oid == null) {
        return null;
    }
    byte[] bytes = crl.getExtensionValue(oid);
    return getDerObjectFromByteArray(bytes);
}

From source file:org.ejbca.core.model.ca.publisher.GeneralPurposeCustomPublisher.java

/**
 * Writes the CRL to a temporary file and executes an external command with
 * the temporary file as argument. By default, a PublisherException is
 * thrown if the external command returns with an errorlevel or outputs to
 * stderr.//from   ww w  .j a  v a2 s.  c o  m
 * 
 * @see org.ejbca.core.model.ca.publisher.ICustomPublisher#storeCRL(org.ejbca.core.model.log.Admin,
 *      byte[], java.lang.String, int)
 */
@Override
public boolean storeCRL(AuthenticationToken admin, byte[] incrl, String cafp, int number, String userDN)
        throws PublisherException {
    if (log.isTraceEnabled()) {
        log.trace(">storeCRL, Storing CRL");
    }
    // Verify initialization
    if (crlExternalCommandFileName == null) {
        String msg = intres.getLocalizedMessage("publisher.errormissingproperty",
                crlExternalCommandPropertyName);
        log.error(msg);
        throw new PublisherException(msg);
    }

    List<String> additionalArguments = new ArrayList<>();

    if (calclulateDeltaCrlLocally) {
        X509CRL crl;
        try {
            crl = CertTools.getCRLfromByteArray(incrl);
            additionalArguments
                    .add(Boolean.toString(crl.getExtensionValue(Extension.deltaCRLIndicator.getId()) != null));
        } catch (CRLException e) {
            log.error("Byte array does not contain a correct CRL.", e);
        }

    }

    // Run internal method to create tempfile and run the command
    runWithTempFile(crlExternalCommandFileName, incrl, crlFailOnErrorCode, crlFailOnStandardError,
            additionalArguments);
    if (log.isTraceEnabled()) {
        log.trace("<storeCRL");
    }
    return true;
}

From source file:org.ejbca.core.model.ca.publisher.LdapPublisher.java

/**
 * @see org.ejbca.core.model.ca.publisher.BasePublisher#storeCRL
 *///from   w  w w  .ja  va2s.com
public boolean storeCRL(AuthenticationToken admin, byte[] incrl, String cafp, int number, String userDN)
        throws PublisherException {
    if (log.isTraceEnabled()) {
        log.trace(">storeCRL");
    }
    int ldapVersion = LDAPConnection.LDAP_V3;

    final String dn;
    final String crldn;
    final boolean isDeltaCRL;
    try {
        // Extract the users DN from the crl. Use the least number of encodings...
        final X509CRL crl = CertTools.getCRLfromByteArray(incrl);
        crldn = CertTools.stringToBCDNString(crl.getIssuerDN().toString());
        // Is it a delta CRL?
        if (crl.getExtensionValue(Extension.deltaCRLIndicator.getId()) != null) {
            isDeltaCRL = true;
        } else {
            isDeltaCRL = false;
        }
        // Construct the DN used for the LDAP object entry
        dn = constructLDAPDN(crldn, userDN);
    } catch (Exception e) {
        String msg = intres.getLocalizedMessage("publisher.errorldapdecode", "CRL");
        log.error(msg, e);
        throw new PublisherException(msg);
    }

    LDAPConnection lc = createLdapConnection();

    // Check if the entry is already present, we will update it with the new CRL.
    LDAPEntry oldEntry = searchOldEntity(null, ldapVersion, lc, crldn, userDN, null);

    LDAPEntry newEntry = null;
    ArrayList<LDAPModification> modSet = new ArrayList<LDAPModification>();
    LDAPAttributeSet attributeSet = null;

    if (oldEntry != null) {
        modSet = getModificationSet(oldEntry, crldn, null, false, false, null, null);
    } else {
        attributeSet = getAttributeSet(null, this.getCAObjectClass(), crldn, null, true, false, null, null);
    }

    if (isDeltaCRL) {
        // It's a delta CRL.
        LDAPAttribute attr = new LDAPAttribute(getDeltaCRLAttribute(), incrl);
        if (oldEntry != null) {
            modSet.add(new LDAPModification(LDAPModification.REPLACE, attr));
        } else {
            attributeSet.add(attr);
        }
    } else {
        // It's a CRL
        LDAPAttribute crlAttr = new LDAPAttribute(getCRLAttribute(), incrl);
        LDAPAttribute arlAttr = new LDAPAttribute(getARLAttribute(), incrl);
        if (oldEntry != null) {
            modSet.add(new LDAPModification(LDAPModification.REPLACE, crlAttr));
            modSet.add(new LDAPModification(LDAPModification.REPLACE, arlAttr));
        } else {
            attributeSet.add(crlAttr);
            attributeSet.add(arlAttr);
        }
    }
    if (oldEntry == null) {
        newEntry = new LDAPEntry(dn, attributeSet);
    }
    // Try all the listed servers
    Iterator<String> servers = getHostnameList().iterator();
    boolean connectionFailed;
    do {
        connectionFailed = false;
        String currentServer = servers.next();
        try {
            TCPTool.probeConnectionLDAP(currentServer, Integer.parseInt(getPort()), getConnectionTimeOut()); // Avoid waiting for halfdead-servers
            // connect to the server
            lc.connect(currentServer, Integer.parseInt(getPort()));
            // Execute a STARTTLS handshake if it was requested.
            if (getConnectionSecurity() == ConnectionSecurity.STARTTLS) {
                if (log.isDebugEnabled()) {
                    log.debug("STARTTLS to LDAP server " + currentServer);
                }
                lc.startTLS();
            }
            // authenticate to the server
            lc.bind(ldapVersion, getLoginDN(), getLoginPassword().getBytes("UTF8"), ldapBindConstraints);
            // Add or modify the entry
            if (oldEntry != null) {
                LDAPModification[] mods = new LDAPModification[modSet.size()];
                mods = (LDAPModification[]) modSet.toArray(mods);
                lc.modify(dn, mods, ldapStoreConstraints);
                String msg = intres.getLocalizedMessage("publisher.ldapmodify", "CRL", dn);
                log.info(msg);
            } else {
                lc.add(newEntry, ldapStoreConstraints);
                String msg = intres.getLocalizedMessage("publisher.ldapadd", "CRL", dn);
                log.info(msg);
            }
        } catch (LDAPException e) {
            connectionFailed = true;
            if (servers.hasNext()) {
                log.warn("Failed to publish to " + currentServer + ". Trying next in list.");
            } else {
                String msg = intres.getLocalizedMessage("publisher.errorldapstore", "CRL", getCRLAttribute(),
                        getCAObjectClass(), dn, e.getMessage());
                log.error(msg, e);
                throw new PublisherException(msg);
            }
        } catch (UnsupportedEncodingException e) {
            String msg = intres.getLocalizedMessage("publisher.errorpassword", getLoginPassword());
            log.error(msg, e);
            throw new PublisherException(msg);
        } finally {
            // disconnect with the server
            try {
                lc.disconnect(ldapDisconnectConstraints);
            } catch (LDAPException e) {
                String msg = intres.getLocalizedMessage("publisher.errordisconnect");
                log.error(msg, e);
            }
        }
    } while (connectionFailed && servers.hasNext());
    if (log.isTraceEnabled()) {
        log.trace("<storeCRL");
    }
    return true;
}

From source file:org.xdi.oxauth.cert.validation.CRLCertificateVerifier.java

@SuppressWarnings({ "deprecation", "resource" })
private BigInteger getCrlNumber(X509CRL crl) throws IOException {
    byte[] crlNumberExtensionValue = crl.getExtensionValue(X509Extensions.CRLNumber.getId());
    if (crlNumberExtensionValue == null) {
        return null;
    }/*from  w w  w  . j  av  a 2  s .  c o  m*/

    DEROctetString octetString = (DEROctetString) (new ASN1InputStream(
            new ByteArrayInputStream(crlNumberExtensionValue)).readObject());
    byte[] octets = octetString.getOctets();
    DERInteger integer = (DERInteger) new ASN1InputStream(octets).readObject();
    BigInteger crlNumber = integer.getPositiveValue();

    return crlNumber;
}