List of usage examples for org.bouncycastle.asn1 DEROctetString getOctets
public byte[] getOctets()
From source file:org.usrz.libs.crypto.cert.X509CertificateBuilder.java
License:Apache License
/** * Set the {@linkplain X509Certificate certificate} of the authority * issuing the certificate./* w ww. j a v a2s . c o m*/ * * <p>This method will set the issuer's * {@linkplain #withIssuer(X500Principal) principal}, * {@linkplain #withIssuerPublicKey(PublicKey) public key} * and will attempt to copy the issuer's * {@linkplain #withCrlDistributionPoint(URI) CRL distribution points} * in the issued certificate.</p> */ public X509CertificateBuilder withIssuer(X509Certificate issuer) { if (issuer == null) throw new NullPointerException("Null issuer"); this.withIssuer(issuer.getSubjectX500Principal()); withIssuerPublicKey(issuer.getPublicKey()); final byte[] crl = issuer.getExtensionValue(Extension.cRLDistributionPoints.toString()); if (crl != null) try { final DEROctetString value = (DEROctetString) ASN1Primitive.fromByteArray(crl); final CRLDistPoint crlDistPoint = CRLDistPoint.getInstance(value.getOctets()); for (DistributionPoint distPoint : crlDistPoint.getDistributionPoints()) { final DistributionPointName distPointName = distPoint.getDistributionPoint(); final GeneralNames names = (GeneralNames) distPointName.getName(); for (GeneralName name : names.getNames()) { crlDistributionPoints.add(name); } } } catch (Exception exception) { Logger.getLogger(this.getClass().getName()).log(Level.WARNING, "Unable to parse CRL distribution points", exception); } return this; }
From source file:org.viafirma.nucleo.validacion.CRLUtil.java
License:Open Source License
/** * Se conecta a la url indicada y se descarga las crls. No se esta usando * *******************!!! En desarrollo, no funciona * /*from w ww . j a va 2s . com*/ * @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
License:Open Source License
/** * Recupero los puntos de distribucin/*from w ww.jav a 2 s . c o m*/ * * @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()); } }
From source file:org.viafirma.nucleo.validacion.CRLUtil.java
License:Open Source License
/** * Parsea el objeto y devuelve un listado con las urls de punto de * distribucin de las CRLs/* w ww . j a va2 s . c o m*/ * * @param derObj * @return */ @SuppressWarnings("unchecked") private List<String> getDERValue(DERObject derObj) { if (derObj instanceof DERSequence) { List<String> list = new LinkedList<String>(); DERSequence seq = (DERSequence) derObj; Enumeration enumeracion = seq.getObjects(); while (enumeracion.hasMoreElements()) { DERObject nestedObj = (DERObject) enumeracion.nextElement(); List<String> appo = getDERValue(nestedObj); if (appo != null) { list.addAll(appo); } } return list; } else if (derObj instanceof DERTaggedObject) { DERTaggedObject derTag = (DERTaggedObject) derObj; if ((derTag.isExplicit() && !derTag.isEmpty()) || derTag.getObject() instanceof DERSequence) { DERObject nestedObj = derTag.getObject(); List<String> ret = getDERValue(nestedObj); return ret; } else { DEROctetString derOct = (DEROctetString) derTag.getObject(); String val = new String(derOct.getOctets()); List<String> ret = new LinkedList<String>(); ret.add(val); return ret; } } else if (derObj instanceof DERSet) { Enumeration enumSet = ((DERSet) derObj).getObjects(); List<String> list = new LinkedList<String>(); while (enumSet.hasMoreElements()) { DERObject nestedObj = (DERObject) enumSet.nextElement(); List<String> appo = getDERValue(nestedObj); if (appo != null) { list.addAll(appo); } } return list; } else if (derObj instanceof DERObjectIdentifier) { DERObjectIdentifier derId = (DERObjectIdentifier) derObj; List<String> list = new LinkedList<String>(); list.add(derId.getId()); return list; } else if (derObj instanceof DERPrintableString) { // hemos localizado un par id-valor String valor = ((DERPrintableString) derObj).getString(); List<String> list = new LinkedList<String>(); list.add(valor); return list; } else { log.fatal("tipo de dato en ASN1 al recuperar las crls no es reconocido : " + derObj); } return null; }
From source file:org.viafirma.nucleo.X509.X509Handler.java
License:Open Source License
/** * Navega sobre los campos ASN.1 del certificado recuperando los pares valor * oid= valor//from w w w. j ava 2 s . com * * @param extensionType * @param propiedadesOid */ @SuppressWarnings("unchecked") public void readPropiedadesOid(String oidActual, DERObject extension, Map<String, String> propiedadesOid) { if (extension instanceof DERSequence) { // tengo un objeto de tipo secuence. DERSequence secuence = (DERSequence) extension; Enumeration enumObjetos = secuence.getObjects(); String oidUtilizadoNodo = oidActual; while (enumObjetos.hasMoreElements()) { DERObject objeto = (DERObject) enumObjetos.nextElement(); // si este objeto fuese un identificador quiere decir que el // siguiente seria un objeto que queremos guardar if (objeto instanceof DERObjectIdentifier) { DERObjectIdentifier objetoID = (DERObjectIdentifier) objeto; // este es el oid utilizado para los nodos que estan por // debajo del actual oidUtilizadoNodo = objetoID.getId(); } else { readPropiedadesOid(oidUtilizadoNodo, objeto, propiedadesOid); } } } else if (extension instanceof DERObjectIdentifier) { // el objeto es un identificador. DERObjectIdentifier objetoID = (DERObjectIdentifier) extension; String oid = objetoID.getId(); System.out.println("Valor perdido " + oid); } else if (extension instanceof DERIA5String) { // hemos localizado un par id-valor String valor = ((DERIA5String) extension).getString(); propiedadesOid.put(oidActual, valor); } else if (extension instanceof DERVisibleString) { // hemos localizado un par id-valor String valor = ((DERVisibleString) extension).getString(); propiedadesOid.put(oidActual, valor); } else if (extension instanceof DERPrintableString) { // hemos localizado un par id-valor String valor = ((DERPrintableString) extension).getString(); propiedadesOid.put(oidActual, valor); } else if (extension instanceof DERBitString) { String valor = "" + ((DERBitString) extension).getPadBits(); propiedadesOid.put(oidActual, valor); } else if (extension instanceof DERSet) { Enumeration enumSet = ((DERSet) extension).getObjects(); while (enumSet.hasMoreElements()) { readPropiedadesOid(oidActual, (DERObject) enumSet.nextElement(), propiedadesOid); } } else if (extension instanceof DERTaggedObject) { DERTaggedObject derTag = (DERTaggedObject) extension; if ((derTag.isExplicit() && !derTag.isEmpty()) || derTag.getObject() instanceof DERSequence) { DERObject nestedObj = derTag.getObject(); readPropiedadesOid(oidActual, nestedObj, propiedadesOid); } else { DEROctetString derOct = (DEROctetString) derTag.getObject(); readPropiedadesOid(oidActual, derOct, propiedadesOid); } } /* * else if(extension instanceof DERTaggedObject){ DERTaggedObject * tagged=((DERTaggedObject)extension); int tagNo=tagged.getTagNo(); * readPropiedadesOid(oidActual,tagged.getObject(),propiedadesOid); * * * //propiedadesOid.put(oidActual,valor); } */else if (extension instanceof DEROctetString) { DEROctetString oct = (DEROctetString) extension; // ASN1InputStream aIn= new ASN1InputStream(oct.getOctets()); ASN1InputStream aIn = new ASN1InputStream(new ByteArrayInputStream(oct.getOctets())); try { DERObject extensionObj = aIn.readObject(); readPropiedadesOid(oidActual, extensionObj, propiedadesOid); } catch (IOException e) { // si no es un nuevo objeto codificado quizas sea un string(ej : // las crls se recuperan asi) propiedadesOid.put(oidActual, new String(oct.getOctets())); } catch (IllegalStateException e) { // Problema extrao detectado con los certificados corruptos. // OID: 2.5.29.14 :java.lang.IllegalStateException: DER length // more than 4 bytes // DER length more than 4 bytes log.warn(e.getMessage()); } catch (Exception e) { // Problema extrao detectado con los certificados corruptos. // OID: 2.5.29.14 :java.lang.IllegalStateException: DER length // more than 4 bytes e.printStackTrace(); } } else if (extension instanceof DERInteger) { String valor = "" + ((DERInteger) extension).getValue().longValue(); propiedadesOid.put(oidActual, valor); } else if (extension instanceof DERT61String) { String valor = ((DERT61String) extension).getString(); propiedadesOid.put(oidActual, valor); } else if (extension instanceof DERUTF8String) { String valor = ((DERUTF8String) extension).getString(); propiedadesOid.put(oidActual, valor); } else if (extension instanceof DERApplicationSpecific) { DERApplicationSpecific temp = (DERApplicationSpecific) extension; String valor = new String(temp.getContents()); propiedadesOid.put(oidActual, valor); } else { log.warn("Tipo de estructura ANS1 no soportada: " + extension); } // log.debug("tipo de dato en ASN1 parsear estructura : "+extension); }
From source file:org.wso2.carbon.identity.authenticator.pki.cert.validation.crl.CRLVerifier.java
License:Apache License
/** * Extracts all CRL distribution point URLs from the * "CRL Distribution Point"/*from www . j av a2s.c o m*/ * extension in a X.509 certificate. If CRL distribution point extension is * unavailable, returns an empty list. */ private List<String> getCrlDistributionPoints(X509Certificate cert) throws CertificateVerificationException { // Gets the DER-encoded OCTET string for the extension value for // CRLDistributionPoints byte[] crlDPExtensionValue = cert.getExtensionValue(X509Extensions.CRLDistributionPoints.getId()); if (crlDPExtensionValue == null) throw new CertificateVerificationException("Certificate doesn't have CRL Distribution points"); // crlDPExtensionValue is encoded in ASN.1 format. ASN1InputStream asn1In = new ASN1InputStream(crlDPExtensionValue); // DER (Distinguished Encoding Rules) is one of ASN.1 encoding rules // defined in ITU-T X.690, 2002, specification. // ASN.1 encoding rules can be used to encode any data object into a // binary file. Read the object in octets. CRLDistPoint distPoint; try { DEROctetString crlDEROctetString = (DEROctetString) asn1In.readObject(); // Get Input stream in octets ASN1InputStream asn1InOctets = new ASN1InputStream(crlDEROctetString.getOctets()); DERObject crlDERObject = asn1InOctets.readObject(); distPoint = CRLDistPoint.getInstance(crlDERObject); } catch (IOException e) { throw new CertificateVerificationException("Cannot read certificate to get CRL urls", e); } List<String> crlUrls = new ArrayList<String>(); // Loop through ASN1Encodable DistributionPoints for (DistributionPoint dp : distPoint.getDistributionPoints()) { // get ASN1Encodable DistributionPointName DistributionPointName dpn = dp.getDistributionPoint(); if (dpn != null && dpn.getType() == DistributionPointName.FULL_NAME) { // Create ASN1Encodable General Names GeneralName[] genNames = GeneralNames.getInstance(dpn.getName()).getNames(); // Look for a URI // todo: May be able to check for OCSP url specifically. for (GeneralName genName : genNames) { if (genName.getTagNo() == GeneralName.uniformResourceIdentifier) { // DERIA5String contains an ascii string. // A IA5String is a restricted character string type in // the ASN.1 notation String url = DERIA5String.getInstance(genName.getName()).getString().trim(); crlUrls.add(url); } } } } if (crlUrls.isEmpty()) throw new CertificateVerificationException("Cant get CRL urls from certificate"); return crlUrls; }
From source file:org.wso2.carbon.identity.authenticator.pki.cert.validation.ocsp.OCSPVerifier.java
License:Apache License
/** * Authority Information Access (AIA) is a non-critical extension in an X509 * Certificate. This contains the/* w ww.j av a2 s . c o m*/ * URL of the OCSP endpoint if one is available. * TODO: This might contain non OCSP urls as well. Handle this. * * @param cert * is the certificate * @return a lit of URLs in AIA extension of the certificate which will * hopefully contain an OCSP endpoint. * @throws CertificateVerificationException * */ private List<String> getAIALocations(X509Certificate cert) throws CertificateVerificationException { // Gets the DER-encoded OCTET string for the extension value for // Authority information access Points byte[] aiaExtensionValue = cert.getExtensionValue(X509Extensions.AuthorityInfoAccess.getId()); if (aiaExtensionValue == null) throw new CertificateVerificationException( "Certificate Doesnt have Authority Information Access points"); // might have to pass an ByteArrayInputStream(aiaExtensionValue) ASN1InputStream asn1In = new ASN1InputStream(aiaExtensionValue); AuthorityInformationAccess authorityInformationAccess; try { DEROctetString aiaDEROctetString = (DEROctetString) (asn1In.readObject()); ASN1InputStream asn1Inoctets = new ASN1InputStream(aiaDEROctetString.getOctets()); ASN1Sequence aiaASN1Sequence = (ASN1Sequence) asn1Inoctets.readObject(); authorityInformationAccess = new AuthorityInformationAccess(aiaASN1Sequence); } catch (IOException e) { throw new CertificateVerificationException("Cannot read certificate to get OSCP urls", e); } List<String> ocspUrlList = new ArrayList<String>(); AccessDescription[] accessDescriptions = authorityInformationAccess.getAccessDescriptions(); for (AccessDescription accessDescription : accessDescriptions) { GeneralName gn = accessDescription.getAccessLocation(); if (gn.getTagNo() == GeneralName.uniformResourceIdentifier) { DERIA5String str = DERIA5String.getInstance(gn.getName()); String accessLocation = str.getString(); ocspUrlList.add(accessLocation); } } if (ocspUrlList.isEmpty()) throw new CertificateVerificationException("Cant get OCSP urls from certificate"); return ocspUrlList; }
From source file:org.xdi.oxauth.cert.validation.CRLCertificateVerifier.java
License:MIT License
@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 a v a2s . 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; }
From source file:org.xipki.commons.security.shell.ExtractCertFromCrlCmd.java
License:Open Source License
private static byte[] removingTagAndLenFromExtensionValue(final byte[] encodedExtensionValue) { DEROctetString derOctet = (DEROctetString) DEROctetString.getInstance(encodedExtensionValue); return derOctet.getOctets(); }
From source file:org.xipki.security.api.p11.remote.PSOTemplate.java
License:Open Source License
private PSOTemplate(final ASN1Sequence seq) { if (seq.size() != 2) { throw new IllegalArgumentException("wrong number of elements in sequence"); }/*ww w . ja v a2 s. c o m*/ this.slotAndKeyIdentifier = SlotAndKeyIdentifer.getInstance(seq.getObjectAt(0)); DEROctetString octetString = (DEROctetString) DEROctetString.getInstance(seq.getObjectAt(1)); this.message = octetString.getOctets(); }