Example usage for java.security.cert X509CRL getIssuerDN

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

Introduction

In this page you can find the example usage for java.security.cert X509CRL getIssuerDN.

Prototype

public abstract Principal getIssuerDN();

Source Link

Document

Denigrated, replaced by #getIssuerX500Principal() .

Usage

From source file:MainClass.java

public static void main(String[] args) throws Exception {
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    FileInputStream in = new FileInputStream(args[0]);
    X509CRL crl = (X509CRL) cf.generateCRL(in);
    System.out.println("type = " + crl.getType());
    System.out.println("version = " + crl.getVersion());
    System.out.println("issuer = " + crl.getIssuerDN().getName());
    System.out.println("signing algorithm = " + crl.getSigAlgName());
    System.out.println("this update = " + crl.getThisUpdate());
    System.out.println("next update = " + crl.getNextUpdate());
    in.close();//from  w ww . j av  a  2 s .  c  o  m
}

From source file:gov.nih.nci.cagrid.gts.service.CertificateRevocationLists.java

/**
 * Method loads a CRL provided a mapping for it is<br>
 * a) Not already in the HashMap b) In the HashMap, but - mapped to null
 * object - the CRLEntry has a modified time that is older that latest time
 *///from w w w.  j a  v a  2  s.c o  m
private void loadCrl(String crlPath, long latestLastModified, Map newCrlFileMap, Map newCrlIssuerDNMap) {
    X509CRL crl = null;

    if (this.crlFileMap == null) {
        this.crlFileMap = new HashMap();
    }

    TimestampEntry crlEntry = (TimestampEntry) this.crlFileMap.get(crlPath);
    try {
        if (crlEntry == null) {
            logger.debug("Loading " + crlPath + " CRL.");
            crl = CertUtil.loadCrl(crlPath);
            crlEntry = new TimestampEntry(crl, latestLastModified);
        } else if (latestLastModified > crlEntry.getLastModified()) {
            logger.debug("Reloading " + crlPath + " CRL.");
            crl = CertUtil.loadCrl(crlPath);
            crlEntry.setValue(crl);
            crlEntry.setLastModified(latestLastModified);
        } else {
            logger.debug("CRL " + crlPath + " is up-to-date.");
            crl = (X509CRL) crlEntry.getValue();
        }
        newCrlFileMap.put(crlPath, crlEntry);
        newCrlIssuerDNMap.put(crl.getIssuerDN().getName(), crl);
    } catch (Exception e) {
        logger.error("CRL " + crlPath + " failed to load.", e);
    }
}

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

/**
 * Gets issuer DN for CRL in the format we are sure about (BouncyCastle),supporting UTF8.
 * /*  w  ww  . j  ava 2 s  .  c o m*/
 * @param crl X509RL
 * 
 * @return String containing the DN.
 */
public static String getIssuerDN(X509CRL crl) {
    String dn = null;
    try {
        CertificateFactory cf = CertTools.getCertificateFactory();
        X509CRL x509crl = (X509CRL) cf.generateCRL(new ByteArrayInputStream(crl.getEncoded()));
        // log.debug("Created certificate of class: " + x509crl.getClass().getName());
        dn = x509crl.getIssuerDN().toString();
    } catch (CRLException ce) {
        log.error("CRLException: ", ce);
        return null;
    }
    return stringToBCDNString(dn);
}

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

/**
 * @see org.ejbca.core.model.ca.publisher.BasePublisher#storeCRL
 *///  w  ww  . j  a  va 2s  . 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.ejbca.core.protocol.scep.ProtocolScepHttpTest.java

private void checkScepResponse(byte[] retMsg, String userDN, String _senderNonce, String _transId,
        boolean crlRep, String digestOid, boolean noca)
        throws CMSException, OperatorCreationException, NoSuchProviderException, CRLException,
        InvalidKeyException, NoSuchAlgorithmException, SignatureException, CertificateException {

    // Parse response message
    ////from w w w. j  a  va 2 s . c  o  m
    CMSSignedData s = new CMSSignedData(retMsg);
    // The signer, i.e. the CA, check it's the right CA
    SignerInformationStore signers = s.getSignerInfos();
    @SuppressWarnings("unchecked")
    Collection<SignerInformation> col = signers.getSigners();
    assertTrue(col.size() > 0);
    Iterator<SignerInformation> iter = col.iterator();
    SignerInformation signerInfo = iter.next();
    // Check that the message is signed with the correct digest alg
    assertEquals(signerInfo.getDigestAlgOID(), digestOid);
    SignerId sinfo = signerInfo.getSID();
    // Check that the signer is the expected CA
    assertEquals(CertTools.stringToBCDNString(cacert.getIssuerDN().getName()),
            CertTools.stringToBCDNString(sinfo.getIssuer().toString()));
    // Verify the signature
    JcaDigestCalculatorProviderBuilder calculatorProviderBuilder = new JcaDigestCalculatorProviderBuilder()
            .setProvider(BouncyCastleProvider.PROVIDER_NAME);
    JcaSignerInfoVerifierBuilder jcaSignerInfoVerifierBuilder = new JcaSignerInfoVerifierBuilder(
            calculatorProviderBuilder.build()).setProvider(BouncyCastleProvider.PROVIDER_NAME);
    boolean ret = signerInfo.verify(jcaSignerInfoVerifierBuilder.build(cacert.getPublicKey()));
    assertTrue(ret);
    // Get authenticated attributes
    AttributeTable tab = signerInfo.getSignedAttributes();
    // --Fail info
    Attribute attr = tab.get(new ASN1ObjectIdentifier(ScepRequestMessage.id_failInfo));
    // No failInfo on this success message
    assertNull(attr);
    // --Message type
    attr = tab.get(new ASN1ObjectIdentifier(ScepRequestMessage.id_messageType));
    assertNotNull(attr);
    ASN1Set values = attr.getAttrValues();
    assertEquals(values.size(), 1);
    ASN1String str = DERPrintableString.getInstance((values.getObjectAt(0)));
    String messageType = str.getString();
    assertEquals("3", messageType);
    // --Success status
    attr = tab.get(new ASN1ObjectIdentifier(ScepRequestMessage.id_pkiStatus));
    assertNotNull(attr);
    values = attr.getAttrValues();
    assertEquals(values.size(), 1);
    str = DERPrintableString.getInstance((values.getObjectAt(0)));
    assertEquals(ResponseStatus.SUCCESS.getStringValue(), str.getString());
    // --SenderNonce
    attr = tab.get(new ASN1ObjectIdentifier(ScepRequestMessage.id_senderNonce));
    assertNotNull(attr);
    values = attr.getAttrValues();
    assertEquals(values.size(), 1);
    ASN1OctetString octstr = ASN1OctetString.getInstance(values.getObjectAt(0));
    // SenderNonce is something the server came up with, but it should be 16
    // chars
    assertTrue(octstr.getOctets().length == 16);
    // --Recipient Nonce
    attr = tab.get(new ASN1ObjectIdentifier(ScepRequestMessage.id_recipientNonce));
    assertNotNull(attr);
    values = attr.getAttrValues();
    assertEquals(values.size(), 1);
    octstr = ASN1OctetString.getInstance(values.getObjectAt(0));
    // recipient nonce should be the same as we sent away as sender nonce
    assertEquals(_senderNonce, new String(Base64.encode(octstr.getOctets())));
    // --Transaction ID
    attr = tab.get(new ASN1ObjectIdentifier(ScepRequestMessage.id_transId));
    assertNotNull(attr);
    values = attr.getAttrValues();
    assertEquals(values.size(), 1);
    str = DERPrintableString.getInstance((values.getObjectAt(0)));
    // transid should be the same as the one we sent
    assertEquals(_transId, str.getString());

    //
    // Check different message types
    //
    if (messageType.equals("3")) {
        // First we extract the encrypted data from the CMS enveloped data
        // contained
        // within the CMS signed data
        final CMSProcessable sp = s.getSignedContent();
        final byte[] content = (byte[]) sp.getContent();
        final CMSEnvelopedData ed = new CMSEnvelopedData(content);
        final RecipientInformationStore recipients = ed.getRecipientInfos();
        Store certstore;

        @SuppressWarnings("unchecked")
        Collection<RecipientInformation> c = recipients.getRecipients();
        assertEquals(c.size(), 1);
        Iterator<RecipientInformation> riIterator = c.iterator();
        byte[] decBytes = null;
        RecipientInformation recipient = riIterator.next();
        JceKeyTransEnvelopedRecipient rec = new JceKeyTransEnvelopedRecipient(key1.getPrivate());
        rec.setContentProvider(BouncyCastleProvider.PROVIDER_NAME);
        decBytes = recipient.getContent(rec);
        // This is yet another CMS signed data
        CMSSignedData sd = new CMSSignedData(decBytes);
        // Get certificates from the signed data
        certstore = sd.getCertificates();

        if (crlRep) {
            // We got a reply with a requested CRL
            @SuppressWarnings("unchecked")
            final Collection<X509CRLHolder> crls = (Collection<X509CRLHolder>) sd.getCRLs().getMatches(null);
            assertEquals(crls.size(), 1);
            final Iterator<X509CRLHolder> it = crls.iterator();
            // CRL is first (and only)
            final X509CRL retCrl = new JcaX509CRLConverter().getCRL(it.next());
            log.info("Got CRL with DN: " + retCrl.getIssuerDN().getName());

            // check the returned CRL
            assertEquals(CertTools.getSubjectDN(cacert), CertTools.getIssuerDN(retCrl));
            retCrl.verify(cacert.getPublicKey());
        } else {
            // We got a reply with a requested certificate
            @SuppressWarnings("unchecked")
            final Collection<X509CertificateHolder> certs = (Collection<X509CertificateHolder>) certstore
                    .getMatches(null);
            // EJBCA returns the issued cert and the CA cert (cisco vpn
            // client requires that the ca cert is included)
            if (noca) {
                assertEquals(certs.size(), 1);
            } else {
                assertEquals(certs.size(), 2);
            }
            final Iterator<X509CertificateHolder> it = certs.iterator();
            // Issued certificate must be first
            boolean verified = false;
            boolean gotcacert = false;
            JcaX509CertificateConverter jcaX509CertificateConverter = new JcaX509CertificateConverter();
            while (it.hasNext()) {
                X509Certificate retcert = jcaX509CertificateConverter.getCertificate(it.next());
                log.info("Got cert with DN: " + retcert.getSubjectDN().getName());

                // check the returned certificate
                String subjectdn = CertTools.stringToBCDNString(retcert.getSubjectDN().getName());
                if (CertTools.stringToBCDNString(userDN).equals(subjectdn)) {
                    // issued certificate
                    assertEquals(CertTools.stringToBCDNString(userDN), subjectdn);
                    assertEquals(CertTools.getSubjectDN(cacert), CertTools.getIssuerDN(retcert));
                    retcert.verify(cacert.getPublicKey());
                    assertTrue(checkKeys(key1.getPrivate(), retcert.getPublicKey()));
                    verified = true;
                } else {
                    // ca certificate
                    assertEquals(CertTools.getSubjectDN(cacert), CertTools.getSubjectDN(retcert));
                    gotcacert = true;
                }
            }
            assertTrue(verified);
            if (noca) {
                assertFalse(gotcacert);
            } else {
                assertTrue(gotcacert);
            }
        }
    }

}

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

/**
 * Gets issuer DN for CRL in the format we are sure about (BouncyCastle),supporting UTF8.
 *
 * @param crl X509RL//from   w  w  w .  j  a v  a 2s . com
 *
 * @return String containing the DN.
 */
public static String getIssuerDN(X509CRL crl) {
    /*if (log.isTraceEnabled()) {
       log.trace(">getIssuerDN(crl)");
    }*/
    String dn = null;
    try {
        CertificateFactory cf = CertTools.getCertificateFactory();
        X509CRL x509crl = (X509CRL) cf.generateCRL(new ByteArrayInputStream(crl.getEncoded()));
        //log.debug("Created certificate of class: " + x509crl.getClass().getName());
        dn = x509crl.getIssuerDN().toString();
    } catch (CRLException ce) {
        log.error("CRLException: ", ce);
        return null;
    }
    /*if (log.isTraceEnabled()) {
       log.trace("<getIssuerDN(crl):"+dn);
    }*/
    return stringToBCDNString(dn);
}

From source file:org.viafirma.nucleo.validacion.CRLUtil.java

/**
 * Recupera el listado de Crls obtenidas desde el LDAP. 
 * TODO: Separar cada implementacin en un IMPL concreto que tenga que cumplir con una interfaz
 * para resolver las crls y para parsear el certificado 
 * NOTA: para utilizar de forma oficial la validazin de CRLs de la FNMT es necesario firmar un convenio.
 * /*from   ww  w.j a  va  2s  .c  o  m*/
 * @param certificadoX509
 * @return
 */
private List<X509CRL> getCrlLDAPFNMT(X509Certificate certificadoX509) {
    List<X509CRL> crls = new LinkedList<X509CRL>();
    // ********************************************************************************
    // si es un certiticado de la FNMT hay que acceder al ldap para
    // recuperar las crls.
    try {
        CertificateFactory factoriaCertificados = CertificateFactory.getInstance("X.509",
                BouncyCastleProvider.PROVIDER_NAME);
        // es un certificado de la FNMT. el procesamiento es diferente
        // al resto, es atacando a un LDAP
        // recuperamos del LDAP el certificado
        // NOTA: Esta url es solo para pruebas, para utilizar de forma
        // oficial la validazin de CRLs de la FNMT es necesario firmar un
        // convenio
        // ldap-2.cert.fnmt.es:389
        InputStream ioCrl = getIoCrlFromFNMTLDAP(certificadoX509);
        if (ioCrl != null) {
            // la crl del fichero actual esta publicada, recuperamos la crl
            // leo el io para generar un fichero de crl
            System.out.println("***ioCrl:" + ioCrl);
            X509CRL crl = (X509CRL) factoriaCertificados.generateCRL(ioCrl);
            System.out.println("***Despues deioCrl:" + crl);
            try {
                if (crl != null) {
                    crls.add(crl);
                    System.out.println("***3:" + crl.getIssuerDN());
                    log.debug("CRLer     -->" + crl.getIssuerDN());
                    log.debug("Effective   From -->" + crl.getThisUpdate());
                    log.debug("Nextate    -->" + crl.getNextUpdate());
                    crls.add(crl);
                } else {
                    log.debug("No se puede recuperar o no es un cert valido .");
                }

                ioCrl.close();
            } catch (Throwable e) {
                log.warn("Problemas al recuperar la crl ." + e.getMessage());
                e.printStackTrace();
            } // no importa si no podemos cerrar la conexin( significa
              // que ya esta cerrada)
        } else {
            log.error("No se ha recuperado la crl.");
        }
    } catch (CRLException e) {
        log.warn("No se puede recuperar la crl." + e.getMessage());
    } catch (Throwable e) {
        e.printStackTrace();
    }
    return crls;
}

From source file:test.integ.be.fedict.performance.TestHarvestEid.java

@Test
public void testHarvestEid() throws Exception {

    // Operate: fetch CRL urls
    HttpClient httpClient = new HttpClient();
    GetMethod getMethod = new GetMethod(BEID_URI);
    httpClient.executeMethod(getMethod);

    String content = getMethod.getResponseBodyAsString();
    List<String> crlPaths = new LinkedList<String>();
    int start = content.indexOf(URL_START);
    int end = content.indexOf(URL_STOP);
    while (-1 != start) {
        String ahref = content.substring(start + URL_START.length(), end);
        String path = ahref.substring(0, ahref.indexOf("\">"));
        if (path.contains(".crl")) {
            crlPaths.add(path);/*from  w w  w .j  a  v a 2  s. c  o m*/
        }
        content = content.substring(end + URL_STOP.length());
        start = content.indexOf(URL_START);
        end = content.indexOf(URL_STOP);
    }

    // Setup
    OnlineCrlRepository onlineCrlRepository = new OnlineCrlRepository();

    // Operate: harvest
    List<CrlInfo> crlInfos = new LinkedList<CrlInfo>();
    for (String path : crlPaths) {
        URI crlURI = new URI(BEID_URI + "/" + path);
        X509CRL crl = onlineCrlRepository.findCrl(crlURI, null, null);
        int entries = 0;
        Set<? extends X509CRLEntry> crlEntries = crl.getRevokedCertificates();
        if (null != crlEntries) {
            entries = crlEntries.size();
        }
        crlInfos.add(new CrlInfo(crlURI.toString(), crl.getIssuerDN().toString(), entries));
    }

    // Verify: output
    Random random = new Random();
    for (CrlInfo crlInfo : crlInfos) {
        LOG.debug(crlInfo.getUrl() + " : " + "TestPKI.get().addSaveCa(\"" + crlInfo.getIssuer()
                + "\", \"CN=root" + random.nextInt(2) + "\", " + crlInfo.getEntries() + ", 0);");
    }
}