Example usage for org.bouncycastle.asn1 ASN1Integer getValue

List of usage examples for org.bouncycastle.asn1 ASN1Integer getValue

Introduction

In this page you can find the example usage for org.bouncycastle.asn1 ASN1Integer getValue.

Prototype

public BigInteger getValue() 

Source Link

Usage

From source file:at.asitplus.regkassen.common.util.CryptoUtil.java

License:Apache License

/**
 * Helper method to convert DER-encoded signature values (e.g. used by Java)
 * to concatenated signature values//from   www .j  av a 2 s.c  o  m
 * (as used by the JWS-standard)
 *
 * @param derEncodedSignatureValue
 *          DER-encoded signature value
 * @return concatenated signature value (as used by JWS standard)
 * @throws IOException
 */
public static byte[] convertDEREncodedSignatureToJWSConcatenated(final byte[] derEncodedSignatureValue)
        throws IOException {
    final ASN1InputStream asn1InputStream = new ASN1InputStream(derEncodedSignatureValue);
    final ASN1Primitive asn1Primitive = asn1InputStream.readObject();
    asn1InputStream.close();
    final ASN1Sequence asn1Sequence = (ASN1Sequence.getInstance(asn1Primitive));
    final ASN1Integer rASN1 = (ASN1Integer) asn1Sequence.getObjectAt(0);
    final ASN1Integer sASN1 = (ASN1Integer) asn1Sequence.getObjectAt(1);
    final X9IntegerConverter x9IntegerConverter = new X9IntegerConverter();
    final byte[] r = x9IntegerConverter.integerToBytes(rASN1.getValue(), 32);
    final byte[] s = x9IntegerConverter.integerToBytes(sASN1.getValue(), 32);

    final byte[] concatenatedSignatureValue = new byte[64];
    System.arraycopy(r, 0, concatenatedSignatureValue, 0, 32);
    System.arraycopy(s, 0, concatenatedSignatureValue, 32, 32);

    return concatenatedSignatureValue;
}

From source file:at.asitplus.regkassen.core.base.util.CryptoUtil.java

License:Apache License

/**
 * Helper method to convert DER-encoded signature values (e.g. used by Java) to concatenated signature values
 * (as used by the JWS-standard)// ww w  .j  av a 2s  . c  om
 *
 * @param derEncodedSignatureValue DER-encoded signature value
 * @return concatenated signature value (as used by JWS standard)
 * @throws IOException
 */
public static byte[] convertDEREncodedSignatureToJWSConcatenated(byte[] derEncodedSignatureValue)
        throws IOException {
    ASN1InputStream asn1InputStream = new ASN1InputStream(derEncodedSignatureValue);
    ASN1Primitive asn1Primitive = asn1InputStream.readObject();
    ASN1Sequence asn1Sequence = (ASN1Sequence.getInstance(asn1Primitive));
    ASN1Integer rASN1 = (ASN1Integer) asn1Sequence.getObjectAt(0);
    ASN1Integer sASN1 = (ASN1Integer) asn1Sequence.getObjectAt(1);
    X9IntegerConverter x9IntegerConverter = new X9IntegerConverter();
    byte[] r = x9IntegerConverter.integerToBytes(rASN1.getValue(), 32);
    byte[] s = x9IntegerConverter.integerToBytes(sASN1.getValue(), 32);

    byte[] concatenatedSignatureValue = new byte[64];
    System.arraycopy(r, 0, concatenatedSignatureValue, 0, 32);
    System.arraycopy(s, 0, concatenatedSignatureValue, 32, 32);

    return concatenatedSignatureValue;
}

From source file:ca.trustpoint.m2m.M2mCertificateFactory.java

License:Apache License

/**
 * Parses the given ASN.1 sequence and return the corresponding {@link M2mCertificate
 * M2MCertificate} object.//from  w w  w . j  av  a  2s .com
 *
 * @param seq ASN.1 sequence containing TBS data.
 * @param cert A M2MCertificate object.
 * @throw InvalidKeyException if public key is invalid.
 * @throw IOException if parsing error.
 * @throw URISyntaxException if URI field is invalid.
 */
private void parseTbsCertificate(ASN1Sequence seq, M2mCertificate cert)
        throws InvalidKeyException, IOException, URISyntaxException {
    if (seq.size() < 2) {
        throw new IOException("no enough data for TBS certificate in sequence");
    }

    // Set tbsCertificate
    for (int i = 0; i < seq.size(); i++) {
        ASN1TaggedObject obj = (ASN1TaggedObject) seq.getObjectAt(i);
        TbsCertificateFields tag = TbsCertificateFields.getInstance(obj.getTagNo());

        switch (tag) {
        case SERIAL_NUMBER:
            ASN1OctetString serialNumber = ASN1OctetString.getInstance(obj, false);
            cert.setSerialNumber(serialNumber.getOctets());
            break;
        case CA_ALGORITHM:
            ASN1ObjectIdentifier cAAlgorithm = ASN1ObjectIdentifier.getInstance(obj, false);

            if (cert.getCaKeyDefinition() == null) {
                cert.setCaKeyDefinition(new KeyAlgorithmDefinition());
            }

            cert.getCaKeyDefinition().setAlgorithm(parseKeyAlgorithmDefinitionAlgorithm(cAAlgorithm));
            break;
        case CA_ALGORITHM_PARAMETERS:
            ASN1OctetString cAAlgParams = ASN1OctetString.getInstance(obj, false);

            if (cert.getCaKeyDefinition() == null) {
                cert.setCaKeyDefinition(new KeyAlgorithmDefinition());
            }

            cert.getCaKeyDefinition().setParameters(cAAlgParams.getOctets());
            break;
        case ISSUER:
            ASN1Sequence issuerSeq = ASN1Sequence.getInstance(obj, false);
            cert.setIssuer(parseEntityName(issuerSeq));
            break;
        case VALID_FROM:
            ASN1OctetString validFrom = ASN1OctetString.getInstance(obj, false);
            BigInteger dateTimeBInt = new BigInteger(validFrom.getOctets());

            // date in sequence is second, converts to millisecond for constructing Date
            long dateTime = dateTimeBInt.longValue() * 1000;

            cert.setValidFrom(new Date(dateTime));
            break;
        case VALID_DURATION:
            ASN1OctetString validDuration = ASN1OctetString.getInstance(obj, false);
            BigInteger duration = new BigInteger(validDuration.getOctets());

            cert.setValidDuration(new Integer(duration.intValue()));
            break;
        case SUBJECT:
            ASN1Sequence subjectSeq = ASN1Sequence.getInstance(obj, false);
            cert.setSubject(parseEntityName(subjectSeq));
            break;
        case PUBLIC_KEY_ALGORITHM:
            ASN1ObjectIdentifier pKAlgorithm = ASN1ObjectIdentifier.getInstance(obj, false);

            if (cert.getPublicKeyDefinition() == null) {
                cert.setPublicKeyDefinition(new KeyAlgorithmDefinition());
            }

            cert.getPublicKeyDefinition().setAlgorithm(parseKeyAlgorithmDefinitionAlgorithm(pKAlgorithm));
            break;
        case PUBLIC_KEY_ALGORITHM_PARAMETERS:
            ASN1OctetString pKAlgParams = ASN1OctetString.getInstance(obj, false);

            if (cert.getPublicKeyDefinition() == null) {
                cert.setPublicKeyDefinition(new KeyAlgorithmDefinition());
            }

            cert.getPublicKeyDefinition().setParameters(pKAlgParams.getOctets());
            break;
        case PUBLIC_KEY:
            ASN1OctetString pubKey = ASN1OctetString.getInstance(obj, false);
            byte[] rawPublicKey = pubKey.getOctets();

            cert.setIsPublicKeyCompressed(KeyConversionUtils.isCompressedEcPoint(rawPublicKey));

            PublicKey publicKey = KeyConversionUtils.convertRawBytestoEcPublicKey(rawPublicKey);
            cert.setPublicKey(publicKey);
            break;
        case AUTHORITY_KEY_ID:
            ASN1Sequence authKeyIdSeq = ASN1Sequence.getInstance(obj, false);
            cert.setAuthorityKeyIdentifier(parseAuthorityKeyIdentifier(authKeyIdSeq));
            break;
        case SUBJECT_KEY_ID:
            ASN1OctetString subjKeyId = ASN1OctetString.getInstance(obj, false);
            cert.setSubjectKeyIdentifier(subjKeyId.getOctets());
            break;
        case KEY_USAGE:
            ASN1OctetString keyUsageObj = ASN1OctetString.getInstance(obj, false);
            KeyUsage keyUsage = new KeyUsage(keyUsageObj.getEncoded());
            cert.setKeyUsage(keyUsage);
            break;
        case BASIC_CONSTRAINTS:
            ASN1Integer basicConstraints = ASN1Integer.getInstance(obj, false);
            cert.setBasicConstraints(basicConstraints.getValue().intValue());
            break;
        case CERTIFICATE_POLICY:
            ASN1ObjectIdentifier certPolicy = ASN1ObjectIdentifier.getInstance(obj, false);
            cert.setCertificatePolicy(certPolicy.getId());
            break;
        case SUBJECT_ALTERNATE_NAME:
            ASN1TaggedObject subjectAltNameObj = ASN1TaggedObject.getInstance(obj, true);
            cert.setSubjectAlternativeName(parseGeneralName(subjectAltNameObj));
            break;
        case ISSUER_ALTERNATE_NAME:
            ASN1TaggedObject issuerAltNameObj = ASN1TaggedObject.getInstance(obj, true);
            cert.setIssuerAlternativeName(parseGeneralName(issuerAltNameObj));
            break;
        case EXTENDED_KEY_USAGE:
            ASN1ObjectIdentifier extendedKeyUsage = ASN1ObjectIdentifier.getInstance(obj, false);
            cert.setExtendedKeyUsage(extendedKeyUsage.getId());
            break;
        case AUTHENTICATION_INFO_ACCESS_OCSP:
            DERIA5String authInfoAccessOCSPObj = DERIA5String.getInstance(obj, false);
            URI authInfoAccessOCSP = new URI(authInfoAccessOCSPObj.getString());
            cert.setAuthenticationInfoAccessOcsp(authInfoAccessOCSP);
            break;
        case CRL_DISTRIBUTION_POINT_URI:
            DERIA5String cRLDistribPointURIObj = DERIA5String.getInstance(obj, false);
            URI cRLDistribPointURI = new URI(cRLDistribPointURIObj.getString());
            cert.setCrlDistributionPointUri(cRLDistribPointURI);
            break;
        case EXTENSIONS:
            ASN1Sequence x509extensionsSeq = ASN1Sequence.getInstance(obj, false);
            parseX509extensions(x509extensionsSeq, cert);
            break;
        default:
            throw new IOException("unknow TBS certificate field number: " + tag.getTagNumber());
        }
    }
}

From source file:com.guardtime.asn1.Accuracy.java

License:Apache License

/**
 * Class constructor.//w w  w .  j a va  2s . c  om
 *
 * @param obj ASN.1 representation of the timestamp accuracy.
 *
 * @throws Asn1FormatException if provided ASN.1 object has invalid format.
 */
Accuracy(ASN1Encodable obj) throws Asn1FormatException {
    try {
        accuracy = org.bouncycastle.asn1.tsp.Accuracy.getInstance(obj);

        ASN1Integer sec = accuracy.getSeconds();
        if (sec == null) {
            seconds = null;
        } else {
            int n = sec.getValue().intValue();
            if (n < 0) {
                throw new Asn1FormatException("invalid seconds value: " + n);
            }
            seconds = new Integer(n);
        }

        ASN1Integer mls = accuracy.getMillis();
        if (mls == null) {
            millis = null;
        } else {
            int n = mls.getValue().intValue();
            if (n < 1 || n > 999) {
                throw new Asn1FormatException("invalid millis value: " + n);
            }
            millis = new Integer(n);
        }

        ASN1Integer mcs = accuracy.getMicros();
        if (mcs == null) {
            micros = null;
        } else {
            int n = mcs.getValue().intValue();
            if (n < 1 || n > 999) {
                throw new Asn1FormatException("invalid micros value: " + n);
            }
            micros = new Integer(n);
        }
    } catch (Asn1FormatException e) {
        throw e;
    } catch (Exception e) {
        throw new Asn1FormatException("accuracy has invalid format", e);
    }
}

From source file:com.guardtime.asn1.TstInfo.java

License:Apache License

/**
 * Class constructor./*from  w  w w .jav a 2  s. co m*/
 *
 * @param obj ASN.1 representation of TST info.
 *
 * @throws Asn1FormatException if provided ASN.1 object has invalid format.
 */
TstInfo(ASN1Encodable obj) throws Asn1FormatException {
    try {
        tstInfo = TSTInfo.getInstance(obj);

        // Extract and check version
        BigInteger ver = tstInfo.getVersion().getValue();
        if (!ver.equals(BigInteger.valueOf(VERSION))) {
            throw new Asn1FormatException("invalid TST info version: " + ver);
        }
        version = ver.intValue();

        // Extract policy
        policy = tstInfo.getPolicy().getId();

        // Extract message imprint
        messageImprint = new MessageImprint(tstInfo.getMessageImprint().toASN1Primitive());

        // Extract serial number
        //
        // As `DERInteger` can be constructed out of `ASN1OctetString`
        // without any error, here we have no option to determine
        // if the serial number is actually an INTEGER or OCTET STRING.
        //
        // Possible solutions is to rewrite BouncyCastle `TSTInfo` class
        // adding more strict checks.
        serialNumber = tstInfo.getSerialNumber().getValue();

        // Extract request time
        //
        // Current BouncyCastle implementation can parse the time string
        // that does not omit trailing zeros in second fraction part.
        // RFC 3161 requires that such time string is labeled invalid.
        genTime = tstInfo.getGenTime().getDate();

        // Extract optional fields

        ASN1Encodable acc = tstInfo.getAccuracy();
        accuracy = ((acc == null) ? null : new Accuracy(acc.toASN1Primitive()));

        ASN1Boolean ord = tstInfo.getOrdering();
        ordering = (ord != null && ord.isTrue());

        ASN1Integer nnc = tstInfo.getNonce();
        nonce = ((nnc == null) ? null : nnc.getValue());

        GeneralName tsaName = tstInfo.getTsa();
        tsa = ((tsaName == null) ? null : tsaName.toString());

        Extensions exts = tstInfo.getExtensions();
        if (exts != null) {
            // check for critical extensions
            Asn1Util.checkExtensions(exts);
            extensions = exts.getEncoded(ASN1Encoding.DER);
        }
    } catch (Asn1FormatException e) {
        throw e;
    } catch (Exception e) {
        throw new Asn1FormatException("TST info has invalid format", e);
    }
}

From source file:de.carne.certmgr.store.provider.bouncycastle.BouncyCastleStoreProvider.java

License:Open Source License

@Override
public X509CRL generateAndSignCRL(X509CRL currentCRL, X509CRLParams crlParams,
        Map<BigInteger, RevokeReason> revokeSerials, KeyPair issuerKey, X509Certificate issuerCRT)
        throws IOException, GeneralSecurityException {
    Date lastUpdate = Date
            .from(crlParams.getLastUpdate().atStartOfDay().atZone(ZoneId.systemDefault()).toInstant());
    JcaX509v2CRLBuilder crlBuilder = new JcaX509v2CRLBuilder(issuerCRT.getSubjectX500Principal(), lastUpdate);
    LocalDate nextUpdateParam = crlParams.getNextUpdate();

    if (nextUpdateParam != null) {
        crlBuilder.setNextUpdate(/*from w  ww  .  ja v a 2 s  .c  om*/
                Date.from(nextUpdateParam.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant()));
    }

    CRLNumber crlNumber;

    if (currentCRL != null) {
        X509CRLHolder crlHolder = new X509CRLHolder(currentCRL.getEncoded());
        ASN1Integer currentSerial = (ASN1Integer) crlHolder.getExtension(Extension.cRLNumber).getParsedValue();

        crlNumber = new CRLNumber(currentSerial.getValue().add(BigInteger.ONE));
    } else {
        crlNumber = new CRLNumber(BigInteger.ONE);
    }
    for (Map.Entry<BigInteger, RevokeReason> revokeListEntry : revokeSerials.entrySet()) {
        crlBuilder.addCRLEntry(revokeListEntry.getKey(), lastUpdate, revokeListEntry.getValue().value());
    }

    JcaX509ExtensionUtils extensionUtils = new JcaX509ExtensionUtils();

    crlBuilder.addExtension(Extension.authorityKeyIdentifier, false,
            extensionUtils.createAuthorityKeyIdentifier(issuerCRT.getPublicKey()));
    crlBuilder.addExtension(Extension.cRLNumber, false, crlNumber);

    ContentSigner crlSigner;

    try {
        crlSigner = new JcaContentSignerBuilder(crlParams.getSigAlg()).build(issuerKey.getPrivate());
    } catch (OperatorCreationException e) {
        throw new StoreProviderException(e.getMessage(), e);
    }
    return new JcaX509CRLConverter().getCRL(crlBuilder.build(crlSigner));
}

From source file:de.fraunhofer.fokus.openeid.ta.TerminalAuthenticationInfoProtocol.java

License:Open Source License

/**
 * convert signature from asn1 mode (default ECDSA) to plain mode (no asn1)
 * refert to://  w  w w  .j a  v a  2  s  .  c o  m
 * D.2.1.4 ECDSA Plain Signature
 * According to [3] ECDSA signatures in plain format are specified as 
  * direct concatenation of two octet 
  * strings R||S. For ECDSA-224, each octet string has length 28 (decimal).
  * R    1DAF7AA1 98B948A6 DFB626BD DDAD3C03 43ABD1F1 049C4CA1 B09821C7
  * S    7A5A3BBB 18A5D2F6 D9AF0A24 63B4C137 287BAFF1 9DB8684C 1441989F
 * @param signature in asn1 mode
 * @return signature in plain mode
 */
public static byte[] convertToPlainMode(byte[] signature) {
    try {

        ASN1Sequence sequence = (ASN1Sequence) DERSequence.fromByteArray(signature);

        DEREncodable rObject = sequence.getObjectAt(0);
        DEREncodable sObject = sequence.getObjectAt(1);
        byte[] rValue;
        byte[] sValue;
        if (rObject instanceof ASN1Integer) {
            ASN1Integer r = (ASN1Integer) rObject;
            ASN1Integer s = (ASN1Integer) sObject;
            rValue = r.getValue().toByteArray();
            sValue = s.getValue().toByteArray();
        } else {
            DERInteger r = (DERInteger) rObject;
            DERInteger s = (DERInteger) sObject;
            rValue = r.getValue().toByteArray();
            sValue = s.getValue().toByteArray();
        }
        byte[] r_part = removeLeadingZero(rValue);
        byte[] l_part = removeLeadingZero(sValue);
        return Utils.concat(r_part, l_part);
    } catch (IOException e) {
        return signature;
    }

}

From source file:es.gob.afirma.signers.pkcs7.ReadNodesTree.java

License:Open Source License

/** M&eacute;todo que, apartir de un numero de serie de un certificado,
 * devuelve su nombre com&uacute;n (CN). De no existir el CN,
 * devolver&aacute; el nombre de la unidad organizativa.
 * @param certificates/*  w  w  w  . ja v  a  2  s.c o m*/
 *        Certificados de los firmantes.
 * @param serialNumber
 *        N&uacute;mero de serie del certificado a firmar.
 * @return El nombre com&uacute;n. */
private static String searchName(final ASN1Set certificates, final ASN1Integer serialNumber) {
    final Enumeration<?> certSet = certificates.getObjects();
    while (certSet.hasMoreElements()) {
        final X509Certificate c;
        try {
            c = (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate( //$NON-NLS-1$
                    new ByteArrayInputStream(((ASN1Sequence) certSet.nextElement()).getEncoded()));
        } catch (final Exception e) {
            LOGGER.severe(
                    "Error extrayendo los certificados del Set ASN.1, puede que se haya omitido un elemento valido" //$NON-NLS-1$
                            + e);
            continue;
        }
        if (c.getSerialNumber().equals(serialNumber.getValue())) {
            return AOUtil.getCN(c);
        }
    }
    LOGGER.info("No se ha encontrado el certificado indicado, se devolvera una cadena vacia"); //$NON-NLS-1$
    return ""; //$NON-NLS-1$
}

From source file:es.gob.afirma.signers.pkcs7.ReadNodesTree.java

License:Open Source License

/** A partir de un numero de serie de un certificado, devuelve un array con
 * el certificado y su cadena de confianza.
 * @param certificates/*www  .  j  a  v  a2 s .c om*/
 *        Certificados de los firmantes.
 * @param serialNumber
 *        N&uacute;mero de serie del certificado a firmar.
 * @return El certificado (en la posici&oacute;n 0 y su cadena de confianza
 *         en orden). */
private static X509Certificate[] searchCert(final ASN1Set certificates, final ASN1Integer serialNumber) {
    final Enumeration<?> certSet = certificates.getObjects();
    while (certSet.hasMoreElements()) {
        final X509Certificate c;
        try {
            c = (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate( //$NON-NLS-1$
                    new ByteArrayInputStream(((ASN1Sequence) certSet.nextElement()).getEncoded()));
        } catch (final Exception e) {
            LOGGER.severe(
                    "Error extrayendo los certificados del Set ASN.1, puede que se haya omitido un elemento valido" //$NON-NLS-1$
                            + e);
            continue;
        }
        if (c.getSerialNumber().equals(serialNumber.getValue())) {
            return new X509Certificate[] { c };
        }
    }
    LOGGER.severe("El certificados pedido no estaba en la lista, se devolvera un array vacio"); //$NON-NLS-1$
    return new X509Certificate[0];
}

From source file:eu.emi.security.authn.x509.helpers.pkipath.bc.FixedBCPKIXCertPathReviewer.java

License:Open Source License

private void checkPolicy() {
    ///*from  ww w .j av  a2s.c om*/
    // 6.1.1 Inputs
    //

    // c) Initial Policy Set

    Set userInitialPolicySet = pkixParams.getInitialPolicies();

    // e) f) g) are part of pkixParams

    //
    // 6.1.2 Initialization
    //

    // a) valid policy tree

    List[] policyNodes = new ArrayList[n + 1];
    for (int j = 0; j < policyNodes.length; j++) {
        policyNodes[j] = new ArrayList();
    }

    Set policySet = new HashSet();

    policySet.add(ANY_POLICY);

    PKIXPolicyNode validPolicyTree = new PKIXPolicyNode(new ArrayList(), 0, policySet, null, new HashSet(),
            ANY_POLICY, false);

    policyNodes[0].add(validPolicyTree);

    // d) explicit policy

    int explicitPolicy;
    if (pkixParams.isExplicitPolicyRequired()) {
        explicitPolicy = 0;
    } else {
        explicitPolicy = n + 1;
    }

    // e) inhibit any policy

    int inhibitAnyPolicy;
    if (pkixParams.isAnyPolicyInhibited()) {
        inhibitAnyPolicy = 0;
    } else {
        inhibitAnyPolicy = n + 1;
    }

    // f) policy mapping

    int policyMapping;
    if (pkixParams.isPolicyMappingInhibited()) {
        policyMapping = 0;
    } else {
        policyMapping = n + 1;
    }

    Set acceptablePolicies = null;

    //
    // 6.1.3 Basic Certificate processing
    //

    X509Certificate cert = null;
    int index;
    int i;

    try {
        for (index = certs.size() - 1; index >= 0; index--) {
            // i as defined in the algorithm description
            i = n - index;

            // set certificate to be checked in this round
            cert = (X509Certificate) certs.get(index);

            // d) process policy information

            ASN1Sequence certPolicies;
            try {
                certPolicies = (ASN1Sequence) getExtensionValue(cert, CERTIFICATE_POLICIES);
            } catch (AnnotatedException ae) {
                ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.policyExtError");
                throw new CertPathReviewerException(msg, ae, certPath, index);
            }
            if (certPolicies != null && validPolicyTree != null) {

                // d) 1)

                Enumeration e = certPolicies.getObjects();
                Set pols = new HashSet();

                while (e.hasMoreElements()) {
                    PolicyInformation pInfo = PolicyInformation.getInstance(e.nextElement());
                    ASN1ObjectIdentifier pOid = pInfo.getPolicyIdentifier();

                    pols.add(pOid.getId());

                    if (!ANY_POLICY.equals(pOid.getId())) {
                        Set pq;
                        try {
                            pq = getQualifierSet(pInfo.getPolicyQualifiers());
                        } catch (CertPathValidatorException cpve) {
                            ErrorBundle msg = new ErrorBundle(RESOURCE_NAME,
                                    "CertPathReviewer.policyQualifierError");
                            throw new CertPathReviewerException(msg, cpve, certPath, index);
                        }

                        boolean match = processCertD1i(i, policyNodes, pOid, pq);

                        if (!match) {
                            processCertD1ii(i, policyNodes, pOid, pq);
                        }
                    }
                }

                if (acceptablePolicies == null || acceptablePolicies.contains(ANY_POLICY)) {
                    acceptablePolicies = pols;
                } else {
                    Iterator it = acceptablePolicies.iterator();
                    Set t1 = new HashSet();

                    while (it.hasNext()) {
                        Object o = it.next();

                        if (pols.contains(o)) {
                            t1.add(o);
                        }
                    }

                    acceptablePolicies = t1;
                }

                // d) 2)

                if ((inhibitAnyPolicy > 0) || ((i < n) && isSelfIssued(cert))) {
                    e = certPolicies.getObjects();

                    while (e.hasMoreElements()) {
                        PolicyInformation pInfo = PolicyInformation.getInstance(e.nextElement());

                        if (ANY_POLICY.equals(pInfo.getPolicyIdentifier().getId())) {
                            Set _apq;
                            try {
                                _apq = getQualifierSet(pInfo.getPolicyQualifiers());
                            } catch (CertPathValidatorException cpve) {
                                ErrorBundle msg = new ErrorBundle(RESOURCE_NAME,
                                        "CertPathReviewer.policyQualifierError");
                                throw new CertPathReviewerException(msg, cpve, certPath, index);
                            }
                            List _nodes = policyNodes[i - 1];

                            for (int k = 0; k < _nodes.size(); k++) {
                                PKIXPolicyNode _node = (PKIXPolicyNode) _nodes.get(k);

                                Iterator _policySetIter = _node.getExpectedPolicies().iterator();
                                while (_policySetIter.hasNext()) {
                                    Object _tmp = _policySetIter.next();

                                    String _policy;
                                    if (_tmp instanceof String) {
                                        _policy = (String) _tmp;
                                    } else if (_tmp instanceof ASN1ObjectIdentifier) {
                                        _policy = ((ASN1ObjectIdentifier) _tmp).getId();
                                    } else {
                                        continue;
                                    }

                                    boolean _found = false;
                                    Iterator _childrenIter = _node.getChildren();

                                    while (_childrenIter.hasNext()) {
                                        PKIXPolicyNode _child = (PKIXPolicyNode) _childrenIter.next();

                                        if (_policy.equals(_child.getValidPolicy())) {
                                            _found = true;
                                        }
                                    }

                                    if (!_found) {
                                        Set _newChildExpectedPolicies = new HashSet();
                                        _newChildExpectedPolicies.add(_policy);

                                        PKIXPolicyNode _newChild = new PKIXPolicyNode(new ArrayList(), i,
                                                _newChildExpectedPolicies, _node, _apq, _policy, false);
                                        _node.addChild(_newChild);
                                        policyNodes[i].add(_newChild);
                                    }
                                }
                            }
                            break;
                        }
                    }
                }

                //
                // (d) (3)
                //
                for (int j = (i - 1); j >= 0; j--) {
                    List nodes = policyNodes[j];

                    for (int k = 0; k < nodes.size(); k++) {
                        PKIXPolicyNode node = (PKIXPolicyNode) nodes.get(k);
                        if (!node.hasChildren()) {
                            validPolicyTree = removePolicyNode(validPolicyTree, policyNodes, node);
                            if (validPolicyTree == null) {
                                break;
                            }
                        }
                    }
                }

                //
                // d (4)
                //
                Set criticalExtensionOids = cert.getCriticalExtensionOIDs();

                if (criticalExtensionOids != null) {
                    boolean critical = criticalExtensionOids.contains(CERTIFICATE_POLICIES);

                    List nodes = policyNodes[i];
                    for (int j = 0; j < nodes.size(); j++) {
                        PKIXPolicyNode node = (PKIXPolicyNode) nodes.get(j);
                        node.setCritical(critical);
                    }
                }

            }

            // e)

            if (certPolicies == null) {
                validPolicyTree = null;
            }

            // f)

            if (explicitPolicy <= 0 && validPolicyTree == null) {
                ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.noValidPolicyTree");
                throw new CertPathReviewerException(msg);
            }

            //
            // 6.1.4 preparation for next Certificate
            //

            if (i != n) {

                // a)

                ASN1Primitive pm;
                try {
                    pm = getExtensionValue(cert, POLICY_MAPPINGS);
                } catch (AnnotatedException ae) {
                    ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.policyMapExtError");
                    throw new CertPathReviewerException(msg, ae, certPath, index);
                }

                if (pm != null) {
                    ASN1Sequence mappings = (ASN1Sequence) pm;
                    for (int j = 0; j < mappings.size(); j++) {
                        ASN1Sequence mapping = (ASN1Sequence) mappings.getObjectAt(j);
                        ASN1ObjectIdentifier ip_id = (ASN1ObjectIdentifier) mapping.getObjectAt(0);
                        ASN1ObjectIdentifier sp_id = (ASN1ObjectIdentifier) mapping.getObjectAt(1);
                        if (ANY_POLICY.equals(ip_id.getId())) {
                            ErrorBundle msg = new ErrorBundle(RESOURCE_NAME,
                                    "CertPathReviewer.invalidPolicyMapping");
                            throw new CertPathReviewerException(msg, certPath, index);
                        }
                        if (ANY_POLICY.equals(sp_id.getId())) {
                            ErrorBundle msg = new ErrorBundle(RESOURCE_NAME,
                                    "CertPathReviewer.invalidPolicyMapping");
                            throw new CertPathReviewerException(msg, certPath, index);
                        }
                    }
                }

                // b)

                if (pm != null) {
                    ASN1Sequence mappings = (ASN1Sequence) pm;
                    Map m_idp = new HashMap();
                    Set s_idp = new HashSet();

                    for (int j = 0; j < mappings.size(); j++) {
                        ASN1Sequence mapping = (ASN1Sequence) mappings.getObjectAt(j);
                        String id_p = ((ASN1ObjectIdentifier) mapping.getObjectAt(0)).getId();
                        String sd_p = ((ASN1ObjectIdentifier) mapping.getObjectAt(1)).getId();
                        Set tmp;

                        if (!m_idp.containsKey(id_p)) {
                            tmp = new HashSet();
                            tmp.add(sd_p);
                            m_idp.put(id_p, tmp);
                            s_idp.add(id_p);
                        } else {
                            tmp = (Set) m_idp.get(id_p);
                            tmp.add(sd_p);
                        }
                    }

                    Iterator it_idp = s_idp.iterator();
                    while (it_idp.hasNext()) {
                        String id_p = (String) it_idp.next();

                        //
                        // (1)
                        //
                        if (policyMapping > 0) {
                            try {
                                prepareNextCertB1(i, policyNodes, id_p, m_idp, cert);
                            } catch (AnnotatedException ae) {
                                // error processing certificate policies extension
                                ErrorBundle msg = new ErrorBundle(RESOURCE_NAME,
                                        "CertPathReviewer.policyExtError");
                                throw new CertPathReviewerException(msg, ae, certPath, index);
                            } catch (CertPathValidatorException cpve) {
                                // error building qualifier set
                                ErrorBundle msg = new ErrorBundle(RESOURCE_NAME,
                                        "CertPathReviewer.policyQualifierError");
                                throw new CertPathReviewerException(msg, cpve, certPath, index);
                            }

                            //
                            // (2)
                            // 
                        } else if (policyMapping <= 0) {
                            validPolicyTree = prepareNextCertB2(i, policyNodes, id_p, validPolicyTree);
                        }

                    }
                }

                //
                // h)
                //

                if (!isSelfIssued(cert)) {

                    // (1)
                    if (explicitPolicy != 0) {
                        explicitPolicy--;
                    }

                    // (2)
                    if (policyMapping != 0) {
                        policyMapping--;
                    }

                    // (3)
                    if (inhibitAnyPolicy != 0) {
                        inhibitAnyPolicy--;
                    }

                }

                //
                // i)
                //

                try {
                    ASN1Sequence pc = (ASN1Sequence) getExtensionValue(cert, POLICY_CONSTRAINTS);
                    if (pc != null) {
                        Enumeration policyConstraints = pc.getObjects();

                        while (policyConstraints.hasMoreElements()) {
                            ASN1TaggedObject constraint = (ASN1TaggedObject) policyConstraints.nextElement();
                            int tmpInt;

                            switch (constraint.getTagNo()) {
                            case 0:
                                tmpInt = ASN1Integer.getInstance(constraint, false).getValue().intValue();
                                if (tmpInt < explicitPolicy) {
                                    explicitPolicy = tmpInt;
                                }
                                break;
                            case 1:
                                tmpInt = ASN1Integer.getInstance(constraint, false).getValue().intValue();
                                if (tmpInt < policyMapping) {
                                    policyMapping = tmpInt;
                                }
                                break;
                            }
                        }
                    }
                } catch (AnnotatedException ae) {
                    ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.policyConstExtError");
                    throw new CertPathReviewerException(msg, certPath, index);
                }

                //
                // j)
                //

                try {
                    ASN1Integer iap = (ASN1Integer) getExtensionValue(cert, INHIBIT_ANY_POLICY);

                    if (iap != null) {
                        int _inhibitAnyPolicy = iap.getValue().intValue();

                        if (_inhibitAnyPolicy < inhibitAnyPolicy) {
                            inhibitAnyPolicy = _inhibitAnyPolicy;
                        }
                    }
                } catch (AnnotatedException ae) {
                    ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.policyInhibitExtError");
                    throw new CertPathReviewerException(msg, certPath, index);
                }
            }

        }

        //
        // 6.1.5 Wrap up
        //

        //
        // a)
        //

        if (!isSelfIssued(cert) && explicitPolicy > 0) {
            explicitPolicy--;
        }

        //
        // b)
        //

        try {
            ASN1Sequence pc = (ASN1Sequence) getExtensionValue(cert, POLICY_CONSTRAINTS);
            if (pc != null) {
                Enumeration policyConstraints = pc.getObjects();

                while (policyConstraints.hasMoreElements()) {
                    ASN1TaggedObject constraint = (ASN1TaggedObject) policyConstraints.nextElement();
                    switch (constraint.getTagNo()) {
                    case 0:
                        int tmpInt = ASN1Integer.getInstance(constraint, false).getValue().intValue();
                        if (tmpInt == 0) {
                            explicitPolicy = 0;
                        }
                        break;
                    }
                }
            }
        } catch (AnnotatedException e) {
            ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.policyConstExtError");
            throw new CertPathReviewerException(msg, certPath, index);
        }

        //
        // (g)
        //
        PKIXPolicyNode intersection;

        //
        // (g) (i)
        //
        if (validPolicyTree == null) {
            if (pkixParams.isExplicitPolicyRequired()) {
                ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.explicitPolicy");
                throw new CertPathReviewerException(msg, certPath, index);
            }
            intersection = null;
        } else if (isAnyPolicy(userInitialPolicySet)) // (g) (ii)
        {
            if (pkixParams.isExplicitPolicyRequired()) {
                if (acceptablePolicies.isEmpty()) {
                    ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.explicitPolicy");
                    throw new CertPathReviewerException(msg, certPath, index);
                } else {
                    Set _validPolicyNodeSet = new HashSet();

                    for (int j = 0; j < policyNodes.length; j++) {
                        List _nodeDepth = policyNodes[j];

                        for (int k = 0; k < _nodeDepth.size(); k++) {
                            PKIXPolicyNode _node = (PKIXPolicyNode) _nodeDepth.get(k);

                            if (ANY_POLICY.equals(_node.getValidPolicy())) {
                                Iterator _iter = _node.getChildren();
                                while (_iter.hasNext()) {
                                    _validPolicyNodeSet.add(_iter.next());
                                }
                            }
                        }
                    }

                    Iterator _vpnsIter = _validPolicyNodeSet.iterator();
                    while (_vpnsIter.hasNext()) {
                        PKIXPolicyNode _node = (PKIXPolicyNode) _vpnsIter.next();
                        String _validPolicy = _node.getValidPolicy();

                        if (!acceptablePolicies.contains(_validPolicy)) {
                            //validPolicyTree = removePolicyNode(validPolicyTree, policyNodes, _node);
                        }
                    }
                    if (validPolicyTree != null) {
                        for (int j = (n - 1); j >= 0; j--) {
                            List nodes = policyNodes[j];

                            for (int k = 0; k < nodes.size(); k++) {
                                PKIXPolicyNode node = (PKIXPolicyNode) nodes.get(k);
                                if (!node.hasChildren()) {
                                    validPolicyTree = removePolicyNode(validPolicyTree, policyNodes, node);
                                }
                            }
                        }
                    }
                }
            }

            intersection = validPolicyTree;
        } else {
            //
            // (g) (iii)
            //
            // This implementation is not exactly same as the one described in RFC3280.
            // However, as far as the validation result is concerned, both produce 
            // adequate result. The only difference is whether AnyPolicy is remain 
            // in the policy tree or not. 
            //
            // (g) (iii) 1
            //
            Set _validPolicyNodeSet = new HashSet();

            for (int j = 0; j < policyNodes.length; j++) {
                List _nodeDepth = policyNodes[j];

                for (int k = 0; k < _nodeDepth.size(); k++) {
                    PKIXPolicyNode _node = (PKIXPolicyNode) _nodeDepth.get(k);

                    if (ANY_POLICY.equals(_node.getValidPolicy())) {
                        Iterator _iter = _node.getChildren();
                        while (_iter.hasNext()) {
                            PKIXPolicyNode _c_node = (PKIXPolicyNode) _iter.next();
                            if (!ANY_POLICY.equals(_c_node.getValidPolicy())) {
                                _validPolicyNodeSet.add(_c_node);
                            }
                        }
                    }
                }
            }

            //
            // (g) (iii) 2
            //
            Iterator _vpnsIter = _validPolicyNodeSet.iterator();
            while (_vpnsIter.hasNext()) {
                PKIXPolicyNode _node = (PKIXPolicyNode) _vpnsIter.next();
                String _validPolicy = _node.getValidPolicy();

                if (!userInitialPolicySet.contains(_validPolicy)) {
                    validPolicyTree = removePolicyNode(validPolicyTree, policyNodes, _node);
                }
            }

            //
            // (g) (iii) 4
            //
            if (validPolicyTree != null) {
                for (int j = (n - 1); j >= 0; j--) {
                    List nodes = policyNodes[j];

                    for (int k = 0; k < nodes.size(); k++) {
                        PKIXPolicyNode node = (PKIXPolicyNode) nodes.get(k);
                        if (!node.hasChildren()) {
                            validPolicyTree = removePolicyNode(validPolicyTree, policyNodes, node);
                        }
                    }
                }
            }

            intersection = validPolicyTree;
        }

        if ((explicitPolicy <= 0) && (intersection == null)) {
            ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.invalidPolicy");
            throw new CertPathReviewerException(msg);
        }

        validPolicyTree = intersection;
    } catch (CertPathReviewerException cpre) {
        addError(cpre.getErrorMessage(), cpre.getIndex());
        validPolicyTree = null;
    }
}