Example usage for org.bouncycastle.asn1 DERSequence getObjects

List of usage examples for org.bouncycastle.asn1 DERSequence getObjects

Introduction

In this page you can find the example usage for org.bouncycastle.asn1 DERSequence getObjects.

Prototype

public Enumeration getObjects() 

Source Link

Usage

From source file:org.dcache.gridsite.BouncyCastleCredentialDelegation.java

License:Open Source License

private static X509Name buildProxyDN(X500Principal principal) throws GeneralSecurityException {
    ASN1StreamParser parser = new ASN1StreamParser(principal.getEncoded());

    DERSequence seq;
    try {//from ww w.  j  av  a 2 s.c o m
        ASN1Encodable object = parser.readObject().getDERObject();
        if (!(object instanceof DERSequence)) {
            throw new IOException("not a DER-encoded ASN.1 sequence");
        }
        seq = (DERSequence) object;
    } catch (IOException e) {
        throw new GeneralSecurityException("failed to parse DN: " + e.getMessage());
    }

    List<ASN1Encodable> rdn = new ArrayList<>(seq.size() + 1);
    for (Enumeration e = seq.getObjects(); e.hasMoreElements();) {
        rdn.add((ASN1Encodable) e.nextElement());
    }

    DERSequence atv = new DERSequence(new ASN1Object[] { X509Name.CN, new DERPrintableString("proxy") });
    rdn.add(new DERSet(atv));

    ASN1Encodable[] rdnArray = rdn.toArray(new ASN1Encodable[rdn.size()]);
    return new X509Name(new DERSequence(rdnArray));
}

From source file:org.ejbca.core.model.ca.certextensions.BasicCertificateExtensionTest.java

License:Open Source License

public void test10SequencedExtension() throws Exception {
    Properties props = new Properties();
    props.put("id1.property.encoding", "DERUTF8STRING "); // Also test that we ignore spaces in the end here
    props.put("id1.property.nvalues", "3");
    props.put("id1.property.value1", "foo1");
    props.put("id1.property.value2", "foo2");
    props.put("id1.property.value3", "foo3");

    BasicCertificateExtension baseExt = new BasicCertificateExtension();
    baseExt.init(1, "1.2.3", false, props);

    DEREncodable value = getObject(baseExt.getValueEncoded(null, null, null, null, null));
    assertTrue(value.getClass().toString(), value instanceof DERSequence);
    DERSequence seq = (DERSequence) value;
    assertEquals(3, seq.size());/*from  w ww  .  j  ava  2s . c o  m*/
    Enumeration e = seq.getObjects();
    int i = 1;
    while (e.hasMoreElements()) {
        DEREncodable v = (DEREncodable) e.nextElement();
        assertTrue(v.getClass().toString(), v instanceof DERUTF8String);
        String str = ((DERUTF8String) v).getString();
        log.info(str);
        assertEquals(str, "foo" + i++);
    }
}

From source file:org.ejbca.core.model.ca.certextensions.BasicCertificateExtensionTest.java

License:Open Source License

/**
 * Test with dynamic=true and and a static value specified where nvalues are used.
 *
 * The static values should be used if no value was specified in ExtendedInformation.
 * The values from ExtendedInformation should be used if present.
 *//*w w w .j av a 2 s.  c  o  m*/
public void test15DynamicTrueStaticNvalues() throws Exception {
    Properties props = new Properties();
    props.put("id1.property.encoding", "DERPRINTABLESTRING");
    props.put("id1.property.dynamic", "true");
    props.put("id1.property.nvalues", "3");
    props.put("id1.property.value1", "The static value 1");
    props.put("id1.property.value2", "The static value 2");
    props.put("id1.property.value3", "The static value 3");
    BasicCertificateExtension baseExt = new BasicCertificateExtension();
    baseExt.init(1, "1.2.3", false, props);
    UserDataVO userData = new UserDataVO();
    userData.setExtendedinformation(new ExtendedInformation());

    // Without value in userdata, the static values is used
    ASN1InputStream in = new ASN1InputStream(
            new ByteArrayInputStream(baseExt.getValueEncoded(userData, null, null, null, null)));
    DEREncodable value = in.readObject();
    assertTrue(value.getClass().toString(), value instanceof DERSequence);
    DERSequence seq = (DERSequence) value;
    assertEquals(3, seq.size());
    Enumeration e = seq.getObjects();
    int i = 1;
    while (e.hasMoreElements()) {
        DEREncodable v = (DEREncodable) e.nextElement();
        assertTrue(v.getClass().toString(), v instanceof DERPrintableString);
        String str = ((DERPrintableString) v).getString();
        assertEquals(str, "The static value " + i++);
    }

    // With values in userdata, that values is used
    userData.getExtendedinformation().setExtensionData("1.2.3.value1", "A dynamic value 1");
    userData.getExtendedinformation().setExtensionData("1.2.3.value2", "A dynamic value 2");
    userData.getExtendedinformation().setExtensionData("1.2.3.value3", "A dynamic value 3");
    in = new ASN1InputStream(
            new ByteArrayInputStream(baseExt.getValueEncoded(userData, null, null, null, null)));
    value = in.readObject();
    assertTrue(value.getClass().toString(), value instanceof DERSequence);
    seq = (DERSequence) value;
    assertEquals(3, seq.size());
    e = seq.getObjects();
    i = 1;
    while (e.hasMoreElements()) {
        DEREncodable v = (DEREncodable) e.nextElement();
        assertTrue(v.getClass().toString(), v instanceof DERPrintableString);
        String str = ((DERPrintableString) v).getString();
        assertEquals(str, "A dynamic value " + i++);
    }
}

From source file:org.ejbca.core.protocol.MSPKCS10RequestMessage.java

License:Open Source License

/**
 * Returns the MS request client info object (1.3.6.1.4.1.311.21.20) as an ArrayList<String>.
 * /*w  w w. j  av  a  2 s . c  o  m*/
 * E.g. an Machine-template request contains the following structure
 *     SEQUENCE {
 *             209    9:         OBJECT IDENTIFIER '1 3 6 1 4 1 311 21 20'
 *                 220   57:         SET {
 *                     222   55:           SEQUENCE {
 *                         224    1:             INTEGER 1
 *                             227   18:             UTF8String 'host.company.local'
 *                          247   21:             UTF8String 'COMPANY\Administrator'
 *                          270    7:             UTF8String 'certreq'
 *                :             }
 *                :           }
 *                :         }
 */
private ArrayList<String> getMSRequestInfo() {
    ArrayList<String> ret = new ArrayList<String>();
    if (pkcs10 == null) {
        log.error("PKCS10 not inited!");
        return ret;
    }
    // Get attributes
    Attribute[] attributes = pkcs10.getAttributes(new ASN1ObjectIdentifier(szOID_REQUEST_CLIENT_INFO));
    if (attributes.length == 0) {
        return ret;
    } else {
        ASN1Set values = attributes[0].getAttrValues();
        if (values.size() == 0) {
            return ret;
        }
        DERSequence seq = (DERSequence) DERSequence.getInstance(values.getObjectAt(0));
        Enumeration<?> enumeration = seq.getObjects();
        while (enumeration.hasMoreElements()) {
            Object current = enumeration.nextElement();
            if (current instanceof DERPrintableString) {
                ret.add(((DERPrintableString) current).getString());
            } else if (current instanceof DERUTF8String) {
                ret.add(((DERUTF8String) current).getString());
            } else if (current instanceof ASN1Integer) {
                ret.add(((ASN1Integer) current).toString());
            } else {
                ret.add("Unsupported type: " + current.getClass().getName());
            }
        }
        Iterator<String> iter = ret.iterator();
        while (iter.hasNext()) {
            log.info("TEMP-DEBUG-: " + iter.next());
        }
    }
    return ret;
}

From source file:org.ejbca.core.protocol.MSPKCS10RequestMessage.java

License:Open Source License

/**
 * Returns the name of the Certificate Template or null if not available or not known.
 *///from www  . j  av a 2  s  .co  m
public String getMSRequestInfoTemplateName() {
    if (pkcs10 == null) {
        log.error("PKCS10 not inited!");
        return null;
    }
    // Get attributes
    Attribute[] attributes = pkcs10.getAttributes(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest);
    if (attributes.length == 0) {
        log.error("Cannot find request extension.");
        return null;
    }
    ASN1Set set = attributes[0].getAttrValues();
    DERSequence seq = (DERSequence) DERSequence.getInstance(set.getObjectAt(0));
    Enumeration<?> enumeration = seq.getObjects();
    while (enumeration.hasMoreElements()) {
        DERSequence seq2 = (DERSequence) DERSequence.getInstance(enumeration.nextElement());
        ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier) seq2.getObjectAt(0);
        if (szOID_ENROLL_CERTTYPE_EXTENSION.equals(oid.getId())) {
            try {
                DEROctetString dos = (DEROctetString) seq2.getObjectAt(1);
                ASN1InputStream dosAsn1InputStream = new ASN1InputStream(
                        new ByteArrayInputStream(dos.getOctets()));
                try {
                    ASN1String derobj = (ASN1String) dosAsn1InputStream.readObject();
                    return derobj.getString();
                } finally {
                    dosAsn1InputStream.close();
                }
            } catch (IOException e) {
                log.error(e);
            }
        }
    }
    return null;
}

From source file:org.ejbca.core.protocol.MSPKCS10RequestMessage.java

License:Open Source License

/**
 * Returns a String vector with known subject altnames:
 *   [0] Requested GUID//from www.  j a  v a2  s.c om
 *   [1] Requested DNS
 */
public String[] getMSRequestInfoSubjectAltnames() {
    String[] ret = new String[2]; // GUID, DNS so far..
    if (pkcs10 == null) {
        log.error("PKCS10 not inited!");
        return ret;
    }
    // Get attributes
    Attribute[] attributes = pkcs10.getAttributes(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest);
    if (attributes.length != 0) {
        ASN1Set set = attributes[0].getAttrValues();
        DERSequence seq = (DERSequence) DERSequence.getInstance(set.getObjectAt(0));
        Enumeration<?> enumeration = seq.getObjects();
        while (enumeration.hasMoreElements()) {
            DERSequence seq2 = (DERSequence) DERSequence.getInstance(enumeration.nextElement());
            ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier) seq2.getObjectAt(0);
            if ("2.5.29.17".equals(oid.getId())) { //SubjectAN
                try {
                    DEROctetString dos = (DEROctetString) seq2.getObjectAt(2);
                    ASN1InputStream ais = new ASN1InputStream(new ByteArrayInputStream(dos.getOctets()));
                    while (ais.available() > 0) {
                        DERSequence seq3 = (DERSequence) ais.readObject();
                        Enumeration<?> enum1 = seq3.getObjects();
                        while (enum1.hasMoreElements()) {
                            DERTaggedObject dto = (DERTaggedObject) enum1.nextElement();
                            if (dto.getTagNo() == 0) {
                                // Sequence of OIDs and tagged objects
                                DERSequence ds = (DERSequence) dto.getObject();
                                ASN1ObjectIdentifier doid = (ASN1ObjectIdentifier) ds.getObjectAt(0);
                                if (OID_GUID.equals((doid).getId())) {
                                    DEROctetString dos3 = (DEROctetString) ((DERTaggedObject) ds.getObjectAt(1))
                                            .getObject();
                                    ret[0] = dos3.toString().substring(1); // Removes the initial #-sign
                                }
                            } else if (dto.getTagNo() == 2) {
                                // DNS
                                DEROctetString dos3 = (DEROctetString) dto.getObject();
                                ret[1] = new String(dos3.getOctets());
                            }
                        }
                    }
                    ais.close();
                } catch (IOException e) {
                    log.error(e);
                }
            }
        }
    }
    return ret;
}

From source file:org.glite.security.util.proxy.ProxyRestrictionData.java

License:Apache License

/**
 * This method copies the contents of a generalSubtrees sequence into the given vector. Static to protect the
 * internal data structures from access.
 * //from   ww  w  .j a  v  a 2 s.  c o  m
 * @param subSeq the subsequence to copy.
 * @param vector The target to copy the parsed GeneralSubtree objects.
 */
private static void copyCondSequenceToVector(DERSequence subSeq, Vector<GeneralSubtree> vector) {
    Enumeration<DERObject> subTreeEnum = subSeq.getObjects();
    while (subTreeEnum.hasMoreElements()) {
        DERObject object = subTreeEnum.nextElement();
        vector.add(new GeneralSubtree((ASN1Sequence) object));
    }
}

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//from   w  w  w .j  a  va2s . c om
 * 
 * @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  .  ja va  2  s  .c om
 * 
 * @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);
}