Example usage for org.bouncycastle.asn1 DERSequence size

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

Introduction

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

Prototype

public int size() 

Source Link

Document

Return the number of objects in this sequence.

Usage

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

License:Open Source License

protected void writeToEmptyCrl(OutputStream out) throws IOException {
    ASN1InputStream asn1in = null;
    try {//from  w w  w  .j  a v a  2  s .  c  o m
        asn1in = new ASN1InputStream(crlIn);
        DERSequence certListSeq = (DERSequence) asn1in.readObject();
        CertificateList certList = new CertificateList(certListSeq);
        X509CRLHolder oldCrl = new X509CRLHolder(certList);

        X509v2CRLBuilder crlBuilder = new X509v2CRLBuilder(oldCrl.getIssuer(), new Date());
        crlBuilder.addCRL(oldCrl);

        Date now = new Date();
        Date oldNextUpdate = certList.getNextUpdate().getDate();
        Date oldThisUpdate = certList.getThisUpdate().getDate();

        Date nextUpdate = new Date(now.getTime() + (oldNextUpdate.getTime() - oldThisUpdate.getTime()));
        crlBuilder.setNextUpdate(nextUpdate);

        for (Object o : oldCrl.getExtensionOIDs()) {
            ASN1ObjectIdentifier oid = (ASN1ObjectIdentifier) o;
            X509Extension ext = oldCrl.getExtension(oid);

            if (oid.equals(X509Extension.cRLNumber)) {
                DEROctetString octet = (DEROctetString) ext.getValue().getDERObject();
                DERInteger currentNumber = (DERInteger) DERTaggedObject.fromByteArray(octet.getOctets());
                DERInteger nextNumber = new DERInteger(currentNumber.getValue().add(BigInteger.ONE));

                crlBuilder.addExtension(oid, ext.isCritical(), nextNumber);
            } else if (oid.equals(X509Extension.authorityKeyIdentifier)) {
                crlBuilder.addExtension(oid, ext.isCritical(),
                        new AuthorityKeyIdentifierStructure(ext.getValue().getDEREncoded()));
            }
        }

        for (DERSequence entry : newEntries) {
            // XXX: This is all a bit messy considering the user already passed in the serial, date
            // and reason.
            BigInteger serial = ((DERInteger) entry.getObjectAt(0)).getValue();
            Date revokeDate = ((Time) entry.getObjectAt(1)).getDate();
            int reason = CRLReason.unspecified;
            if (entry.size() == 3) {
                X509Extensions extensions = (X509Extensions) entry.getObjectAt(2);
                X509Extension reasonExt = extensions.getExtension(X509Extension.reasonCode);

                if (reasonExt != null) {
                    reason = ((DEREnumerated) reasonExt.getParsedValue()).getValue().intValue();
                }
            }
            crlBuilder.addCRLEntry(serial, revokeDate, reason);
        }

        RSAKeyParameters keyParams = new RSAKeyParameters(true, key.getModulus(), key.getPrivateExponent());

        signingAlg = oldCrl.toASN1Structure().getSignatureAlgorithm();
        digestAlg = new DefaultDigestAlgorithmIdentifierFinder().find(signingAlg);

        ContentSigner s;
        try {
            s = new BcRSAContentSignerBuilder(signingAlg, digestAlg).build(keyParams);
            X509CRLHolder newCrl = crlBuilder.build(s);
            out.write(newCrl.getEncoded());
        } catch (OperatorCreationException e) {
            throw new IOException("Could not sign CRL", e);
        }
    } finally {
        IOUtils.closeQuietly(asn1in);
    }
}

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 2s  . co  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.demoiselle.signer.policy.engine.asn1.etsi.CMSAttrs.java

License:Open Source License

@Override
public void parse(ASN1Primitive derObject) {
    DERSequence derSequence = (DERSequence) derObject;
    int total = derSequence.size();
    for (int i = 0; i < total; i++) {
        ObjectIdentifier objectIdentifier = new ObjectIdentifier();
        objectIdentifier.parse(derSequence.getObjectAt(i).toASN1Primitive());
        if (this.objectIdentifiers == null) {
            this.objectIdentifiers = new ArrayList<ObjectIdentifier>();
        }/*  ww  w  .  jav  a  2  s  .  c o  m*/
        this.objectIdentifiers.add(objectIdentifier);
    }
}

From source file:org.demoiselle.signer.policy.engine.asn1.etsi.PathLenConstraint.java

License:Open Source License

@Override
public void parse(ASN1Primitive derObject) {
    DERTaggedObject derTaggedObject = (DERTaggedObject) derObject;
    DERSequence derSequence = (DERSequence) derTaggedObject.getObject();
    int total = derSequence.size();
    for (int i = 0; i < total; i++) {
        ObjectIdentifier objectIdentifier = new ObjectIdentifier();
        objectIdentifier.parse(derSequence.getObjectAt(i).toASN1Primitive());
        if (this.pathLenConstraints == null) {
            this.pathLenConstraints = new ArrayList<ObjectIdentifier>();
        }/*from w w w  .ja  va 2s .  c  om*/
        this.pathLenConstraints.add(objectIdentifier);
    }
}

From source file:org.demoiselle.signer.policy.engine.asn1.etsi.PolicyIssuerName.java

License:Open Source License

@Override
public void parse(ASN1Primitive primitive) {
    if (primitive instanceof DLSequence) {
        DLSequence sequence = (DLSequence) primitive;
        ASN1Encodable asn1Encodable = sequence.getObjectAt(0);
        if (asn1Encodable instanceof DERTaggedObject) {
            DERTaggedObject derTaggedObject = (DERTaggedObject) asn1Encodable;
            ASN1Primitive object = derTaggedObject.getObject();
            if (object instanceof DEROctetString) {
                OctetString octetString = new OctetString();
                octetString.parse(object);
                this.issuerName = octetString.getValueUTF8();
            } else if (object instanceof DERSequence) {
                DERSequence sequence2 = (DERSequence) object;
                for (int i = 0; i < sequence2.size(); i++) {
                    ASN1Encodable obj = sequence2.getObjectAt(i);
                    if (obj instanceof DERSet) {
                        DERSet set = (DERSet) obj;
                        ASN1Encodable object2 = set.getObjectAt(0);
                        if (object2 instanceof DERSequence) {
                            DERSequence sequence3 = (DERSequence) object2;
                            ObjectIdentifier objectIdendifier = new ObjectIdentifier();
                            objectIdendifier.parse(sequence3.getObjectAt(0).toASN1Primitive());
                            String name = null;
                            ASN1Encodable object3 = sequence3.getObjectAt(1);
                            if (object3 instanceof DERPrintableString) {
                                name = ((DERPrintableString) object3).getString();
                            } else if (object3 instanceof DERUTF8String) {
                                name = ((DERUTF8String) object3).getString();
                            } else {
                                System.out.println(policyMessagesBundle.getString("error.not.recognized.object",
                                        object3.getClass(), object3.toString()));
                            }//  www  .  j a v  a 2 s  . c  o m
                            if (this.issuerNames == null) {
                                this.issuerNames = new HashMap<ObjectIdentifier, String>();
                            }
                            this.issuerNames.put(objectIdendifier, name);
                        }
                    }
                }
            }
        }
    }
}

From source file:org.deviceconnect.android.ssl.CertificateAuthority.java

License:MIT License

/**
 * ???? Subject Alternative Names (SANs) ??.
 *
 * @param request ???/*from w w w. j  a v a  2  s.  c o m*/
 * @return SubjectAlternativeNames? {@link GeneralNames} 
 * @throws IOException ?????
 */
private GeneralNames parseSANs(final PKCS10CertificationRequest request) throws IOException {
    List<ASN1Encodable> generalNames = new ArrayList<>();

    CertificationRequestInfo info = request.getCertificationRequestInfo();
    ASN1Set attributes = info.getAttributes();
    for (int i = 0; i < attributes.size(); i++) {
        DEREncodable extensionRequestObj = attributes.getObjectAt(i);
        if (!(extensionRequestObj instanceof DERSequence)) {
            continue;
        }
        DERSequence extensionRequest = (DERSequence) extensionRequestObj;
        if (extensionRequest.size() != 2) {
            continue;
        }
        DEREncodable idObj = extensionRequest.getObjectAt(0);
        DEREncodable contentObj = extensionRequest.getObjectAt(1);
        if (!(idObj instanceof ASN1ObjectIdentifier && contentObj instanceof DERSet)) {
            continue;
        }
        ASN1ObjectIdentifier id = (ASN1ObjectIdentifier) idObj;
        DERSet content = (DERSet) contentObj;
        if (!id.getId().equals("1.2.840.113549.1.9.14")) {
            continue;
        }
        if (content.size() < 1) {
            continue;
        }
        DEREncodable extensionsObj = content.getObjectAt(0);
        if (!(extensionsObj instanceof DERSequence)) {
            continue;
        }
        DERSequence extensions = (DERSequence) extensionsObj;

        for (int k = 0; k < extensions.size(); k++) {
            DEREncodable extensionObj = extensions.getObjectAt(k);
            if (!(extensionObj instanceof DERSequence)) {
                continue;
            }
            DERSequence extension = (DERSequence) extensionObj;
            if (extension.size() != 2) {
                continue;
            }
            DEREncodable extensionIdObj = extension.getObjectAt(0);
            DEREncodable extensionContentObj = extension.getObjectAt(1);
            if (!(extensionIdObj instanceof ASN1ObjectIdentifier)) {
                continue;
            }
            ASN1ObjectIdentifier extensionId = (ASN1ObjectIdentifier) extensionIdObj;
            if (extensionId.getId().equals("2.5.29.17")) {
                DEROctetString san = (DEROctetString) extensionContentObj;

                ASN1StreamParser sanParser = new ASN1StreamParser(san.parser().getOctetStream());
                DEREncodable namesObj = sanParser.readObject().getDERObject();
                if (namesObj instanceof DERSequence) {
                    DERSequence names = (DERSequence) namesObj;
                    for (int m = 0; m < names.size(); m++) {
                        DEREncodable nameObj = names.getObjectAt(m);
                        if (nameObj instanceof DERTaggedObject) {
                            DERTaggedObject name = (DERTaggedObject) nameObj;
                            switch (name.getTagNo()) {
                            case GeneralName.dNSName:
                                generalNames.add(new GeneralName(GeneralName.dNSName,
                                        DERIA5String.getInstance(name, false)));
                                break;
                            case GeneralName.iPAddress:
                                generalNames.add(new GeneralName(GeneralName.iPAddress,
                                        DEROctetString.getInstance(name, true)));
                                break;
                            }
                        }
                    }
                }
            }
        }
    }
    if (generalNames.size() > 0) {
        return new GeneralNames(new DERSequence(generalNames.toArray(new ASN1Encodable[generalNames.size()])));
    }
    return null;
}

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());
    Enumeration e = seq.getObjects();
    int i = 1;//from  w  w w  .j  a  v a 2 s  .c o  m
    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.
 *///from  ww w  . ja  v  a  2s.c om
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.identityconnectors.racf.BouncyCastlePEUtilities.java

License:Open Source License

public String getPassword(byte[] envelope) {
    ASN1InputStream aIn = null;/*  w w w.  ja  va2s  .  co m*/
    try {
        aIn = new ASN1InputStream(envelope);
        Object o = null;
        DEROctetString oString = null;

        while ((o = aIn.readObject()) != null) {
            if (o instanceof DERSequence) {

                // identifier (1.2.840.113549.1.7.1)
                DERSequence seq = (DERSequence) o;
                if (seq.size() >= 2 && seq.getObjectAt(0) instanceof DERObjectIdentifier
                        && "1.2.840.113549.1.7.1".equals(((DERObjectIdentifier) seq.getObjectAt(0)).getId())) {

                    if (seq.getObjectAt(1) instanceof DERTaggedObject
                            && ((DERTaggedObject) seq.getObjectAt(1)).getObject() instanceof DEROctetString) {

                        oString = (DEROctetString) ((DERTaggedObject) seq.getObjectAt(1)).getObject();
                        break;
                    }
                }
            }
        }
        aIn.close();
        aIn = null;
        String pw = null;
        if (oString != null) {
            aIn = new ASN1InputStream(oString.getOctets());
            DERSequence seq = (DERSequence) aIn.readObject();
            if (seq.getObjectAt(2) instanceof DERUTF8String) {
                pw = ((DERUTF8String) seq.getObjectAt(2)).getString();
            }
            aIn.close();
            aIn = null;
        }
        return pw;
    } catch (IOException e) {
        try {
            if (aIn != null)
                aIn.close();
        } catch (IOException e2) {
        }
        throw ConnectorException.wrap(e);
    }
}

From source file:org.jruby.ext.openssl.x509store.BouncyCastleASN1FormatHandler.java

License:LGPL

private X509AuxCertificate readAuxCertificate(BufferedReader in, String endMarker) throws IOException {
    String line;//from  ww  w  .  j a v  a  2  s .  com
    StringBuffer buf = new StringBuffer();

    while ((line = in.readLine()) != null) {
        if (line.indexOf(endMarker) != -1) {
            break;
        }
        buf.append(line.trim());
    }

    if (line == null) {
        throw new IOException(endMarker + " not found");
    }

    ASN1InputStream try1 = new ASN1InputStream(Base64.decode(buf.toString()));
    ByteArrayInputStream bIn = new ByteArrayInputStream((try1.readObject()).getEncoded());

    try {
        CertificateFactory certFact = CertificateFactory.getInstance("X.509");
        X509Certificate bCert = (X509Certificate) certFact.generateCertificate(bIn);
        DERSequence aux = (DERSequence) try1.readObject();
        X509Aux ax = null;
        if (aux != null) {
            ax = new X509Aux();
            int ix = 0;
            if (aux.size() > ix && aux.getObjectAt(ix) instanceof DERSequence) {
                DERSequence trust = (DERSequence) aux.getObjectAt(ix++);
                for (int i = 0; i < trust.size(); i++) {
                    ax.trust.add(((DERObjectIdentifier) trust.getObjectAt(i)).getId());
                }
            }
            if (aux.size() > ix && aux.getObjectAt(ix) instanceof DERTaggedObject
                    && ((DERTaggedObject) aux.getObjectAt(ix)).getTagNo() == 0) {
                DERSequence reject = (DERSequence) ((DERTaggedObject) aux.getObjectAt(ix++)).getObject();
                for (int i = 0; i < reject.size(); i++) {
                    ax.reject.add(((DERObjectIdentifier) reject.getObjectAt(i)).getId());
                }
            }
            if (aux.size() > ix && aux.getObjectAt(ix) instanceof DERUTF8String) {
                ax.alias = ((DERUTF8String) aux.getObjectAt(ix++)).getString();
            }
            if (aux.size() > ix && aux.getObjectAt(ix) instanceof DEROctetString) {
                ax.keyid = ((DEROctetString) aux.getObjectAt(ix++)).getOctets();
            }
            if (aux.size() > ix && aux.getObjectAt(ix) instanceof DERTaggedObject
                    && ((DERTaggedObject) aux.getObjectAt(ix)).getTagNo() == 1) {
                DERSequence other = (DERSequence) ((DERTaggedObject) aux.getObjectAt(ix++)).getObject();
                for (int i = 0; i < other.size(); i++) {
                    ax.other.add((DERObject) (other.getObjectAt(i)));
                }
            }
        }
        return new X509AuxCertificate(bCert, ax);
    } catch (Exception e) {
        throw new IOException("problem parsing cert: " + e.toString());
    }
}