Example usage for org.bouncycastle.asn1 DERSequence getObjectAt

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

Introduction

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

Prototype

public ASN1Encodable getObjectAt(int index) 

Source Link

Document

Return the object at the sequence position indicated by index.

Usage

From source file:eu.europa.ec.markt.dss.validation.tsl.QcStatementCondition.java

License:Open Source License

@SuppressWarnings("deprecation")
@Override/*w  w  w.j  a  va  2s . co  m*/
public boolean check(CertificateAndContext cert) {
    byte[] qcStatement = cert.getCertificate().getExtensionValue(X509Extensions.QCStatements.getId());
    if (qcStatement != null) {
        try {
            ASN1InputStream input = new ASN1InputStream(qcStatement);
            DEROctetString s = (DEROctetString) input.readObject();
            byte[] content = s.getOctets();
            input = new ASN1InputStream(content);
            DERSequence seq = (DERSequence) input.readObject();
            /* Sequence of QCStatment */
            for (int i = 0; i < seq.size(); i++) {
                QCStatement statement = QCStatement.getInstance(seq.getObjectAt(i));
                if (statement.getStatementId().getId().equals(qcStatementId)) {
                    return true;
                }
            }
            return false;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    return false;
}

From source file:me.it_result.ca.bouncycastle.Utils.java

License:Open Source License

public static String extractProfileId(ASN1Set csrAttributes, String defaultProfileId) {
    String profileId = null;//from w w w .j av a2s . co  m
    try {
        Enumeration<?> attrEnum = csrAttributes.getObjects();
        while (attrEnum.hasMoreElements()) {
            DERSequence attr = (DERSequence) attrEnum.nextElement();
            if (attr.getObjectAt(0).equals(PROFILE_ID_ATTR)) {
                ASN1Set profileIdSet = (ASN1Set) attr.getObjectAt(1);
                DERPrintableString profileIdValue = (DERPrintableString) profileIdSet.getObjectAt(0);
                profileId = profileIdValue.getString();
                break;
            }
        }
    } catch (Exception e) {
    }
    if (profileId == null)
        profileId = defaultProfileId;
    return profileId;
}

From source file:me.it_result.ca.bouncycastle.Utils.java

License:Open Source License

public static String extractChallengePassword(ASN1Set csrAttributes) {
    String challengePassword = null;
    try {/*from  w  w w. j a  va 2  s.  com*/
        Enumeration<?> attrEnum = csrAttributes.getObjects();
        while (attrEnum.hasMoreElements()) {
            DERSequence attr = (DERSequence) attrEnum.nextElement();
            if (attr.getObjectAt(0).equals(PKCSObjectIdentifiers.pkcs_9_at_challengePassword)) {
                ASN1Set passwordSet = (ASN1Set) attr.getObjectAt(1);
                DERPrintableString passwordValue = (DERPrintableString) passwordSet.getObjectAt(0);
                challengePassword = passwordValue.getString();
                break;
            }
        }
    } catch (Exception e) {
    }
    return challengePassword;
}

From source file:nl.uva.vlet.grid.voms.VOMSAttributeCertificate.java

License:Apache License

private String DERSequencetoDN(DERSequence this_sequence) throws Exception {
    String thisDN = "";

    try {//w w w  .ja va 2s. c  o  m

        for (Enumeration n = this_sequence.getObjects(); n.hasMoreElements();) {
            DERSet this_set = (DERSet) n.nextElement();
            DERSequence this_seq = (DERSequence) this_set.getObjectAt(0);
            try {
                DERPrintableString this_string = (DERPrintableString) this_seq.getObjectAt(1);
                thisDN = thisDN.concat("/" + Translate_OID.getStringFromOID("" + this_seq.getObjectAt(0)) + "="
                        + this_string.getString());
            } catch (Exception notPS) {
                // email is encoded differently?
                DERIA5String this_string = (DERIA5String) this_seq.getObjectAt(1);
                thisDN = thisDN.concat("/" + Translate_OID.getStringFromOID("" + this_seq.getObjectAt(0)) + "="
                        + this_string.getString());
            }
        }

    } catch (Exception e) {
        throw e;
    }

    return thisDN;
}

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

License:Open Source License

public synchronized X509CRLStreamWriter preScan(InputStream crlToChange, CRLEntryValidator validator)
        throws IOException {
    if (locked) {
        throw new IllegalStateException("Cannot modify a locked stream.");
    }/*  w  w w  .  ja  v a 2s .  c  om*/

    if (preScanned) {
        throw new IllegalStateException("preScan has already been run.");
    }

    X509CRLEntryStream reaperStream = null;
    ASN1InputStream asn1In = null;

    try {
        reaperStream = new X509CRLEntryStream(crlToChange);
        try {
            if (!reaperStream.hasNext()) {
                emptyCrl = true;
                preScanned = true;
                return this;
            }

            while (reaperStream.hasNext()) {
                X509CRLEntryObject entry = reaperStream.next();
                if (validator != null && validator.shouldDelete(entry)) {
                    deletedEntries.add(entry.getSerialNumber());
                    deletedEntriesLength += entry.getEncoded().length;
                }
            }
        } catch (CRLException e) {
            throw new IOException("Could not read CRL entry", e);
        }

        /* At this point, crlToChange is at the point where the crlExtensions would
         * be.  RFC 5280 says that "Conforming CRL issuers are REQUIRED to include
         * the authority key identifier (Section 5.2.1) and the CRL number (Section 5.2.3)
         * extensions in all CRLs issued.
         */
        byte[] oldExtensions = null;
        DERObject o;
        asn1In = new ASN1InputStream(crlToChange);
        while ((o = asn1In.readObject()) != null) {
            if (o instanceof DERSequence) {
                // Now we are at the signatureAlgorithm
                DERSequence seq = (DERSequence) o;
                if (seq.getObjectAt(0) instanceof DERObjectIdentifier) {
                    signingAlg = new AlgorithmIdentifier(seq);
                    digestAlg = new DefaultDigestAlgorithmIdentifierFinder().find(signingAlg);

                    try {
                        // Build the signer
                        this.signer = new RSADigestSigner(createDigest(digestAlg));
                        signer.init(true,
                                new RSAKeyParameters(true, key.getModulus(), key.getPrivateExponent()));
                    } catch (CryptoException e) {
                        throw new IOException(
                                "Could not create RSADigest signer for " + digestAlg.getAlgorithm());
                    }
                }
            } else if (o instanceof DERBitString) {
                oldSigLength = o.getDEREncoded().length;
            } else {
                if (oldExtensions != null) {
                    throw new IllegalStateException("Already read in CRL extensions.");
                }
                oldExtensions = ((DERTaggedObject) o).getDEREncoded();
            }
        }

        if (oldExtensions == null) {
            /* v1 CRLs (defined in RFC 1422) don't require extensions but all new
             * CRLs should be v2 (defined in RFC 5280).  In the extremely unlikely
             * event that someone is working with a v1 CRL, we handle it here although
             * we print a warning.
             */
            preScanned = true;
            newExtensions = null;
            extensionsDelta = 0;
            log.warn("The CRL you are modifying is a version 1 CRL."
                    + " Please investigate moving to a version 2 CRL by adding the CRL Number"
                    + " and Authority Key Identifier extensions.");
            return this;
        }
        newExtensions = updateExtensions(oldExtensions);
        extensionsDelta = (newExtensions.length - oldExtensions.length)
                + findHeaderBytesDelta(oldExtensions.length, newExtensions.length);
    } finally {
        if (reaperStream != null) {
            reaperStream.close();
        }
        IOUtils.closeQuietly(asn1In);
    }
    preScanned = true;
    return this;
}

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

License:Open Source License

protected void writeToEmptyCrl(OutputStream out) throws IOException {
    ASN1InputStream asn1in = null;
    try {/*from  ww  w  . jav 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.candlepin.util.X509CRLStreamWriter.java

License:Open Source License

/**
 * This method updates the crlNumber and authorityKeyIdentifier extensions.  Any
 * other extensions are copied over unchanged.
 * @param extensions/* ww w  . java2s  .c om*/
 * @return
 * @throws IOException
 */
@SuppressWarnings("rawtypes")
protected byte[] updateExtensions(byte[] obj) throws IOException {
    DERTaggedObject taggedExts = (DERTaggedObject) DERTaggedObject.fromByteArray(obj);
    DERSequence seq = (DERSequence) taggedExts.getObject();
    ASN1EncodableVector modifiedExts = new ASN1EncodableVector();

    // Now we need to read the extensions and find the CRL number and increment it,
    // and determine if its length changed.
    Enumeration objs = seq.getObjects();
    while (objs.hasMoreElements()) {
        DERSequence ext = (DERSequence) objs.nextElement();
        DERObjectIdentifier oid = (DERObjectIdentifier) ext.getObjectAt(0);
        if (X509Extension.cRLNumber.equals(oid)) {
            DEROctetString s = (DEROctetString) ext.getObjectAt(1);
            DERInteger i = (DERInteger) DERTaggedObject.fromByteArray(s.getOctets());
            DERInteger newCrlNumber = new DERInteger(i.getValue().add(BigInteger.ONE));

            X509Extension newNumberExt = new X509Extension(false,
                    new DEROctetString(newCrlNumber.getDEREncoded()));

            ASN1EncodableVector crlNumber = new ASN1EncodableVector();
            crlNumber.add(X509Extension.cRLNumber);
            crlNumber.add(newNumberExt.getValue());
            modifiedExts.add(new DERSequence(crlNumber));
        } else if (X509Extension.authorityKeyIdentifier.equals(oid)) {
            X509Extension newAuthorityKeyExt = new X509Extension(false,
                    new DEROctetString(akiStructure.getDEREncoded()));

            ASN1EncodableVector aki = new ASN1EncodableVector();
            aki.add(X509Extension.authorityKeyIdentifier);
            aki.add(newAuthorityKeyExt.getValue());
            modifiedExts.add(new DERSequence(aki));
        } else {
            modifiedExts.add(ext);
        }
    }

    DERSequence seqOut = new DERSequence(modifiedExts);
    DERTaggedObject out = new DERTaggedObject(true, 0, seqOut);
    return out.getDEREncoded();
}

From source file:org.ccnx.ccn.impl.security.keystore.AESKeyStoreSpi.java

License:Open Source License

/**
 * Load in the key from the keystore file
 *//*  www  . jav a 2  s. c  o m*/
@Override
public void engineLoad(InputStream stream, char[] password)
        throws IOException, NoSuchAlgorithmException, CertificateException {
    if (null == stream)
        return;
    if (null != _id)
        return; // We already have the key so don't need to reload it
    ASN1InputStream ais = new ASN1InputStream(stream);
    DERSequence ds = (DERSequence) ais.readObject();
    DERInteger version = (DERInteger) ds.getObjectAt(0);
    if (version.getValue().intValue() != VERSION)
        throw new IOException("Unsupported AESKeyStore version: " + version.getValue().intValue());
    _oid = (DERObjectIdentifier) ds.getObjectAt(1);
    String keyAlgorithm = OIDLookup.getDigestName(_oid.toString());
    int aeslen = keyAlgorithmToCipherSize(keyAlgorithm);
    ASN1OctetString os = (ASN1OctetString) ds.getObjectAt(2);
    byte[] cryptoData = os.getOctets();
    int checkLength = cryptoData.length - (IV_SIZE + aeslen);
    if (checkLength <= 0)
        throw new IOException("Corrupted keystore");
    byte[] iv = new byte[IV_SIZE];
    System.arraycopy(cryptoData, 0, iv, 0, iv.length);
    Tuple<SecretKeySpec, SecretKeySpec> keys = initializeForAES(password);
    try {
        Cipher cipher = Cipher.getInstance(AES_CRYPTO_ALGORITHM);
        IvParameterSpec ivspec = new IvParameterSpec(iv);
        cipher.init(Cipher.DECRYPT_MODE, keys.first(), ivspec);
        byte[] cryptBytes = new byte[aeslen];
        System.arraycopy(cryptoData, IV_SIZE, cryptBytes, 0, cryptBytes.length);
        _id = cipher.doFinal(cryptBytes);
        byte[] checkbuf = new byte[IV_SIZE + cryptBytes.length];
        System.arraycopy(iv, 0, checkbuf, 0, IV_SIZE);
        System.arraycopy(cryptBytes, 0, checkbuf, IV_SIZE, cryptBytes.length);
        byte[] check = new byte[checkLength];
        System.arraycopy(cryptoData, IV_SIZE + aeslen, check, 0, checkLength);
        _macKeyMac.init(keys.second());
        byte[] hmac = _macKeyMac.doFinal(checkbuf);
        if (!Arrays.equals(hmac, check))
            throw new IOException("Bad signature in AES keystore");
    } catch (Exception e) {
        throw new IOException(e);
    }
}

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>();
        }//from   www  .j a v a  2  s  .  co 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 . j ava  2 s . co  m
        this.pathLenConstraints.add(objectIdentifier);
    }
}