Search in sources :

Example 16 with PolicyInformation

use of com.github.zhenwei.core.asn1.x509.PolicyInformation in project keystore-explorer by kaikramer.

the class X509Ext method getCertificatePoliciesStringValue.

private static String getCertificatePoliciesStringValue(byte[] value) throws IOException {
    // @formatter:off
    /*
		 * 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();
}
Also used : PolicyInformation(org.bouncycastle.asn1.x509.PolicyInformation) UserNotice(org.bouncycastle.asn1.x509.UserNotice) DERBitString(org.bouncycastle.asn1.DERBitString) ASN1OctetString(org.bouncycastle.asn1.ASN1OctetString) DERGeneralString(org.bouncycastle.asn1.DERGeneralString) ASN1IA5String(org.bouncycastle.asn1.ASN1IA5String) DirectoryString(org.bouncycastle.asn1.x500.DirectoryString) ASN1BitString(org.bouncycastle.asn1.ASN1BitString) DEROctetString(org.bouncycastle.asn1.DEROctetString) ASN1BMPString(org.bouncycastle.asn1.ASN1BMPString) DERIA5String(org.bouncycastle.asn1.DERIA5String) ASN1PrintableString(org.bouncycastle.asn1.ASN1PrintableString) NoticeReference(org.bouncycastle.asn1.x509.NoticeReference) ASN1Integer(org.bouncycastle.asn1.ASN1Integer) IssuingDistributionPoint(org.bouncycastle.asn1.x509.IssuingDistributionPoint) CRLDistPoint(org.bouncycastle.asn1.x509.CRLDistPoint) DistributionPoint(org.bouncycastle.asn1.x509.DistributionPoint) ASN1Sequence(org.bouncycastle.asn1.ASN1Sequence) DERIA5String(org.bouncycastle.asn1.DERIA5String) CertificatePolicies(org.bouncycastle.asn1.x509.CertificatePolicies) DisplayText(org.bouncycastle.asn1.x509.DisplayText) ASN1Encodable(org.bouncycastle.asn1.ASN1Encodable) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier)

Example 17 with PolicyInformation

use of com.github.zhenwei.core.asn1.x509.PolicyInformation in project signer by demoiselle.

the class BasicCertificate method getCertificateLevel.

/**
 * returns the ICP-BRASIL Certificate Level(A1, A2, A3, A4, S1, S2, S3,
 * S4).<br>
 * DOC-ICP-04 Returns the <b>null</b> value if the CertificatePolicies is
 * NOT present.
 *
 * @return String Certificate level
 */
public String getCertificateLevel() {
    try {
        DLSequence sequence = (DLSequence) getExtensionValue(Extension.certificatePolicies.getId());
        if (sequence != null) {
            for (int pos = 0; pos < sequence.size(); pos++) {
                DLSequence sequence2 = (DLSequence) sequence.getObjectAt(pos);
                ASN1ObjectIdentifier policyIdentifier = (ASN1ObjectIdentifier) sequence2.getObjectAt(0);
                PolicyInformation policyInformation = new PolicyInformation(policyIdentifier);
                String id = policyInformation.getPolicyIdentifier().getId();
                if (id == null) {
                    continue;
                }
                if (id.startsWith(OID_A1_CERTIFICATE)) {
                    return "A1";
                }
                if (id.startsWith(OID_A2_CERTIFICATE)) {
                    return "A2";
                }
                if (id.startsWith(OID_A3_CERTIFICATE)) {
                    return "A3";
                }
                if (id.startsWith(OID_A4_CERTIFICATE)) {
                    return "A4";
                }
                if (id.startsWith(OID_S1_CERTIFICATE)) {
                    return "S1";
                }
                if (id.startsWith(OID_S2_CERTIFICATE)) {
                    return "S2";
                }
                if (id.startsWith(OID_S3_CERTIFICATE)) {
                    return "S3";
                }
                if (id.startsWith(OID_S4_CERTIFICATE)) {
                    return "S4";
                }
            }
        }
        return null;
    } catch (Exception e) {
        logger.error(e.getMessage());
        return null;
    }
}
Also used : DLSequence(org.bouncycastle.asn1.DLSequence) PolicyInformation(org.bouncycastle.asn1.x509.PolicyInformation) DEROctetString(org.bouncycastle.asn1.DEROctetString) DERIA5String(org.bouncycastle.asn1.DERIA5String) DistributionPoint(org.bouncycastle.asn1.x509.DistributionPoint) CRLDistPoint(org.bouncycastle.asn1.x509.CRLDistPoint) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException)

Example 18 with PolicyInformation

use of com.github.zhenwei.core.asn1.x509.PolicyInformation in project keycloak by keycloak.

the class CertificateValidatorTest method testCertificatePolicyValidation.

// Helper to test various certificate policy validation combinations
private void testCertificatePolicyValidation(String expectedPolicy, String mode, String... certificatePolicyOid) throws GeneralSecurityException {
    List<Extension> certificatePolicies = null;
    if (certificatePolicyOid != null && certificatePolicyOid.length > 0) {
        certificatePolicies = new LinkedList<>();
        List<PolicyInformation> policyInfoList = new LinkedList<>();
        for (String oid : certificatePolicyOid) {
            policyInfoList.add(new PolicyInformation(new ASN1ObjectIdentifier(oid)));
        }
        CertificatePolicies policies = new CertificatePolicies(policyInfoList.toArray(new PolicyInformation[0]));
        try {
            boolean isCritical = false;
            Extension extension = new Extension(Extension.certificatePolicies, isCritical, policies.getEncoded());
            certificatePolicies.add(extension);
        } catch (IOException e) {
            throw new IllegalStateException(e);
        }
    }
    KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
    kpg.initialize(512);
    KeyPair keyPair = kpg.generateKeyPair();
    X509Certificate certificate = createCertificate("CN=keycloak-test", new Date(System.currentTimeMillis() - 1000L * 60 * 2), new Date(System.currentTimeMillis() - 1000L * 60), keyPair, certificatePolicies);
    CertificateValidator.CertificateValidatorBuilder builder = new CertificateValidator.CertificateValidatorBuilder();
    CertificateValidator validator = builder.certificatePolicy().mode(mode).parse(expectedPolicy).build(new X509Certificate[] { certificate });
    validator.validatePolicy();
}
Also used : KeyPair(java.security.KeyPair) PolicyInformation(org.bouncycastle.asn1.x509.PolicyInformation) IOException(java.io.IOException) CertIOException(org.bouncycastle.cert.CertIOException) KeyPairGenerator(java.security.KeyPairGenerator) LinkedList(java.util.LinkedList) X509Certificate(java.security.cert.X509Certificate) Date(java.util.Date) Extension(org.bouncycastle.asn1.x509.Extension) CertificatePolicies(org.bouncycastle.asn1.x509.CertificatePolicies) ASN1ObjectIdentifier(org.bouncycastle.asn1.ASN1ObjectIdentifier)

Example 19 with PolicyInformation

use of com.github.zhenwei.core.asn1.x509.PolicyInformation in project open-ecard by ecsec.

the class ListCertificates method matchesPolicy.

private boolean matchesPolicy(String policy, List<X509Certificate> certChain) throws CertificateException, ParameterInvalid {
    try {
        ASN1ObjectIdentifier policyId = new ASN1ObjectIdentifier(policy);
        X509Certificate cert = certChain.get(0);
        byte[] encodedPolicy = cert.getExtensionValue(Extension.certificatePolicies.getId());
        if (encodedPolicy != null) {
            encodedPolicy = ASN1OctetString.getInstance(encodedPolicy).getOctets();
            try {
                // extract policy object
                CertificatePolicies certPolicies = CertificatePolicies.getInstance(encodedPolicy);
                // see if any of the policies matches
                PolicyInformation targetPolicy = certPolicies.getPolicyInformation(policyId);
                return targetPolicy != null;
            } catch (IllegalArgumentException ex) {
                throw new CertificateException("Certificate contains invalid policy.");
            }
        } else {
            // no policy defined in certificate, so no match
            return false;
        }
    } catch (IllegalArgumentException ex) {
        throw new ParameterInvalid("Requested policy filter is not an OID.");
    }
}
Also used : CertificatePolicies(org.openecard.bouncycastle.asn1.x509.CertificatePolicies) PolicyInformation(org.openecard.bouncycastle.asn1.x509.PolicyInformation) CertificateException(java.security.cert.CertificateException) ParameterInvalid(org.openecard.addons.cg.ex.ParameterInvalid) ASN1ObjectIdentifier(org.openecard.bouncycastle.asn1.ASN1ObjectIdentifier) X509Certificate(java.security.cert.X509Certificate)

Example 20 with PolicyInformation

use of com.github.zhenwei.core.asn1.x509.PolicyInformation in project LinLong-Java by zhenwei1108.

the class RFC3280CertPathUtilities method processCertD.

protected static PKIXPolicyNode processCertD(CertPath certPath, int index, Set acceptablePolicies, PKIXPolicyNode validPolicyTree, List[] policyNodes, int inhibitAnyPolicy, boolean isForCRLCheck) throws CertPathValidatorException {
    List certs = certPath.getCertificates();
    X509Certificate cert = (X509Certificate) certs.get(index);
    int n = certs.size();
    // i as defined in the algorithm description
    int i = n - index;
    // 
    // (d) policy Information checking against initial policy and
    // policy mapping
    // 
    ASN1Sequence certPolicies = null;
    try {
        certPolicies = ASN1Sequence.getInstance(CertPathValidatorUtilities.getExtensionValue(cert, RFC3280CertPathUtilities.CERTIFICATE_POLICIES));
    } catch (AnnotatedException e) {
        throw new ExtCertPathValidatorException("Could not read certificate policies extension from certificate.", e, 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 (!RFC3280CertPathUtilities.ANY_POLICY.equals(pOid.getId())) {
                Set pq = null;
                try {
                    pq = CertPathValidatorUtilities.getQualifierSet(pInfo.getPolicyQualifiers());
                } catch (CertPathValidatorException ex) {
                    throw new ExtCertPathValidatorException("Policy qualifier info set could not be build.", ex, certPath, index);
                }
                boolean match = CertPathValidatorUtilities.processCertD1i(i, policyNodes, pOid, pq);
                if (!match) {
                    CertPathValidatorUtilities.processCertD1ii(i, policyNodes, pOid, pq);
                }
            }
        }
        if (acceptablePolicies.isEmpty() || acceptablePolicies.contains(RFC3280CertPathUtilities.ANY_POLICY)) {
            acceptablePolicies.clear();
            acceptablePolicies.addAll(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.clear();
            acceptablePolicies.addAll(t1);
        }
        // 
        if ((inhibitAnyPolicy > 0) || ((i < n || isForCRLCheck) && CertPathValidatorUtilities.isSelfIssued(cert))) {
            e = certPolicies.getObjects();
            while (e.hasMoreElements()) {
                PolicyInformation pInfo = PolicyInformation.getInstance(e.nextElement());
                if (RFC3280CertPathUtilities.ANY_POLICY.equals(pInfo.getPolicyIdentifier().getId())) {
                    Set _apq = CertPathValidatorUtilities.getQualifierSet(pInfo.getPolicyQualifiers());
                    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;
                }
            }
        }
        PKIXPolicyNode _validPolicyTree = validPolicyTree;
        // 
        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 = CertPathValidatorUtilities.removePolicyNode(_validPolicyTree, policyNodes, node);
                    if (_validPolicyTree == null) {
                        break;
                    }
                }
            }
        }
        // 
        // d (4)
        // 
        Set criticalExtensionOids = cert.getCriticalExtensionOIDs();
        if (criticalExtensionOids != null) {
            boolean critical = criticalExtensionOids.contains(RFC3280CertPathUtilities.CERTIFICATE_POLICIES);
            List nodes = policyNodes[i];
            for (int j = 0; j < nodes.size(); j++) {
                PKIXPolicyNode node = (PKIXPolicyNode) nodes.get(j);
                node.setCritical(critical);
            }
        }
        return _validPolicyTree;
    }
    return null;
}
Also used : Enumeration(java.util.Enumeration) Set(java.util.Set) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet) PolicyInformation(com.github.zhenwei.core.asn1.x509.PolicyInformation) ArrayList(java.util.ArrayList) ASN1String(com.github.zhenwei.core.asn1.ASN1String) X509Certificate(java.security.cert.X509Certificate) IssuingDistributionPoint(com.github.zhenwei.core.asn1.x509.IssuingDistributionPoint) CRLDistPoint(com.github.zhenwei.core.asn1.x509.CRLDistPoint) DistributionPoint(com.github.zhenwei.core.asn1.x509.DistributionPoint) CertPathValidatorException(java.security.cert.CertPathValidatorException) ExtCertPathValidatorException(com.github.zhenwei.provider.jce.exception.ExtCertPathValidatorException) ASN1Sequence(com.github.zhenwei.core.asn1.ASN1Sequence) ExtCertPathValidatorException(com.github.zhenwei.provider.jce.exception.ExtCertPathValidatorException) Iterator(java.util.Iterator) List(java.util.List) ArrayList(java.util.ArrayList) ASN1TaggedObject(com.github.zhenwei.core.asn1.ASN1TaggedObject) ASN1ObjectIdentifier(com.github.zhenwei.core.asn1.ASN1ObjectIdentifier) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet)

Aggregations

IOException (java.io.IOException)24 PolicyInformation (org.bouncycastle.asn1.x509.PolicyInformation)23 ArrayList (java.util.ArrayList)19 CertPathValidatorException (java.security.cert.CertPathValidatorException)17 ASN1Sequence (org.bouncycastle.asn1.ASN1Sequence)14 HashSet (java.util.HashSet)12 Enumeration (java.util.Enumeration)11 Iterator (java.util.Iterator)11 Set (java.util.Set)11 X509Certificate (java.security.cert.X509Certificate)9 ASN1ObjectIdentifier (org.bouncycastle.asn1.ASN1ObjectIdentifier)9 List (java.util.List)8 GeneralSecurityException (java.security.GeneralSecurityException)7 CRLDistPoint (org.bouncycastle.asn1.x509.CRLDistPoint)7 DistributionPoint (org.bouncycastle.asn1.x509.DistributionPoint)7 PolicyInformation (sun.security.x509.PolicyInformation)7 ExtCertPathValidatorException (org.bouncycastle.jce.exception.ExtCertPathValidatorException)6 ASN1Sequence (com.github.zhenwei.core.asn1.ASN1Sequence)5 PolicyInformation (com.github.zhenwei.core.asn1.x509.PolicyInformation)5 ASN1EncodableVector (com.github.zhenwei.core.asn1.ASN1EncodableVector)4