Example usage for org.bouncycastle.asn1.x509 PolicyInformation getPolicyQualifiers

List of usage examples for org.bouncycastle.asn1.x509 PolicyInformation getPolicyQualifiers

Introduction

In this page you can find the example usage for org.bouncycastle.asn1.x509 PolicyInformation getPolicyQualifiers.

Prototype

public ASN1Sequence getPolicyQualifiers() 

Source Link

Usage

From source file:com.jlocksmith.util.ExtensionUtil.java

License:Open Source License

/**
 * Get Certificate Policies String Value
 * /*w w  w.ja va  2s .c  o  m*/
 * @param bytes
 * @return
 * @throws IOException
 */
private String getCertificatePoliciesStringValue(byte[] bytes) throws IOException {
    ASN1Sequence pSeq = (ASN1Sequence) toDERObject(bytes);
    StringBuffer sb = new StringBuffer();

    for (int i = 0, len = pSeq.size(); i < len; i++) {

        PolicyInformation pi = PolicyInformation.getInstance(pSeq.getObjectAt(i));

        sb.append(MessageFormat.format(localeUtil.getString("PolicyIdentifier"),
                new Object[] { pi.getPolicyIdentifier().getId() }));
        sb.append('\n');

        ASN1Sequence pQuals;

        if ((pQuals = pi.getPolicyQualifiers()) != null) {
            for (int j = 0, plen = pQuals.size(); j < plen; j++) {

                ASN1Sequence pqi = (ASN1Sequence) pQuals.getObjectAt(j);
                String pqId = ((DERObjectIdentifier) pqi.getObjectAt(0)).getId();

                sb.append('\t');
                sb.append(MessageFormat.format(getResource(pqId, "UnrecognisedPolicyQualifier"),
                        new Object[] { pqId }));
                sb.append('\n');

                if (pQuals.size() > 0) {

                    DEREncodable d = pqi.getObjectAt(1);

                    if (pqId.equals("1.3.6.1.5.5.7.2.1")) {
                        // cPSuri
                        sb.append("\t\t");
                        sb.append(MessageFormat.format(localeUtil.getString("CpsUri"),
                                new Object[] { ((DERString) d).getString() }));
                        sb.append('\n');
                    } else if (pqId.equals("1.3.6.1.5.5.7.2.2")) {
                        ASN1Sequence un = (ASN1Sequence) d;

                        for (int k = 0, dlen = un.size(); k < dlen; k++) {
                            DEREncodable de = un.getObjectAt(k);

                            if (de instanceof DERString) {
                                // explicitText
                                sb.append("\t\t");
                                sb.append(localeUtil.getString("ExplicitText"));
                                sb.append("\n\t\t\t");
                                sb.append(getObjectString(de));
                                sb.append('\n');
                            } else if (de instanceof ASN1Sequence) {
                                ASN1Sequence nr = (ASN1Sequence) de;

                                String orgstr = getObjectString(nr.getObjectAt(0));
                                ASN1Sequence nrs = (ASN1Sequence) nr.getObjectAt(1);

                                StringBuffer nrstr = new StringBuffer();
                                for (int m = 0, nlen = nrs.size(); m < nlen; m++) {
                                    nrstr.append(getObjectString(nrs.getObjectAt(m)));
                                    if (m != nlen - 1) {
                                        nrstr.append(", ");
                                    }
                                }
                                sb.append("\t\t");
                                sb.append(localeUtil.getString("NoticeRef"));
                                sb.append("\n\t\t\t");
                                sb.append(MessageFormat.format(localeUtil.getString("NoticeRefOrganization"),
                                        new Object[] { orgstr }));
                                sb.append("\n\t\t\t");
                                sb.append(MessageFormat.format(localeUtil.getString("NoticeRefNumber"),
                                        new Object[] { nrstr }));
                                sb.append('\n');
                            }
                        }
                    } else {
                        sb.append("\t\t");
                        sb.append(getObjectString(d));
                        sb.append('\n');
                    }
                }
            }
        }

        if (i != len) {
            sb.append('\n');
        }
    }

    return sb.toString();
}

From source file:com.otterca.common.crypto.SimplePolicyGeneratorTest.java

License:Apache License

/**
 * Test behavior when CPS is set.//from   w  w w.ja va  2s .c  om
 * 
 * @throws IOException
 */
@Test
@edu.umd.cs.findbugs.annotations.SuppressWarnings("NP_NONNULL_PARAM_VIOLATION")
public void testCpsPolicy() throws IOException {
    SimplePolicyGeneratorImpl generator = new SimplePolicyGeneratorImpl(CPS_URI, null, null, null);

    // get policy extensions
    byte[] policyBytes = generator.getExtension(SUBJECT, ISSUER);
    assertNotNull(policyBytes);

    X509Extensions exts = X509Extensions.getInstance(DLSequence.fromByteArray(policyBytes));
    ASN1Encodable asn1 = exts.getExtension(X509Extensions.CertificatePolicies).getParsedValue();
    CertificatePolicies policies = CertificatePolicies.getInstance(asn1);
    assertNotNull(policies, "unable to find CertificatePolicies extension");

    for (PolicyInformation info : policies.getPolicyInformation()) {
        if (id_qt_cps.equals(info.getPolicyIdentifier())) {
            DLSequence dls = (DLSequence) info.getPolicyQualifiers();
            for (int i = 0; i < dls.size(); i++) {
                DLSequence dls1 = (DLSequence) dls.getObjectAt(i);
                PolicyQualifierInfo pqInfo = new PolicyQualifierInfo((ASN1ObjectIdentifier) dls1.getObjectAt(0),
                        dls1.getObjectAt(1));
                // DLSequence dls1 = (DLSequence) dls.getObjectAt(i);
                if (id_qt_cps.equals(pqInfo.getPolicyQualifierId())) {
                    assertEquals(pqInfo.getQualifier().toString(), CPS_URI);
                } else {
                    fail("unknown policy qualifier id: " + pqInfo.getPolicyQualifierId());
                }
            }
        } else {
            fail("unknown policy identifier: " + info.getPolicyIdentifier());
        }
    }
}

From source file:com.otterca.common.crypto.SimplePolicyGeneratorTest.java

License:Apache License

/**
 * Test behavior when user notice is set.
 * /*w ww .j a v  a2  s . co m*/
 * @throws IOException
 */
@Test
@edu.umd.cs.findbugs.annotations.SuppressWarnings("NP_NONNULL_PARAM_VIOLATION")
public void testUserNoticePolicy() throws IOException {
    SimplePolicyGeneratorImpl generator = new SimplePolicyGeneratorImpl(null, ORGANIZATION, USER_NOTICE,
            Integer.valueOf(1));

    // get policy extensions
    byte[] policyBytes = generator.getExtension(SUBJECT, ISSUER);
    assertNotNull(policyBytes);

    X509Extensions exts = X509Extensions.getInstance(DLSequence.fromByteArray(policyBytes));
    ASN1Encodable asn1 = exts.getExtension(X509Extensions.CertificatePolicies).getParsedValue();
    CertificatePolicies policies = CertificatePolicies.getInstance(asn1);
    assertNotNull(policies, "unable to find CertificatePolicies extension");

    for (PolicyInformation info : policies.getPolicyInformation()) {
        if (id_qt_unotice.equals(info.getPolicyIdentifier())) {
            DLSequence dls = (DLSequence) info.getPolicyQualifiers();
            for (int i = 0; i < dls.size(); i++) {
                UserNotice userNotice = UserNotice.getInstance((DLSequence) dls.getObjectAt(i));
                assertEquals(userNotice.getNoticeRef().getOrganization().getString(), ORGANIZATION);
                assertEquals(userNotice.getNoticeRef().getNoticeNumbers()[0].getValue(), BigInteger.ONE);
                assertEquals(userNotice.getExplicitText().getString(), USER_NOTICE);
            }
        } else {
            fail("unknown policy identifier: " + info.getPolicyIdentifier());
        }
    }
}

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

License:Open Source License

private void checkPolicy() {
    ////from   ww  w.  jav 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;
    }
}

From source file:net.sf.keystore_explorer.crypto.x509.PolicyInformationUtil.java

License:Open Source License

/**
 * Get string representation of policy information.
 *
 * @param policyInformation//  w  w w . j  ava2  s . c  om
 *            Policy information
 * @return String representation of policy information
 * @throws IOException
 *             If policy information is invalid
 */
public static String toString(PolicyInformation policyInformation) throws IOException {
    StringBuffer sbPolicyInformation = new StringBuffer();

    ASN1ObjectIdentifier policyIdentifier = policyInformation.getPolicyIdentifier();

    sbPolicyInformation.append(MessageFormat.format(res.getString("PolicyInformationUtil.PolicyIdentifier"),
            policyIdentifier.getId()));

    ASN1Sequence policyQualifiers = policyInformation.getPolicyQualifiers();

    if (policyQualifiers != null) {
        sbPolicyInformation.append(", ");

        StringBuffer sbPolicyQualifiers = new StringBuffer();

        for (int i = 0; i < policyQualifiers.size(); i++) {
            PolicyQualifierInfo policyQualifierInfo = PolicyQualifierInfo
                    .getInstance(policyQualifiers.getObjectAt(i));

            sbPolicyQualifiers.append(toString(policyQualifierInfo));

            if ((i + 1) < policyQualifiers.size()) {
                sbPolicyQualifiers.append(", ");
            }
        }

        sbPolicyInformation.append(MessageFormat.format(res.getString("PolicyInformationUtil.PolicyQualifiers"),
                sbPolicyQualifiers));
    }

    return sbPolicyInformation.toString();
}

From source file:net.sf.keystore_explorer.crypto.x509.X509Ext.java

License:Open Source License

private String getCertificatePoliciesStringValue(byte[] value) throws IOException {
    // @formatter:off

    /*/*w ww .  ja  v a 2  s .  c om*/
     * CertificatePolicies ::= ASN1Sequence SIZE (1..MAX) OF PolicyInformation
     *
     * PolicyInformation ::= ASN1Sequence
     * {
     *      policyIdentifier CertPolicyId,
     *      policyQualifiers ASN1Sequence SIZE (1..MAX) OF PolicyQualifierInfo OPTIONAL
     * }
     *
     * CertPolicyId ::= OBJECT IDENTIFIER
     *
     * PolicyQualifierInfo ::= ASN1Sequence
     * {
     *      policyQualifierId PolicyQualifierId,
     *      qualifier ANY DEFINED BY policyQualifierId
     * }
     *
     * PolicyQualifierId ::= OBJECT IDENTIFIER ( id-qt-cps | id-qt-unotice )
     *
     * Qualifier ::= CHOICE
     * {
     *      cPSuri CPSuri,
     *      userNotice UserNotice
     * }
     *
     * CPSuri ::= DERIA5String
     *
     * UserNotice ::= ASN1Sequence
     * {
     *      noticeRef NoticeReference OPTIONAL,
     *      explicitText DisplayText OPTIONAL
     * }
     *
     * NoticeReference ::= ASN1Sequence
     * {
     *      organization DisplayText,
     *      noticeNumbers ASN1Sequence OF ASN1Integer
     * }
     *
     * DisplayText ::= CHOICE
     * {
     *      ia5String DERIA5String (SIZE (1..200)),
     *      visibleString VisibleString (SIZE (1..200)),
     *      bmpString BMPString (SIZE (1..200)),
     *      utf8String UTF8String (SIZE (1..200))
     * }
     */

    // @formatter:on

    StringBuilder sb = new StringBuilder();

    CertificatePolicies certificatePolicies = CertificatePolicies.getInstance(value);

    int certPolicy = 0;

    for (PolicyInformation policyInformation : certificatePolicies.getPolicyInformation()) {
        certPolicy++;

        sb.append(MessageFormat.format(res.getString("CertificatePolicy"), certPolicy));
        sb.append(NEWLINE);

        ASN1ObjectIdentifier policyIdentifier = policyInformation.getPolicyIdentifier();
        String policyIdentifierStr = ObjectIdUtil.toString(policyIdentifier);

        sb.append(INDENT);
        sb.append(MessageFormat.format(res.getString("PolicyIdentifier"), policyIdentifierStr));
        sb.append(NEWLINE);

        ASN1Sequence policyQualifiers = policyInformation.getPolicyQualifiers();

        if (policyQualifiers != null) { // Optional
            int policyQual = 0;

            for (ASN1Encodable policyQualifier : policyQualifiers.toArray()) {

                ASN1Sequence policyQualifierInfo = (ASN1Sequence) policyQualifier;

                sb.append(INDENT.toString(1));
                sb.append(MessageFormat.format(res.getString("PolicyQualifierInformation"), certPolicy,
                        ++policyQual));
                sb.append(NEWLINE);

                ASN1ObjectIdentifier policyQualifierId = (ASN1ObjectIdentifier) policyQualifierInfo
                        .getObjectAt(0);

                CertificatePolicyQualifierType certificatePolicyQualifierType = CertificatePolicyQualifierType
                        .resolveOid(policyQualifierId.getId());

                if (certificatePolicyQualifierType != null) {
                    sb.append(INDENT.toString(2));
                    sb.append(certificatePolicyQualifierType.friendly());
                    sb.append(NEWLINE);

                    if (certificatePolicyQualifierType == PKIX_CPS_POINTER_QUALIFIER) {
                        DERIA5String cpsPointer = (DERIA5String) policyQualifierInfo.getObjectAt(1);

                        sb.append(INDENT.toString(2));
                        sb.append(MessageFormat.format(res.getString("CpsPointer"),
                                "<a href=\"" + cpsPointer + "\">" + cpsPointer + "</a>"));
                        sb.append(NEWLINE);
                    } else if (certificatePolicyQualifierType == PKIX_USER_NOTICE_QUALIFIER) {
                        ASN1Encodable userNoticeObj = policyQualifierInfo.getObjectAt(1);

                        UserNotice userNotice = UserNotice.getInstance(userNoticeObj);

                        sb.append(INDENT.toString(2));
                        sb.append(res.getString("UserNotice"));
                        sb.append(NEWLINE);

                        NoticeReference noticeReference = userNotice.getNoticeRef();

                        DisplayText explicitText = userNotice.getExplicitText();

                        if (noticeReference != null) { // Optional
                            sb.append(INDENT.toString(3));
                            sb.append(res.getString("NoticeReference"));
                            sb.append(NEWLINE);

                            DisplayText organization = noticeReference.getOrganization();
                            String organizationString = organization.getString();

                            sb.append(INDENT.toString(4));
                            sb.append(MessageFormat.format(res.getString("Organization"), organizationString));
                            sb.append(NEWLINE);

                            ASN1Integer[] noticeNumbers = noticeReference.getNoticeNumbers();

                            StringBuilder sbNoticeNumbers = new StringBuilder();
                            for (ASN1Integer noticeNumber : noticeNumbers) {
                                sbNoticeNumbers.append(noticeNumber.getValue().intValue());
                                sbNoticeNumbers.append(", ");
                            }
                            sbNoticeNumbers.setLength(sbNoticeNumbers.length() - 2);

                            sb.append(INDENT.toString(4));
                            sb.append(MessageFormat.format(res.getString("NoticeNumbers"),
                                    sbNoticeNumbers.toString()));
                            sb.append(NEWLINE);
                        }

                        if (explicitText != null) { // Optional
                            String explicitTextString = explicitText.getString();

                            sb.append(INDENT.toString(3));
                            sb.append(MessageFormat.format(res.getString("ExplicitText"), explicitTextString));
                            sb.append(NEWLINE);
                        }
                    }
                }
            }
        }
    }

    return sb.toString();
}

From source file:net.sf.keystore_explorer.gui.crypto.policyinformation.DPolicyInformationChooser.java

License:Open Source License

private void populate(PolicyInformation policyInformation) throws IOException {
    if (policyInformation != null) {
        joiPolicyIdentifier.setObjectId(policyInformation.getPolicyIdentifier());

        ASN1Sequence policyQualifierInfoSeq = policyInformation.getPolicyQualifiers();

        if (policyQualifierInfoSeq != null) {
            List<PolicyQualifierInfo> policyQualifierInfo = new ArrayList<PolicyQualifierInfo>();

            for (int i = 0; i < policyQualifierInfoSeq.size(); i++) {
                PolicyQualifierInfo policyQualInfo = PolicyQualifierInfo
                        .getInstance(policyQualifierInfoSeq.getObjectAt(i));
                policyQualifierInfo.add(policyQualInfo);
            }/*from   w  ww . jav a 2s.  c  o m*/

            jpqPolicyQualifiers.setPolicyQualifierInfo(policyQualifierInfo);
        }
    }
}

From source file:net.sf.portecle.crypto.X509Ext.java

License:Open Source License

/**
 * Get extension value for Certificate Policies as a string.
 * //from ww  w  . j  a v  a 2  s  .co m
 * @see <a href="http://tools.ietf.org/html/rfc3280">RFC 3280</a>
 * @param bValue The octet string value
 * @return Extension value as a string
 * @throws IOException If an I/O problem occurs
 */
private String getCertificatePoliciesStringValue(byte[] bValue) throws IOException {
    ASN1Sequence pSeq = (ASN1Sequence) ASN1Primitive.fromByteArray(bValue);
    StringBuilder sb = new StringBuilder();

    for (int i = 0, len = pSeq.size(); i < len; i++) {
        PolicyInformation pi = PolicyInformation.getInstance(pSeq.getObjectAt(i));
        String piId = pi.getPolicyIdentifier().getId();

        sb.append("<ul><li>");
        sb.append(RB.getString("PolicyIdentifier"));
        sb.append(": ");
        sb.append(MessageFormat.format(getRes(piId, "UnrecognisedPolicyIdentifier"), piId));

        ASN1Sequence pQuals;
        if ((pQuals = pi.getPolicyQualifiers()) != null) {
            sb.append("<ul>");

            for (int j = 0, plen = pQuals.size(); j < plen; j++) {
                ASN1Sequence pqi = (ASN1Sequence) pQuals.getObjectAt(j);
                ASN1Encodable pqId = pqi.getObjectAt(0);
                String spqId = pqId.toString();

                sb.append("<li>");
                sb.append(MessageFormat.format(getRes(spqId, "UnrecognisedPolicyQualifier"), spqId));
                sb.append(": ");

                ASN1Encodable d = pqi.getObjectAt(1);
                sb.append("<ul>");
                if (pqId.equals(PolicyQualifierId.id_qt_cps)) {
                    // cPSuri
                    String sUri = ((ASN1String) d).getString();

                    sb.append("<li>");
                    sb.append(RB.getString("CpsUri"));
                    sb.append(": ");
                    sb.append(getLink(sUri, escapeHtml(sUri), LinkClass.BROWSER));
                    sb.append("</li>");
                } else if (pqId.equals(PolicyQualifierId.id_qt_unotice)) {
                    // userNotice
                    ASN1Sequence un = (ASN1Sequence) d;

                    for (int k = 0, dlen = un.size(); k < dlen; k++) {
                        ASN1Encodable de = un.getObjectAt(k);

                        // TODO: is it possible to use something
                        // smarter than instanceof here?

                        if (de instanceof ASN1String) {
                            // explicitText
                            sb.append("<li>");
                            sb.append(RB.getString("ExplicitText"));
                            sb.append(": ");
                            sb.append(stringify(de));
                            sb.append("</li>");
                        } else if (de instanceof ASN1Sequence) {
                            // noticeRef
                            ASN1Sequence nr = (ASN1Sequence) de;
                            String orgstr = stringify(nr.getObjectAt(0));
                            ASN1Sequence nrs = (ASN1Sequence) nr.getObjectAt(1);
                            StringBuilder nrstr = new StringBuilder();
                            for (int m = 0, nlen = nrs.size(); m < nlen; m++) {
                                nrstr.append(stringify(nrs.getObjectAt(m)));
                                if (m != nlen - 1) {
                                    nrstr.append(", ");
                                }
                            }
                            sb.append("<li>");
                            sb.append(RB.getString("NoticeRef"));
                            sb.append(": ");
                            sb.append(RB.getString("NoticeRefOrganization"));
                            sb.append(": ");
                            sb.append(orgstr);
                            sb.append(", ");
                            sb.append(RB.getString("NoticeRefNumber"));
                            sb.append(": ");
                            sb.append(nrstr);
                            sb.append("</li>");
                        }
                        // else TODO
                    }
                } else {
                    sb.append(stringify(d));
                }
                sb.append("</ul></li>");
            }
            sb.append("</ul></li>");
        }

        sb.append("</ul>");
        if (i != len) {
            sb.append("<br>");
        }
    }

    return sb.toString();
}

From source file:org.cryptacular.x509.ExtensionReaderTest.java

License:Open Source License

@Test(dataProvider = "certificate-policies")
public void testReadCertificatePolicies(final X509Certificate cert, final PolicyInformation[] expected)
        throws Exception {
    final List<PolicyInformation> policies = new ExtensionReader(cert).readCertificatePolicies();
    assertEquals(policies.size(), expected.length);

    PolicyInformation current;
    for (int i = 0; i < expected.length; i++) {
        current = policies.get(i);/*from   ww w.  j  a  v  a2 s  .  c  om*/
        assertEquals(current.getPolicyIdentifier(), expected[i].getPolicyIdentifier());
        if (expected[i].getPolicyQualifiers() != null) {
            for (int j = 0; j < expected[i].getPolicyQualifiers().size(); j++) {
                assertEquals(current.getPolicyQualifiers().getObjectAt(j),
                        expected[i].getPolicyQualifiers().getObjectAt(j));
            }
        }
    }
}

From source file:org.xipki.ca.qa.impl.X509CertprofileQAImpl.java

License:Open Source License

private void checkExtensionCertificatePolicies(final StringBuilder failureMsg, final byte[] extensionValue,
        final Extensions requestExtensions, final ExtensionControl extControl) {
    QaCertificatePolicies conf = certificatePolicies;
    if (conf == null) {
        byte[] expected = getExpectedExtValue(Extension.certificatePolicies, requestExtensions, extControl);
        if (Arrays.equals(expected, extensionValue) == false) {
            failureMsg.append("extension valus is '" + hex(extensionValue) + "' but expected '"
                    + (expected == null ? "not present" : hex(expected)) + "'");
            failureMsg.append("; ");
        }/*from   w ww.j a  v  a  2 s .  c o  m*/
        return;
    }

    org.bouncycastle.asn1.x509.CertificatePolicies asn1 = org.bouncycastle.asn1.x509.CertificatePolicies
            .getInstance(extensionValue);
    PolicyInformation[] iPolicyInformations = asn1.getPolicyInformation();

    for (PolicyInformation iPolicyInformation : iPolicyInformations) {
        ASN1ObjectIdentifier iPolicyId = iPolicyInformation.getPolicyIdentifier();
        QaCertificatePolicyInformation eCp = conf.getPolicyInformation(iPolicyId.getId());
        if (eCp == null) {
            failureMsg.append("certificate policy '" + iPolicyId + "' is not expected");
            failureMsg.append("; ");
            continue;
        }

        QaPolicyQualifiers eCpPq = eCp.getPolicyQualifiers();
        if (eCpPq == null) {
            continue;
        }

        ASN1Sequence iPolicyQualifiers = iPolicyInformation.getPolicyQualifiers();
        List<String> iCpsUris = new LinkedList<>();
        List<String> iUserNotices = new LinkedList<>();

        int n = iPolicyQualifiers.size();
        for (int i = 0; i < n; i++) {
            PolicyQualifierInfo iPolicyQualifierInfo = (PolicyQualifierInfo) iPolicyQualifiers.getObjectAt(i);
            ASN1ObjectIdentifier iPolicyQualifierId = iPolicyQualifierInfo.getPolicyQualifierId();
            ASN1Encodable iQualifier = iPolicyQualifierInfo.getQualifier();
            if (PolicyQualifierId.id_qt_cps.equals(iPolicyQualifierId)) {
                String iCpsUri = ((DERIA5String) iQualifier).getString();
                iCpsUris.add(iCpsUri);
            } else if (PolicyQualifierId.id_qt_unotice.equals(iPolicyQualifierId)) {
                UserNotice iUserNotice = UserNotice.getInstance(iQualifier);
                if (iUserNotice.getExplicitText() != null) {
                    iUserNotices.add(iUserNotice.getExplicitText().getString());
                }
            }
        }

        List<QaPolicyQualifierInfo> qualifierInfos = eCpPq.getPolicyQualifiers();
        for (QaPolicyQualifierInfo qualifierInfo : qualifierInfos) {
            if (qualifierInfo instanceof QaCPSUriPolicyQualifier) {
                String value = ((QaCPSUriPolicyQualifier) qualifierInfo).getCPSUri();
                if (iCpsUris.contains(value) == false) {
                    failureMsg.append("CPSUri '" + value + "' is absent but is required");
                    failureMsg.append("; ");
                }
            } else if (qualifierInfo instanceof QaUserNoticePolicyQualifierInfo) {
                String value = ((QaUserNoticePolicyQualifierInfo) qualifierInfo).getUserNotice();
                if (iUserNotices.contains(value) == false) {
                    failureMsg.append("userNotice '" + value + "' is absent but is required");
                    failureMsg.append("; ");
                }
            } else {
                throw new RuntimeException("should not reach here");
            }
        }
    }

    for (QaCertificatePolicyInformation cp : conf.getPolicyInformations()) {
        boolean present = false;
        for (PolicyInformation iPolicyInformation : iPolicyInformations) {
            if (iPolicyInformation.getPolicyIdentifier().getId().equals(cp.getPolicyId())) {
                present = true;
                break;
            }
        }

        if (present) {
            continue;
        }

        failureMsg.append("certificate policy '").append(cp.getPolicyId())
                .append("' is absent but is required");
        failureMsg.append("; ");
    }
}