Example usage for java.security.cert CertificateParsingException CertificateParsingException

List of usage examples for java.security.cert CertificateParsingException CertificateParsingException

Introduction

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

Prototype

public CertificateParsingException(Throwable cause) 

Source Link

Document

Creates a CertificateParsingException with the specified cause and a detail message of (cause==null ?

Usage

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

/**
 * Reads certificates in PEM-format from an InputStream. 
 * The stream may contain other things between the different certificates.
 * /*w  w  w  .  j av  a 2  s.c o  m*/
 * @param certstream the input stream containing the certificates in PEM-format
 * @return Ordered List of Certificates, first certificate first, or empty List
 * @exception CertificateParsingException if the stream contains an incorrect certificate.
 */
public static List<Certificate> getCertsFromPEM(InputStream certstream) throws CertificateParsingException {
    if (log.isTraceEnabled()) {
        log.trace(">getCertfromPEM");
    }
    ArrayList<Certificate> ret = new ArrayList<Certificate>();
    String beginKeyTrust = "-----BEGIN TRUSTED CERTIFICATE-----";
    String endKeyTrust = "-----END TRUSTED CERTIFICATE-----";
    BufferedReader bufRdr = null;
    ByteArrayOutputStream ostr = null;
    PrintStream opstr = null;
    try {
        try {
            bufRdr = new BufferedReader(new InputStreamReader(certstream));
            while (bufRdr.ready()) {
                ostr = new ByteArrayOutputStream();
                opstr = new PrintStream(ostr);
                String temp;
                while ((temp = bufRdr.readLine()) != null
                        && !(temp.equals(CertTools.BEGIN_CERTIFICATE) || temp.equals(beginKeyTrust))) {
                    continue;
                }
                if (temp == null) {
                    if (ret.isEmpty()) {
                        // There was no certificate in the file
                        throw new CertificateParsingException("Error in " + certstream.toString() + ", missing "
                                + CertTools.BEGIN_CERTIFICATE + " boundary");
                    } else {
                        // There were certificates, but some blank lines or something in the end
                        // anyhow, the file has ended so we can break here.
                        break;
                    }
                }
                while ((temp = bufRdr.readLine()) != null
                        && !(temp.equals(CertTools.END_CERTIFICATE) || temp.equals(endKeyTrust))) {
                    opstr.print(temp);
                }
                if (temp == null) {
                    throw new IllegalArgumentException("Error in " + certstream.toString() + ", missing "
                            + CertTools.END_CERTIFICATE + " boundary");
                }
                opstr.close();

                byte[] certbuf = Base64.decode(ostr.toByteArray());
                ostr.close();
                // Phweeew, were done, now decode the cert from file back to Certificate object
                Certificate cert = getCertfromByteArray(certbuf);
                ret.add(cert);
            }

        } finally {
            if (bufRdr != null) {
                bufRdr.close();
            }
            if (opstr != null) {
                opstr.close();
            }
            if (ostr != null) {
                ostr.close();
            }
        }
    } catch (IOException e) {
        throw new IllegalStateException(
                "Exception caught when attempting to read stream, see underlying IOException", e);
    }
    if (log.isTraceEnabled()) {
        log.trace("<getcertfromPEM:" + ret.size());
    }
    return ret;
}

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

/**
 * Creates Certificate from byte[], can be either an X509 certificate or a CVCCertificate
 * /* w w w .ja  v a 2s.c om*/
 * @param cert byte array containing certificate in binary (DER) format, or PEM encoded X.509 certificate
 * @param provider provider for example "SUN" or "BC", use null for the default provider (BC)
 * 
 * @return a Certificate 
 * @throws CertificateParsingException if certificate couldn't be parsed from cert
 * 
 */
public static Certificate getCertfromByteArray(byte[] cert, String provider)
        throws CertificateParsingException {
    Certificate ret = null;
    String prov = provider;
    if (provider == null) {
        prov = BouncyCastleProvider.PROVIDER_NAME;
    }
    try {
        final CertificateFactory cf = CertTools.getCertificateFactory(prov);
        ret = cf.generateCertificate(new ByteArrayInputStream(cert));
    } catch (CertificateException e) {
        log.debug("CertificateException trying to read X509Certificate.", e);
    }
    if (ret == null) {
        // We could not create an X509Certificate, see if it is a CVC certificate instead
        try {
            final CVCertificate parsedObject = CertificateParser.parseCertificate(cert);
            ret = new CardVerifiableCertificate(parsedObject);
        } catch (ParseException e) {
            log.debug("ParseException trying to read CVCCertificate.", e);
        } catch (ConstructionException e) {
            log.debug("ConstructionException trying to read CVCCertificate.", e);
        }
    }
    if (ret == null) {
        throw new CertificateParsingException(
                "No certificate could be parsed from byte array. See debug logs for details.");
    }
    return ret;
}

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

/**
 * Return the CRL distribution point URL from a certificate.
 *//*w w w.  j a v a 2 s . com*/
public static URL getCrlDistributionPoint(Certificate certificate) throws CertificateParsingException {
    if (certificate instanceof X509Certificate) {
        X509Certificate x509cert = (X509Certificate) certificate;
        try {
            ASN1Primitive obj = getExtensionValue(x509cert, Extension.cRLDistributionPoints.getId());
            if (obj == null) {
                return null;
            }
            ASN1Sequence distributionPoints = (ASN1Sequence) obj;
            for (int i = 0; i < distributionPoints.size(); i++) {
                ASN1Sequence distrPoint = (ASN1Sequence) distributionPoints.getObjectAt(i);
                for (int j = 0; j < distrPoint.size(); j++) {
                    ASN1TaggedObject tagged = (ASN1TaggedObject) distrPoint.getObjectAt(j);
                    if (tagged.getTagNo() == 0) {
                        String url = getStringFromGeneralNames(tagged.getObject());
                        if (url != null) {
                            return new URL(url);
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.error("Error parsing CrlDistributionPoint", e);
            throw new CertificateParsingException(e.toString());
        }
    }
    return null;
}

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

/**
 * Returns OCSP URL that is inside AuthorityInformationAccess extension, or null.
 * /*from  w w w.j a v a  2 s .c o  m*/
 * @param cert is the certificate to parse
 * @throws CertificateParsingException
 */
public static String getAuthorityInformationAccessOcspUrl(Certificate cert) throws CertificateParsingException {
    String ret = null;
    if (cert instanceof X509Certificate) {
        X509Certificate x509cert = (X509Certificate) cert;
        try {
            ASN1Primitive obj = getExtensionValue(x509cert, Extension.authorityInfoAccess.getId());
            if (obj == null) {
                return null;
            }
            AuthorityInformationAccess aia = AuthorityInformationAccess.getInstance(obj);
            AccessDescription[] ad = aia.getAccessDescriptions();
            if ((ad != null) && (ad.length > 0)) {
                for (int i = 0; i < ad.length; i++) {
                    if (ad[i].getAccessMethod().equals(X509ObjectIdentifiers.ocspAccessMethod)) {
                        GeneralName gn = ad[i].getAccessLocation();
                        if (gn.getTagNo() == GeneralName.uniformResourceIdentifier) {
                            // After encoding in a cert, it is tagged an extra time...
                            ASN1Primitive gnobj = gn.toASN1Primitive();
                            if (gnobj instanceof ASN1TaggedObject) {
                                gnobj = ASN1TaggedObject.getInstance(gnobj).getObject();
                            }
                            final DERIA5String str = DERIA5String.getInstance(gnobj);
                            ret = str.getString();
                            break; // no need to go on any further, we got a value
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.error("Error parsing AuthorityInformationAccess", e);
            throw new CertificateParsingException(e.toString());
        }
    }
    return ret;
}

From source file:org.eclipse.smarthome.io.net.http.internal.ExtensibleTrustManagerImplTest.java

@Test
public void shouldBeResilientAgainstInvalidCertificates() throws CertificateException, IllegalAccessException {
    FieldUtils.writeField(subject, "defaultTrustManager", defaultTrustManager, true);

    when(topOfChain.getSubjectX500Principal())
            .thenReturn(new X500Principal("CN=example.com, OU=Smarthome, O=Eclipse, C=DE"));
    when(topOfChain.getSubjectAlternativeNames())
            .thenThrow(new CertificateParsingException("Invalid certificate!!!"));

    subject.checkClientTrusted(chain, "just");

    verify(defaultTrustManager).checkClientTrusted(chain, "just", (Socket) null);
    verifyNoMoreInteractions(trustmanager);
}

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

/**
  * Return the CRL distribution point URL from a certificate.
  *//*  w  w  w.ja  v  a 2s  .  c om*/
public static URL getCrlDistributionPoint(Certificate certificate) throws CertificateParsingException {
    if (certificate instanceof X509Certificate) {
        X509Certificate x509cert = (X509Certificate) certificate;
        try {
            DERObject obj = getExtensionValue(x509cert, X509Extensions.CRLDistributionPoints.getId());
            if (obj == null) {
                return null;
            }
            ASN1Sequence distributionPoints = (ASN1Sequence) obj;
            for (int i = 0; i < distributionPoints.size(); i++) {
                ASN1Sequence distrPoint = (ASN1Sequence) distributionPoints.getObjectAt(i);
                for (int j = 0; j < distrPoint.size(); j++) {
                    ASN1TaggedObject tagged = (ASN1TaggedObject) distrPoint.getObjectAt(j);
                    if (tagged.getTagNo() == 0) {
                        String url = getStringFromGeneralNames(tagged.getObject());
                        if (url != null) {
                            return new URL(url);
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.error("Error parsing CrlDistributionPoint", e);
            throw new CertificateParsingException(e.toString());
        }
    }
    return null;
}

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

/** Returns OCSP URL that is inside AuthorithInformationAccess extension, or null.
 * /*from  w  ww  . j av  a  2 s .c  o m*/
 * @param cert is the certificate to parse
 * @throws CertificateParsingException
 */
public static String getAuthorityInformationAccessOcspUrl(Certificate cert) throws CertificateParsingException {
    String ret = null;
    if (cert instanceof X509Certificate) {
        X509Certificate x509cert = (X509Certificate) cert;
        try {
            DERObject obj = getExtensionValue(x509cert, X509Extensions.AuthorityInfoAccess.getId());
            if (obj == null) {
                return null;
            }
            AuthorityInformationAccess aia = AuthorityInformationAccess.getInstance(obj);
            AccessDescription[] ad = aia.getAccessDescriptions();
            if ((ad != null) && (ad.length > 0)) {
                for (int i = 0; i < ad.length; i++) {
                    if (ad[i].getAccessMethod().equals(X509ObjectIdentifiers.ocspAccessMethod)) {
                        GeneralName gn = ad[i].getAccessLocation();
                        if (gn.getTagNo() == 6) {
                            DERIA5String str = DERIA5String.getInstance(gn.getDERObject());
                            ret = str.getString();
                            break; // no need to go on any further, we got a value
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.error("Error parsing AuthorityInformationAccess", e);
            throw new CertificateParsingException(e.toString());
        }
    }
    return ret;
}

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

/**
 * Se conecta a la url indicada y se descarga las crls. No se esta usando
 * *******************!!! En desarrollo, no funciona
 * //from  ww  w .j  av  a2s. c  om
 * @param hostURL
 * @return
 * @throws CRLException
 *             No se ha podido recuperar el listado
 * @throws CertificateParsingException
 */
@SuppressWarnings("unchecked")
private InputStream getIoCrlFromFNMTLDAP(X509Certificate certificadoX509)
        throws CRLException, CertificateParsingException {
    // ************************
    // recupero las propiedades para realizar la busqueda en LDAP.
    // EJ :[CN=CRL1, OU=FNMT Clase 2 CA, O=FNMT, C=ES] {2.5.4.11=FNMT Clase
    // 2 CA, 2.5.4.10=FNMT, 2.5.4.6=ES, 2.5.4.3=CRL1}
    Map<String, String> propiedades = new HashMap<String, String>();
    try {
        log.debug("Recuperando puntos de distribucin CRL del certificado FNMT: "
                + certificadoX509.getIssuerDN());
        // recupero la extensin OID 2.5.29.31 ( id-ce-cRLDistributionPoinds
        // segun el RFC 3280 seccin 4.2.1.14)
        byte[] val1 = certificadoX509.getExtensionValue(OID_CRLS);
        if (val1 == null) {
            log.debug("   El certificado NO tiene punto de distribucin de CRL ");
        } else {
            ASN1InputStream oAsnInStream = new ASN1InputStream(new ByteArrayInputStream(val1));
            DERObject derObj = oAsnInStream.readObject();
            DEROctetString dos = (DEROctetString) derObj;
            byte[] val2 = dos.getOctets();
            ASN1InputStream oAsnInStream2 = new ASN1InputStream(new ByteArrayInputStream(val2));
            DERObject derObj2 = oAsnInStream2.readObject();

            X509Handler.getCurrentInstance().readPropiedadesOid(OID_CRLS, derObj2, propiedades);

        }
    } catch (Exception e) {
        e.printStackTrace();
        throw new CertificateParsingException(e.toString());
    }

    // comprobamos la configuracin
    if (isSomeFNMTValorNull()) {
        throw new CRLException(
                "Para el acceso a las CRLs de la FNMT es necesario las credenciales. Indique el parametro de configuracin :"
                        + Constantes.CONEXION_LDAP_CRL_FNMT);
    }

    String CN = "CN=" + propiedades.get(FNMT_CN_IDENTIFICADOR) + "," + certificadoX509.getIssuerDN();
    log.debug("Buscando en el LDAP " + CN);

    // **********************************************
    // Nos conectamos al LDAP para recuperar la CRLs.

    Properties env = new Properties();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, fnmtLDAPHostURL);
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.SECURITY_PRINCIPAL, fnmtPrincipal);
    env.put(Context.SECURITY_CREDENTIALS, fnmtCredencial);
    env.put(Context.REFERRAL, "follow");

    try {
        DirContext ctx = new InitialDirContext(env);
        SearchControls searchControls = new SearchControls();
        searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
        NamingEnumeration namings = (ctx.search(CN, "(objectclass=*)", searchControls));

        log.debug("Se ha logrado conectar al LDAP");

        if (namings.hasMore()) {
            log.debug("Recuperando el contenido de la CRLs");
            // recupero el resultado
            SearchResult resultado = ((SearchResult) namings.next());

            // recupero todos los atributos del resultado
            Attributes avals = resultado.getAttributes();

            // recupero los bytes.
            byte[] bytes;
            if ((avals.get("certificateRevocationList;binary")) != null) {
                log.debug("Atributos deben estar en binario");
                Attribute atributo = (avals.get("certificateRevocationList;binary"));
                bytes = ((byte[]) atributo.get());
            } else {
                log.debug("Atributos en exadecimal En Hexadecimal");
                Attribute atributo = (avals.get("certificateRevocationList"));
                bytes = ((byte[]) atributo.get());
                log.debug("Por implementar");
            }

            if (bytes != null) {
                ByteArrayInputStream io = new ByteArrayInputStream(bytes);
                return io;
            }
        }
    } catch (NamingException e) {
        log.error("No se puede conectar al LDAP!!", e);
    }
    return null;
}

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

/**
 * Recupero los puntos de distribucin/*  ww  w  .  j  ava2 s  .c  om*/
 * 
 * @param certificadoX509
 * @return
 */
private List<String> getCrlPuntosDeDistribucion(X509Certificate certificadoX509)
        throws CertificateParsingException {
    try {
        log.debug("Recuperando puntos de distribucin CRL del certificado: " + certificadoX509.getSubjectDN());
        // recupero la extensin OID 2.5.29.31 ( id-ce-cRLDistributionPoinds
        // segun el RFC 3280 seccin 4.2.1.14)

        byte[] val1 = certificadoX509.getExtensionValue(OID_CRLS);
        if (val1 == null) {
            if (certificadoX509.getSubjectDN().getName().equals(certificadoX509.getIssuerDN().getName())) {
                log.debug("El certificado es un certificado raiz: " + certificadoX509.getSubjectDN().getName());
            } else {
                log.warn("   El certificado NO tiene punto de distribucin de CRL : "
                        + certificadoX509.getSubjectDN().getName());
            }
            return Collections.emptyList();
        } else {
            ASN1InputStream oAsnInStream = new ASN1InputStream(new ByteArrayInputStream(val1));
            DERObject derObj = oAsnInStream.readObject();
            DEROctetString dos = (DEROctetString) derObj;
            byte[] val2 = dos.getOctets();
            ASN1InputStream oAsnInStream2 = new ASN1InputStream(new ByteArrayInputStream(val2));
            DERObject derObj2 = oAsnInStream2.readObject();
            // Map<String,String> propiedades= new HashMap<String,String>();
            List<String> urls = getDERValue(derObj2);
            return urls;
            /*
             * CertificadoHelper.getCurrentInstance().readPropiedadesOid(OID_CRLS,derObj2,propiedades);
             * if(log.isDebugEnabled())log.debug("Informacin sobre CRls del
             * certificado que ha sido recuperada: "+propiedades); // por
             * simplificar, aunque el certificado informe de varias crls que
             * utilizar. Solo trabajamos con la primera List listaCrls=new
             * ArrayList(1); listaCrls.add(propiedades.get(OID_CRLS));
             * return listaCrls;//listaCrls.addAll(getDERValue(derObj2))
             */}
    } catch (Exception e) {
        e.printStackTrace();
        throw new CertificateParsingException(e.toString());
    }
}