Example usage for org.bouncycastle.asn1.x509.qualified QCStatement getStatementInfo

List of usage examples for org.bouncycastle.asn1.x509.qualified QCStatement getStatementInfo

Introduction

In this page you can find the example usage for org.bouncycastle.asn1.x509.qualified QCStatement getStatementInfo.

Prototype

public ASN1Encodable getStatementInfo() 

Source Link

Usage

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

License:Open Source License

private boolean processQcStatements(X509Certificate cert, int index) {
    try {/*from  w ww .ja  va 2s . c o m*/
        boolean unknownStatement = false;

        ASN1Sequence qcSt = (ASN1Sequence) getExtensionValue(cert, QC_STATEMENT);
        for (int j = 0; j < qcSt.size(); j++) {
            QCStatement stmt = QCStatement.getInstance(qcSt.getObjectAt(j));
            if (QCStatement.id_etsi_qcs_QcCompliance.equals(stmt.getStatementId())) {
                // process statement - just write a notification that the certificate contains this statement
                ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.QcEuCompliance");
                addNotification(msg, index);
            } else if (QCStatement.id_qcs_pkixQCSyntax_v1.equals(stmt.getStatementId())) {
                // process statement - just recognize the statement
            } else if (QCStatement.id_etsi_qcs_QcSSCD.equals(stmt.getStatementId())) {
                // process statement - just write a notification that the certificate contains this statement
                ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.QcSSCD");
                addNotification(msg, index);
            } else if (QCStatement.id_etsi_qcs_LimiteValue.equals(stmt.getStatementId())) {
                // process statement - write a notification containing the limit value
                MonetaryValue limit = MonetaryValue.getInstance(stmt.getStatementInfo());
                Iso4217CurrencyCode currency = limit.getCurrency();
                double value = limit.getAmount().doubleValue()
                        * Math.pow(10, limit.getExponent().doubleValue());
                ErrorBundle msg;
                if (limit.getCurrency().isAlphabetic()) {
                    msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.QcLimitValueAlpha", new Object[] {
                            limit.getCurrency().getAlphabetic(), new TrustedInput(new Double(value)), limit });
                } else {
                    msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.QcLimitValueNum",
                            new Object[] { new Integer(limit.getCurrency().getNumeric()),
                                    new TrustedInput(new Double(value)), limit });
                }
                addNotification(msg, index);
            } else {
                ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.QcUnknownStatement",
                        new Object[] { stmt.getStatementId(), new UntrustedInput(stmt) });
                addNotification(msg, index);
                unknownStatement = true;
            }
        }

        return !unknownStatement;
    } catch (AnnotatedException ae) {
        ErrorBundle msg = new ErrorBundle(RESOURCE_NAME, "CertPathReviewer.QcStatementExtError");
        addError(msg, index);
    }

    return false;
}

From source file:it.trento.comune.j4sign.verification.CertValidity.java

License:Open Source License

public boolean getHasQcStatements() {

    try {//  w  w w . ja  v  a 2s . co m

        hasQCStatements = it.trento.comune.j4sign.verification.utils.CertUtils.QCStatements
                .hasQcStatement(cert);
        qcCompliance = false;

        qcStatementsStrings = null;

        if (hasQCStatements) {
            qcStatementsStrings = new ArrayList<String>();

            ASN1Sequence qcStatements = CertUtils.QCStatements.getQcStatements(cert);

            Enumeration<?> qcStatementEnum = qcStatements.getObjects();

            while (qcStatementEnum.hasMoreElements()) {
                QCStatement qc = QCStatement.getInstance(qcStatementEnum.nextElement());

                DERObjectIdentifier statementId = qc.getStatementId();

                if (ETSIQCObjectIdentifiers.id_etsi_qcs_QcCompliance.getId().equals(statementId.getId())) {
                    qcCompliance = true;
                    qcStatementsStrings.add(statementId.getId() + " (etsi_qcs_QcCompliance)");
                } else if (ETSIQCObjectIdentifiers.id_etsi_qcs_LimiteValue.getId()
                        .equals(statementId.getId())) {
                    String qcLimit = CertUtils.QCStatements.getQcStatementValueLimit(cert);

                    qcStatementsStrings.add(statementId.getId() + " (id_etsi_qcs_LimiteValue): " + qcLimit);
                } else if (ETSIQCObjectIdentifiers.id_etsi_qcs_RetentionPeriod.getId()
                        .equals(statementId.getId())) {

                    String qcRetentionPeriod = DERInteger.getInstance(qc.getStatementInfo()).toString();
                    qcStatementsStrings
                            .add(statementId.getId() + " (etsi_qcs_RetentionPeriod): " + qcRetentionPeriod);
                } else if (ETSIQCObjectIdentifiers.id_etsi_qcs_QcSSCD.getId().equals(statementId.getId())) {
                    qcStatementsStrings.add(statementId.getId() + " (etsi_qcs_QcSSCD)");
                } else
                    qcStatementsStrings.add(statementId.getId() + " (Unknown)");
            }
        }

    } catch (IOException e) {

        hasQCStatements = false;

    }

    return hasQCStatements;
}

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

License:Open Source License

private String getQcStatementsStringValue(byte[] octets) throws IOException {

    // @formatter:off

    /*// w  w w  .ja v a  2  s  .  c  o  m
       QCStatements ::= SEQUENCE OF QSStatement
        QSStatement ::= SEQUENCE
        {
      statementId OBJECT IDENTIFIER,
      statementInfo ANY DEFINED BY statementId OPTIONAL
        }
        QcEuLimitValue ::= MonetaryValue
       QcRetentionPeriod ::= INTEGER
     */

    // @formatter:on

    StringBuilder sb = new StringBuilder();

    int qcStatementNr = 0;

    ASN1Sequence qcStatements = ASN1Sequence.getInstance(octets);
    for (ASN1Encodable asn1Encodable : qcStatements.toArray()) {
        QCStatement qcStatement = QCStatement.getInstance(asn1Encodable);
        ASN1ObjectIdentifier statementId = qcStatement.getStatementId();
        ASN1Encodable statementInfo = qcStatement.getStatementInfo();

        int indentLevel = 1;

        sb.append(MessageFormat.format(res.getString("QCStatement.QCStatement"), ++qcStatementNr));
        sb.append(NEWLINE);

        QcStatementType qcStatementType = QcStatementType.resolveOid(statementId.getId());
        switch (qcStatementType) {
        case QC_SYNTAX_V1:
        case QC_SYNTAX_V2:
            SemanticsInformation semanticsInfo = SemanticsInformation.getInstance(statementInfo);
            sb.append(getSemanticInformationValueString(qcStatementType, semanticsInfo, indentLevel));
            break;
        case QC_COMPLIANCE:
            // no statementInfo
            sb.append(INDENT.toString(indentLevel));
            sb.append(res.getString(QcStatementType.QC_COMPLIANCE.getResKey()));
            sb.append(NEWLINE);
            break;
        case QC_EU_LIMIT_VALUE:
            sb.append(INDENT.toString(indentLevel));
            sb.append(res.getString(QcStatementType.QC_EU_LIMIT_VALUE.getResKey()));
            sb.append(NEWLINE);
            sb.append(getMonetaryValueStringValue(statementInfo, indentLevel + 1));
            break;
        case QC_RETENTION_PERIOD:
            ASN1Integer asn1Integer = ASN1Integer.getInstance(statementInfo);
            sb.append(INDENT.toString(indentLevel));
            sb.append(MessageFormat.format(res.getString(QcStatementType.QC_RETENTION_PERIOD.getResKey()),
                    asn1Integer.getValue().toString()));
            sb.append(NEWLINE);
            break;
        case QC_SSCD:
            // no statementInfo
            sb.append(INDENT.toString(indentLevel));
            sb.append(res.getString(QcStatementType.QC_SSCD.getResKey()));
            sb.append(NEWLINE);
            break;
        }
    }

    return sb.toString();
}

From source file:org.cesecore.certificates.util.cert.QCStatementExtension.java

License:Open Source License

/** Returns the value limit ETSI QCStatement if present.
 * /*  ww w .  j a  va 2s  .  com*/
 * @param cert Certificate possibly containing the QCStatement extension
 * @return String with the value and currency (ex '50000 SEK')or null if the extension is not present
 * @throws IOException if there is a problem parsing the certificate
 */
public static String getQcStatementValueLimit(final Certificate cert) throws IOException {
    String ret = null;
    if (cert instanceof X509Certificate) {
        final X509Certificate x509cert = (X509Certificate) cert;
        final ASN1Primitive obj = getExtensionValue(x509cert, Extension.qCStatements.getId());
        if (obj == null) {
            return null;
        }
        final ASN1Sequence seq = (ASN1Sequence) obj;
        MonetaryValue mv = null;
        // Look through all the QCStatements and see if we have a stadard ETSI LimitValue
        for (int i = 0; i < seq.size(); i++) {
            final QCStatement qc = QCStatement.getInstance(seq.getObjectAt(i));
            final ASN1ObjectIdentifier oid = qc.getStatementId();
            if ((oid != null) && oid.equals(ETSIQCObjectIdentifiers.id_etsi_qcs_LimiteValue)) {
                // We MAY have a MonetaryValue object here
                final ASN1Encodable enc = qc.getStatementInfo();
                if (enc != null) {
                    mv = MonetaryValue.getInstance(enc);
                    // We can break the loop now, we got it!
                    break;
                }
            }
        }
        if (mv != null) {
            final BigInteger amount = mv.getAmount();
            final BigInteger exp = mv.getExponent();
            final BigInteger ten = BigInteger.valueOf(10);
            // A possibly gotcha here if the monetary value is larger than what fits in a long...
            final long value = amount.longValue() * (ten.pow(exp.intValue())).longValue();
            if (value < 0) {
                log.error("ETSI LimitValue amount is < 0.");
            }
            final String curr = mv.getCurrency().getAlphabetic();
            if (curr == null) {
                log.error("ETSI LimitValue currency is null");
            }
            if ((value >= 0) && (curr != null)) {
                ret = value + " " + curr;
            }
        }
    }
    return ret;
}

From source file:org.cesecore.certificates.util.cert.QCStatementExtension.java

License:Open Source License

/** Returns the 'NameRegistrationAuthorities' defined in the QCStatement extension (rfc3739).
 * /* w w w.j a  v  a 2s.  co m*/
 * @param cert Certificate containing the extension
 * @return String with for example 'rfc822Name=foo2bar.se, rfc822Name=bar2foo.se' etc. Supports email, dns and uri name, or null of no RAs are found.
 * @throws IOException if there is a problem parsing the certificate
 */
public static String getQcStatementAuthorities(final Certificate cert) throws IOException {
    String ret = null;
    if (cert instanceof X509Certificate) {
        final X509Certificate x509cert = (X509Certificate) cert;
        final ASN1Primitive obj = getExtensionValue(x509cert, Extension.qCStatements.getId());
        if (obj == null) {
            return null;
        }
        final ASN1Sequence seq = (ASN1Sequence) obj;
        SemanticsInformation si = null;
        // Look through all the QCStatements and see if we have a standard RFC3739 pkixQCSyntax
        for (int i = 0; i < seq.size(); i++) {
            final QCStatement qc = QCStatement.getInstance(seq.getObjectAt(i));
            final ASN1ObjectIdentifier oid = qc.getStatementId();
            if ((oid != null) && (oid.equals(RFC3739QCObjectIdentifiers.id_qcs_pkixQCSyntax_v1)
                    || oid.equals(RFC3739QCObjectIdentifiers.id_qcs_pkixQCSyntax_v2))) {
                // We MAY have a SemanticsInformation object here
                final ASN1Encodable enc = qc.getStatementInfo();
                if (enc != null) {
                    si = SemanticsInformation.getInstance(enc);
                    // We can break the loop now, we got it!
                    break;
                }
            }
        }
        if (si != null) {
            final GeneralName[] gns = si.getNameRegistrationAuthorities();
            if (gns == null) {
                return null;
            }
            final StringBuilder strBuf = new StringBuilder();
            for (int i = 0; i < gns.length; i++) {
                final GeneralName gn = gns[i];
                if (strBuf.length() != 0) {
                    // Append comma so we get nice formatting if there are more than one authority
                    strBuf.append(", ");
                }
                final String str = getGeneralNameString(gn.getTagNo(), gn.getName());
                if (str != null) {
                    strBuf.append(str);
                }
            }
            if (strBuf.length() > 0) {
                ret = strBuf.toString();
            }
        }
    }
    return ret;
}

From source file:org.ejbca.util.cert.QCStatementExtension.java

License:Open Source License

/** Returns the value limit ETSI QCStatement if present.
 * //from   w ww  . j  av a  2  s.c  o m
 * @param cert Certificate possibly containing the QCStatement extension
 * @return String with the value and currency (ex '50000 SEK')or null if the extension is not present
 * @throws IOException if there is a problem parsing the certificate
 */
public static String getQcStatementValueLimit(final Certificate cert) throws IOException {
    String ret = null;
    if (cert instanceof X509Certificate) {
        final X509Certificate x509cert = (X509Certificate) cert;
        final DERObject obj = getExtensionValue(x509cert, X509Extensions.QCStatements.getId());
        if (obj == null) {
            return null;
        }
        final ASN1Sequence seq = (ASN1Sequence) obj;
        MonetaryValue mv = null;
        // Look through all the QCStatements and see if we have a stadard ETSI LimitValue
        for (int i = 0; i < seq.size(); i++) {
            final QCStatement qc = QCStatement.getInstance(seq.getObjectAt(i));
            final DERObjectIdentifier oid = qc.getStatementId();
            if ((oid != null) && oid.equals(ETSIQCObjectIdentifiers.id_etsi_qcs_LimiteValue)) {
                // We MAY have a MonetaryValue object here
                final ASN1Encodable enc = qc.getStatementInfo();
                if (enc != null) {
                    mv = MonetaryValue.getInstance(enc);
                    // We can break the loop now, we got it!
                    break;
                }
            }
        }
        if (mv != null) {
            final BigInteger amount = mv.getAmount();
            final BigInteger exp = mv.getExponent();
            final BigInteger ten = BigInteger.valueOf(10);
            // A possibly gotcha here if the monetary value is larger than what fits in a long...
            final long value = amount.longValue() * (ten.pow(exp.intValue())).longValue();
            if (value < 0) {
                log.error("ETSI LimitValue amount is < 0.");
            }
            final String curr = mv.getCurrency().getAlphabetic();
            if (curr == null) {
                log.error("ETSI LimitValue currency is null");
            }
            if ((value >= 0) && (curr != null)) {
                ret = value + " " + curr;
            }
        }
    }
    return ret;
}

From source file:org.ejbca.util.cert.QCStatementExtension.java

License:Open Source License

/** Returns the 'NameRegistrationAuthorities' defined in the QCStatement extension (rfc3739).
 * //from w  w  w.  j a va  2s . c om
 * @param cert Certificate containing the extension
 * @return String with for example 'rfc822Name=foo2bar.se, rfc822Name=bar2foo.se' etc. Supports email, dns and uri name, or null of no RAs are found.
 * @throws IOException if there is a problem parsing the certificate
 */
public static String getQcStatementAuthorities(final Certificate cert) throws IOException {
    String ret = null;
    if (cert instanceof X509Certificate) {
        final X509Certificate x509cert = (X509Certificate) cert;
        final DERObject obj = getExtensionValue(x509cert, X509Extensions.QCStatements.getId());
        if (obj == null) {
            return null;
        }
        final ASN1Sequence seq = (ASN1Sequence) obj;
        SemanticsInformation si = null;
        // Look through all the QCStatements and see if we have a standard RFC3739 pkixQCSyntax
        for (int i = 0; i < seq.size(); i++) {
            final QCStatement qc = QCStatement.getInstance(seq.getObjectAt(i));
            final DERObjectIdentifier oid = qc.getStatementId();
            if ((oid != null) && (oid.equals(RFC3739QCObjectIdentifiers.id_qcs_pkixQCSyntax_v1)
                    || oid.equals(RFC3739QCObjectIdentifiers.id_qcs_pkixQCSyntax_v2))) {
                // We MAY have a SemanticsInformation object here
                final ASN1Encodable enc = qc.getStatementInfo();
                if (enc != null) {
                    si = SemanticsInformation.getInstance(enc);
                    // We can break the loop now, we got it!
                    break;
                }
            }
        }
        if (si != null) {
            final GeneralName[] gns = si.getNameRegistrationAuthorities();
            if (gns == null) {
                return null;
            }
            final StringBuilder strBuf = new StringBuilder();
            for (int i = 0; i < gns.length; i++) {
                final GeneralName gn = gns[i];
                if (strBuf.length() != 0) {
                    // Append comma so we get nice formatting if there are more than one authority
                    strBuf.append(", ");
                }
                final String str = getGeneralNameString(gn.getTagNo(), gn.getName());
                if (str != null) {
                    strBuf.append(str);
                }
            }
            if (strBuf.length() > 0) {
                ret = strBuf.toString();
            }
        }
    }
    return ret;
}

From source file:org.kse.crypto.x509.X509Ext.java

License:Open Source License

private String getQcStatementsStringValue(byte[] octets) throws IOException {

    // @formatter:off

    /*//from   ww w  .  j av  a 2 s.com
       QCStatements ::= SEQUENCE OF QSStatement
        QSStatement ::= SEQUENCE
        {
      statementId OBJECT IDENTIFIER,
      statementInfo ANY DEFINED BY statementId OPTIONAL
        }
        QcEuLimitValue ::= MonetaryValue
       QcRetentionPeriod ::= INTEGER
     */

    // @formatter:on

    StringBuilder sb = new StringBuilder();

    int qcStatementNr = 0;

    ASN1Sequence qcStatements = ASN1Sequence.getInstance(octets);
    for (ASN1Encodable asn1Encodable : qcStatements.toArray()) {
        QCStatement qcStatement = QCStatement.getInstance(asn1Encodable);
        ASN1ObjectIdentifier statementId = qcStatement.getStatementId();
        ASN1Encodable statementInfo = qcStatement.getStatementInfo();

        int indentLevel = 1;

        sb.append(MessageFormat.format(res.getString("QCStatement.QCStatement"), ++qcStatementNr));
        sb.append(NEWLINE);

        QcStatementType qcStatementType = QcStatementType.resolveOid(statementId.getId());
        if (qcStatementType != null) {
            switch (qcStatementType) {
            case QC_SYNTAX_V1:
            case QC_SYNTAX_V2:
                SemanticsInformation semanticsInfo = SemanticsInformation.getInstance(statementInfo);
                sb.append(getSemanticInformationValueString(qcStatementType, semanticsInfo, indentLevel));
                break;
            case QC_COMPLIANCE:
                // no statementInfo
                sb.append(INDENT.toString(indentLevel));
                sb.append(res.getString(QcStatementType.QC_COMPLIANCE.getResKey()));
                sb.append(NEWLINE);
                break;
            case QC_EU_LIMIT_VALUE:
                sb.append(INDENT.toString(indentLevel));
                sb.append(res.getString(QcStatementType.QC_EU_LIMIT_VALUE.getResKey()));
                sb.append(NEWLINE);
                sb.append(getMonetaryValueStringValue(statementInfo, indentLevel + 1));
                break;
            case QC_RETENTION_PERIOD:
                ASN1Integer asn1Integer = ASN1Integer.getInstance(statementInfo);
                sb.append(INDENT.toString(indentLevel));
                sb.append(MessageFormat.format(res.getString(QcStatementType.QC_RETENTION_PERIOD.getResKey()),
                        asn1Integer.getValue().toString()));
                sb.append(NEWLINE);
                break;
            case QC_SSCD:
                // no statementInfo
                sb.append(INDENT.toString(indentLevel));
                sb.append(res.getString(QcStatementType.QC_SSCD.getResKey()));
                sb.append(NEWLINE);
                break;
            case QC_PDS:
                ASN1Sequence pdsLocations = ASN1Sequence.getInstance(statementInfo);
                sb.append(INDENT.toString(indentLevel));
                sb.append(res.getString(QcStatementType.QC_PDS.getResKey()));
                for (ASN1Encodable pdsLoc : pdsLocations) {
                    sb.append(NEWLINE);
                    sb.append(INDENT.toString(indentLevel + 1));
                    DLSequence pds = (DLSequence) pdsLoc;
                    sb.append(MessageFormat.format(res.getString("QCPDS.locations"), pds.getObjectAt(1),
                            pds.getObjectAt(0)));
                }
                sb.append(NEWLINE);
                break;
            case QC_TYPE:
                sb.append(INDENT.toString(indentLevel));
                sb.append(res.getString(QcStatementType.QC_TYPE.getResKey()));
                ASN1Sequence qcTypes = ASN1Sequence.getInstance(statementInfo);
                for (ASN1Encodable type : qcTypes) {
                    sb.append(NEWLINE);
                    sb.append(INDENT.toString(indentLevel + 1));
                    sb.append(ObjectIdUtil.toString((ASN1ObjectIdentifier) type));
                }
                sb.append(NEWLINE);
            }
        } else {
            // no statementInfo
            sb.append(INDENT.toString(indentLevel));
            sb.append(statementId.getId());
            sb.append(statementInfo.toString());
            sb.append(NEWLINE);
        }
    }

    return sb.toString();

}

From source file:org.xipki.pki.ca.certprofile.XmlX509Certprofile.java

License:Open Source License

@Override
public ExtensionValues getExtensions(final Map<ASN1ObjectIdentifier, ExtensionControl> extensionOccurences,
        final X500Name requestedSubject, final X500Name grantedSubject, final Extensions requestedExtensions,
        final Date notBefore, final Date notAfter) throws CertprofileException, BadCertTemplateException {
    ExtensionValues values = new ExtensionValues();
    if (CollectionUtil.isEmpty(extensionOccurences)) {
        return values;
    }/*w  w w. j av a2  s.c  o m*/

    ParamUtil.requireNonNull("requestedSubject", requestedSubject);
    ParamUtil.requireNonNull("notBefore", notBefore);
    ParamUtil.requireNonNull("notAfter", notAfter);

    Set<ASN1ObjectIdentifier> occurences = new HashSet<>(extensionOccurences.keySet());

    // AuthorityKeyIdentifier
    // processed by the CA

    // SubjectKeyIdentifier
    // processed by the CA

    // KeyUsage
    // processed by the CA

    // CertificatePolicies
    ASN1ObjectIdentifier type = Extension.certificatePolicies;
    if (certificatePolicies != null) {
        if (occurences.remove(type)) {
            values.addExtension(type, certificatePolicies);
        }
    }

    // Policy Mappings
    type = Extension.policyMappings;
    if (policyMappings != null) {
        if (occurences.remove(type)) {
            values.addExtension(type, policyMappings);
        }
    }

    // SubjectAltName
    type = Extension.subjectAlternativeName;
    if (occurences.contains(type)) {
        GeneralNames genNames = createRequestedSubjectAltNames(requestedSubject, grantedSubject,
                requestedExtensions);
        if (genNames != null) {
            ExtensionValue value = new ExtensionValue(extensionControls.get(type).isCritical(), genNames);
            values.addExtension(type, value);
            occurences.remove(type);
        }
    }

    // IssuerAltName
    // processed by the CA

    // Subject Directory Attributes
    type = Extension.subjectDirectoryAttributes;
    if (occurences.contains(type) && subjectDirAttrsControl != null) {
        Extension extension = (requestedExtensions == null) ? null : requestedExtensions.getExtension(type);
        if (extension == null) {
            throw new BadCertTemplateException(
                    "no SubjectDirecotryAttributes extension is contained in the request");
        }

        ASN1GeneralizedTime dateOfBirth = null;
        String placeOfBirth = null;
        String gender = null;
        List<String> countryOfCitizenshipList = new LinkedList<>();
        List<String> countryOfResidenceList = new LinkedList<>();
        Map<ASN1ObjectIdentifier, List<ASN1Encodable>> otherAttrs = new HashMap<>();

        Vector<?> reqSubDirAttrs = SubjectDirectoryAttributes.getInstance(extension.getParsedValue())
                .getAttributes();
        final int n = reqSubDirAttrs.size();
        for (int i = 0; i < n; i++) {
            Attribute attr = (Attribute) reqSubDirAttrs.get(i);
            ASN1ObjectIdentifier attrType = attr.getAttrType();
            ASN1Encodable attrVal = attr.getAttributeValues()[0];

            if (ObjectIdentifiers.DN_DATE_OF_BIRTH.equals(attrType)) {
                dateOfBirth = ASN1GeneralizedTime.getInstance(attrVal);
            } else if (ObjectIdentifiers.DN_PLACE_OF_BIRTH.equals(attrType)) {
                placeOfBirth = DirectoryString.getInstance(attrVal).getString();
            } else if (ObjectIdentifiers.DN_GENDER.equals(attrType)) {
                gender = DERPrintableString.getInstance(attrVal).getString();
            } else if (ObjectIdentifiers.DN_COUNTRY_OF_CITIZENSHIP.equals(attrType)) {
                String country = DERPrintableString.getInstance(attrVal).getString();
                countryOfCitizenshipList.add(country);
            } else if (ObjectIdentifiers.DN_COUNTRY_OF_RESIDENCE.equals(attrType)) {
                String country = DERPrintableString.getInstance(attrVal).getString();
                countryOfResidenceList.add(country);
            } else {
                List<ASN1Encodable> otherAttrVals = otherAttrs.get(attrType);
                if (otherAttrVals == null) {
                    otherAttrVals = new LinkedList<>();
                    otherAttrs.put(attrType, otherAttrVals);
                }
                otherAttrVals.add(attrVal);
            }
        }

        Vector<Attribute> attrs = new Vector<>();
        for (ASN1ObjectIdentifier attrType : subjectDirAttrsControl.getTypes()) {
            if (ObjectIdentifiers.DN_DATE_OF_BIRTH.equals(attrType)) {
                if (dateOfBirth != null) {
                    String timeStirng = dateOfBirth.getTimeString();
                    if (!SubjectDnSpec.PATTERN_DATE_OF_BIRTH.matcher(timeStirng).matches()) {
                        throw new BadCertTemplateException("invalid dateOfBirth " + timeStirng);
                    }
                    attrs.add(new Attribute(attrType, new DERSet(dateOfBirth)));
                    continue;
                }
            } else if (ObjectIdentifiers.DN_PLACE_OF_BIRTH.equals(attrType)) {
                if (placeOfBirth != null) {
                    ASN1Encodable attrVal = new DERUTF8String(placeOfBirth);
                    attrs.add(new Attribute(attrType, new DERSet(attrVal)));
                    continue;
                }
            } else if (ObjectIdentifiers.DN_GENDER.equals(attrType)) {
                if (gender != null && !gender.isEmpty()) {
                    char ch = gender.charAt(0);
                    if (!(gender.length() == 1 && (ch == 'f' || ch == 'F' || ch == 'm' || ch == 'M'))) {
                        throw new BadCertTemplateException("invalid gender " + gender);
                    }
                    ASN1Encodable attrVal = new DERPrintableString(gender);
                    attrs.add(new Attribute(attrType, new DERSet(attrVal)));
                    continue;
                }
            } else if (ObjectIdentifiers.DN_COUNTRY_OF_CITIZENSHIP.equals(attrType)) {
                if (!countryOfCitizenshipList.isEmpty()) {
                    for (String country : countryOfCitizenshipList) {
                        if (!SubjectDnSpec.isValidCountryAreaCode(country)) {
                            throw new BadCertTemplateException("invalid countryOfCitizenship code " + country);
                        }
                        ASN1Encodable attrVal = new DERPrintableString(country);
                        attrs.add(new Attribute(attrType, new DERSet(attrVal)));
                    }
                    continue;
                }
            } else if (ObjectIdentifiers.DN_COUNTRY_OF_RESIDENCE.equals(attrType)) {
                if (!countryOfResidenceList.isEmpty()) {
                    for (String country : countryOfResidenceList) {
                        if (!SubjectDnSpec.isValidCountryAreaCode(country)) {
                            throw new BadCertTemplateException("invalid countryOfResidence code " + country);
                        }
                        ASN1Encodable attrVal = new DERPrintableString(country);
                        attrs.add(new Attribute(attrType, new DERSet(attrVal)));
                    }
                    continue;
                }
            } else if (otherAttrs.containsKey(attrType)) {
                for (ASN1Encodable attrVal : otherAttrs.get(attrType)) {
                    attrs.add(new Attribute(attrType, new DERSet(attrVal)));
                }

                continue;
            }

            throw new BadCertTemplateException(
                    "could not process type " + attrType.getId() + " in extension SubjectDirectoryAttributes");
        }

        SubjectDirectoryAttributes subjDirAttrs = new SubjectDirectoryAttributes(attrs);
        ExtensionValue extValue = new ExtensionValue(extensionControls.get(type).isCritical(), subjDirAttrs);
        values.addExtension(type, extValue);
        occurences.remove(type);
    }

    // Basic Constraints
    // processed by the CA

    // Name Constraints
    type = Extension.nameConstraints;
    if (nameConstraints != null) {
        if (occurences.remove(type)) {
            values.addExtension(type, nameConstraints);
        }
    }

    // PolicyConstrains
    type = Extension.policyConstraints;
    if (policyConstraints != null) {
        if (occurences.remove(type)) {
            values.addExtension(type, policyConstraints);
        }
    }

    // ExtendedKeyUsage
    // processed by CA

    // CRL Distribution Points
    // processed by the CA

    // Inhibit anyPolicy
    type = Extension.inhibitAnyPolicy;
    if (inhibitAnyPolicy != null) {
        if (occurences.remove(type)) {
            values.addExtension(type, inhibitAnyPolicy);
        }
    }

    // Freshest CRL
    // processed by the CA

    // Authority Information Access
    // processed by the CA

    // Subject Information Access
    // processed by the CA

    // Admission
    type = ObjectIdentifiers.id_extension_admission;
    if (occurences.contains(type) && admission != null) {
        if (admission.isInputFromRequestRequired()) {
            Extension extension = (requestedExtensions == null) ? null : requestedExtensions.getExtension(type);
            if (extension == null) {
                throw new BadCertTemplateException("No Admission extension is contained in the request");
            }

            Admissions[] reqAdmissions = org.bouncycastle.asn1.isismtt.x509.AdmissionSyntax
                    .getInstance(extension.getParsedValue()).getContentsOfAdmissions();

            final int n = reqAdmissions.length;
            List<List<String>> reqRegNumsList = new ArrayList<>(n);
            for (int i = 0; i < n; i++) {
                Admissions reqAdmission = reqAdmissions[i];
                ProfessionInfo[] reqPis = reqAdmission.getProfessionInfos();
                List<String> reqNums = new ArrayList<>(reqPis.length);
                reqRegNumsList.add(reqNums);
                for (ProfessionInfo reqPi : reqPis) {
                    String reqNum = reqPi.getRegistrationNumber();
                    reqNums.add(reqNum);
                }
            }
            values.addExtension(type, admission.getExtensionValue(reqRegNumsList));
            occurences.remove(type);
        } else {
            values.addExtension(type, admission.getExtensionValue(null));
            occurences.remove(type);
        }
    }

    // OCSP Nocheck
    // processed by the CA

    // restriction
    type = ObjectIdentifiers.id_extension_restriction;
    if (restriction != null) {
        if (occurences.remove(type)) {
            values.addExtension(type, restriction);
        }
    }

    // AdditionalInformation
    type = ObjectIdentifiers.id_extension_additionalInformation;
    if (additionalInformation != null) {
        if (occurences.remove(type)) {
            values.addExtension(type, additionalInformation);
        }
    }

    // ValidityModel
    type = ObjectIdentifiers.id_extension_validityModel;
    if (validityModel != null) {
        if (occurences.remove(type)) {
            values.addExtension(type, validityModel);
        }
    }

    // PrivateKeyUsagePeriod
    type = Extension.privateKeyUsagePeriod;
    if (occurences.contains(type)) {
        Date tmpNotAfter;
        if (privateKeyUsagePeriod == null) {
            tmpNotAfter = notAfter;
        } else {
            tmpNotAfter = privateKeyUsagePeriod.add(notBefore);
            if (tmpNotAfter.after(notAfter)) {
                tmpNotAfter = notAfter;
            }
        }

        ASN1EncodableVector vec = new ASN1EncodableVector();
        vec.add(new DERTaggedObject(false, 0, new DERGeneralizedTime(notBefore)));
        vec.add(new DERTaggedObject(false, 1, new DERGeneralizedTime(tmpNotAfter)));
        ExtensionValue extValue = new ExtensionValue(extensionControls.get(type).isCritical(),
                new DERSequence(vec));
        values.addExtension(type, extValue);
        occurences.remove(type);
    }

    // QCStatements
    type = Extension.qCStatements;
    if (occurences.contains(type) && (qcStatments != null || qcStatementsOption != null)) {
        if (qcStatments != null) {
            values.addExtension(type, qcStatments);
            occurences.remove(type);
        } else if (requestedExtensions != null && qcStatementsOption != null) {
            // extract the euLimit data from request
            Extension extension = requestedExtensions.getExtension(type);
            if (extension == null) {
                throw new BadCertTemplateException("No QCStatement extension is contained in the request");
            }
            ASN1Sequence seq = ASN1Sequence.getInstance(extension.getParsedValue());

            Map<String, int[]> qcEuLimits = new HashMap<>();
            final int n = seq.size();
            for (int i = 0; i < n; i++) {
                QCStatement stmt = QCStatement.getInstance(seq.getObjectAt(i));
                if (!ObjectIdentifiers.id_etsi_qcs_QcLimitValue.equals(stmt.getStatementId())) {
                    continue;
                }

                MonetaryValue monetaryValue = MonetaryValue.getInstance(stmt.getStatementInfo());
                int amount = monetaryValue.getAmount().intValue();
                int exponent = monetaryValue.getExponent().intValue();
                Iso4217CurrencyCode currency = monetaryValue.getCurrency();
                String currencyS = currency.isAlphabetic() ? currency.getAlphabetic().toUpperCase()
                        : Integer.toString(currency.getNumeric());
                qcEuLimits.put(currencyS, new int[] { amount, exponent });
            }

            ASN1EncodableVector vec = new ASN1EncodableVector();
            for (QcStatementOption m : qcStatementsOption) {
                if (m.getStatement() != null) {
                    vec.add(m.getStatement());
                    continue;
                }

                MonetaryValueOption monetaryOption = m.getMonetaryValueOption();
                String currencyS = monetaryOption.getCurrencyString();
                int[] limit = qcEuLimits.get(currencyS);
                if (limit == null) {
                    throw new BadCertTemplateException(
                            "no EuLimitValue is specified for currency '" + currencyS + "'");
                }

                int amount = limit[0];
                Range2Type range = monetaryOption.getAmountRange();
                if (amount < range.getMin() || amount > range.getMax()) {
                    throw new BadCertTemplateException("amount for currency '" + currencyS + "' is not within ["
                            + range.getMin() + ", " + range.getMax() + "]");
                }

                int exponent = limit[1];
                range = monetaryOption.getExponentRange();
                if (exponent < range.getMin() || exponent > range.getMax()) {
                    throw new BadCertTemplateException("exponent for currency '" + currencyS
                            + "' is not within [" + range.getMin() + ", " + range.getMax() + "]");
                }

                MonetaryValue monetaryVale = new MonetaryValue(monetaryOption.getCurrency(), amount, exponent);
                QCStatement qcStatment = new QCStatement(m.getStatementId(), monetaryVale);
                vec.add(qcStatment);
            }

            ExtensionValue extValue = new ExtensionValue(extensionControls.get(type).isCritical(),
                    new DERSequence(vec));
            values.addExtension(type, extValue);
            occurences.remove(type);
        } else {
            throw new RuntimeException("should not reach here");
        }
    }

    // BiometricData
    type = Extension.biometricInfo;
    if (occurences.contains(type) && biometricInfo != null) {
        Extension extension = (requestedExtensions == null) ? null : requestedExtensions.getExtension(type);
        if (extension == null) {
            throw new BadCertTemplateException("no biometricInfo extension is contained in the request");
        }
        ASN1Sequence seq = ASN1Sequence.getInstance(extension.getParsedValue());
        final int n = seq.size();
        if (n < 1) {
            throw new BadCertTemplateException("biometricInfo extension in request contains empty sequence");
        }

        ASN1EncodableVector vec = new ASN1EncodableVector();

        for (int i = 0; i < n; i++) {
            BiometricData bd = BiometricData.getInstance(seq.getObjectAt(i));
            TypeOfBiometricData bdType = bd.getTypeOfBiometricData();
            if (!biometricInfo.isTypePermitted(bdType)) {
                throw new BadCertTemplateException(
                        "biometricInfo[" + i + "].typeOfBiometricData is not permitted");
            }

            ASN1ObjectIdentifier hashAlgo = bd.getHashAlgorithm().getAlgorithm();
            if (!biometricInfo.isHashAlgorithmPermitted(hashAlgo)) {
                throw new BadCertTemplateException("biometricInfo[" + i + "].hashAlgorithm is not permitted");
            }

            int expHashValueSize;
            try {
                expHashValueSize = AlgorithmUtil.getHashOutputSizeInOctets(hashAlgo);
            } catch (NoSuchAlgorithmException ex) {
                throw new CertprofileException("should not happen, unknown hash algorithm " + hashAlgo);
            }

            byte[] hashValue = bd.getBiometricDataHash().getOctets();
            if (hashValue.length != expHashValueSize) {
                throw new BadCertTemplateException(
                        "biometricInfo[" + i + "].biometricDataHash has incorrect length");
            }

            DERIA5String sourceDataUri = bd.getSourceDataUri();
            switch (biometricInfo.getSourceDataUriOccurrence()) {
            case FORBIDDEN:
                sourceDataUri = null;
                break;
            case REQUIRED:
                if (sourceDataUri == null) {
                    throw new BadCertTemplateException("biometricInfo[" + i
                            + "].sourceDataUri is not specified in request but is required");
                }
                break;
            case OPTIONAL:
                break;
            default:
                throw new BadCertTemplateException("could not reach here, unknown tripleState");
            }

            AlgorithmIdentifier newHashAlg = new AlgorithmIdentifier(hashAlgo, DERNull.INSTANCE);
            BiometricData newBiometricData = new BiometricData(bdType, newHashAlg,
                    new DEROctetString(hashValue), sourceDataUri);
            vec.add(newBiometricData);
        }

        ExtensionValue extValue = new ExtensionValue(extensionControls.get(type).isCritical(),
                new DERSequence(vec));
        values.addExtension(type, extValue);
        occurences.remove(type);
    }

    // TlsFeature
    type = ObjectIdentifiers.id_pe_tlsfeature;
    if (tlsFeature != null) {
        if (occurences.remove(type)) {
            values.addExtension(type, tlsFeature);
        }
    }

    // AuthorizationTemplate
    type = ObjectIdentifiers.id_xipki_ext_authorizationTemplate;
    if (authorizationTemplate != null) {
        if (occurences.remove(type)) {
            values.addExtension(type, authorizationTemplate);
        }
    }

    // SMIME
    type = ObjectIdentifiers.id_smimeCapabilities;
    if (smimeCapabilities != null) {
        if (occurences.remove(type)) {
            values.addExtension(type, smimeCapabilities);
        }
    }

    // constant extensions
    if (constantExtensions != null) {
        for (ASN1ObjectIdentifier m : constantExtensions.keySet()) {
            if (!occurences.remove(m)) {
                continue;
            }

            ExtensionValue extensionValue = constantExtensions.get(m);
            if (extensionValue != null) {
                values.addExtension(m, extensionValue);
            }
        }
    }

    return values;
}

From source file:org.xipki.pki.ca.qa.ExtensionsChecker.java

License:Open Source License

private void checkExtensionQcStatements(final StringBuilder failureMsg, final byte[] extensionValue,
        final Extensions requestedExtensions, final ExtensionControl extControl) {
    QcStatements conf = qcStatements;//from   ww w  .  j av  a 2s  .c  om
    if (conf == null) {
        byte[] expected = getExpectedExtValue(Extension.qCStatements, requestedExtensions, extControl);
        if (!Arrays.equals(expected, extensionValue)) {
            addViolation(failureMsg, "extension values", extensionValue,
                    (expected == null) ? "not present" : hex(expected));
        }
        return;
    }

    final int expSize = conf.getQcStatement().size();
    ASN1Sequence extValue = ASN1Sequence.getInstance(extensionValue);
    final int isSize = extValue.size();
    if (isSize != expSize) {
        addViolation(failureMsg, "number of statements", isSize, expSize);
        return;
    }

    // extract the euLimit and pdsLocations data from request
    Map<String, int[]> reqQcEuLimits = new HashMap<>();
    Extension reqExtension = (requestedExtensions == null) ? null
            : requestedExtensions.getExtension(Extension.qCStatements);
    if (reqExtension != null) {
        ASN1Sequence seq = ASN1Sequence.getInstance(reqExtension.getParsedValue());

        final int n = seq.size();
        for (int j = 0; j < n; j++) {
            QCStatement stmt = QCStatement.getInstance(seq.getObjectAt(j));
            if (ObjectIdentifiers.id_etsi_qcs_QcLimitValue.equals(stmt.getStatementId())) {
                MonetaryValue monetaryValue = MonetaryValue.getInstance(stmt.getStatementInfo());
                int amount = monetaryValue.getAmount().intValue();
                int exponent = monetaryValue.getExponent().intValue();
                Iso4217CurrencyCode currency = monetaryValue.getCurrency();
                String currencyS = currency.isAlphabetic() ? currency.getAlphabetic().toUpperCase()
                        : Integer.toString(currency.getNumeric());
                reqQcEuLimits.put(currencyS, new int[] { amount, exponent });
            }
        }
    }

    for (int i = 0; i < expSize; i++) {
        QCStatement is = QCStatement.getInstance(extValue.getObjectAt(i));
        QcStatementType exp = conf.getQcStatement().get(i);
        if (!is.getStatementId().getId().equals(exp.getStatementId().getValue())) {
            addViolation(failureMsg, "statmentId[" + i + "]", is.getStatementId().getId(),
                    exp.getStatementId().getValue());
            continue;
        }

        if (exp.getStatementValue() == null) {
            if (is.getStatementInfo() != null) {
                addViolation(failureMsg, "statmentInfo[" + i + "]", "present", "absent");
            }
            continue;
        }

        if (is.getStatementInfo() == null) {
            addViolation(failureMsg, "statmentInfo[" + i + "]", "absent", "present");
            continue;
        }

        QcStatementValueType expStatementValue = exp.getStatementValue();
        try {
            if (expStatementValue.getConstant() != null) {
                byte[] expValue = expStatementValue.getConstant().getValue();
                byte[] isValue = is.getStatementInfo().toASN1Primitive().getEncoded();
                if (!Arrays.equals(isValue, expValue)) {
                    addViolation(failureMsg, "statementInfo[" + i + "]", hex(isValue), hex(expValue));
                }
            } else if (expStatementValue.getQcRetentionPeriod() != null) {
                String isValue = ASN1Integer.getInstance(is.getStatementInfo()).toString();
                String expValue = expStatementValue.getQcRetentionPeriod().toString();
                if (!isValue.equals(expValue)) {
                    addViolation(failureMsg, "statementInfo[" + i + "]", isValue, expValue);
                }
            } else if (expStatementValue.getPdsLocations() != null) {
                Set<String> pdsLocations = new HashSet<>();
                ASN1Sequence pdsLocsSeq = ASN1Sequence.getInstance(is.getStatementInfo());
                int size = pdsLocsSeq.size();
                for (int k = 0; k < size; k++) {
                    ASN1Sequence pdsLocSeq = ASN1Sequence.getInstance(pdsLocsSeq.getObjectAt(k));
                    int size2 = pdsLocSeq.size();
                    if (size2 != 2) {
                        throw new IllegalArgumentException("sequence size is " + size2 + " but expected 2");
                    }
                    String url = DERIA5String.getInstance(pdsLocSeq.getObjectAt(0)).getString();
                    String lang = DERPrintableString.getInstance(pdsLocSeq.getObjectAt(1)).getString();
                    pdsLocations.add("url=" + url + ",lang=" + lang);
                }

                PdsLocationsType pdsLocationsConf = expStatementValue.getPdsLocations();
                Set<String> expectedPdsLocations = new HashSet<>();
                for (PdsLocationType m : pdsLocationsConf.getPdsLocation()) {
                    expectedPdsLocations.add("url=" + m.getUrl() + ",lang=" + m.getLanguage());
                }

                Set<String> diffs = strInBnotInA(expectedPdsLocations, pdsLocations);
                if (CollectionUtil.isNonEmpty(diffs)) {
                    failureMsg.append("statementInfo[" + i + "]: ").append(diffs.toString());
                    failureMsg.append(" are present but not expected; ");
                }

                diffs = strInBnotInA(pdsLocations, expectedPdsLocations);
                if (CollectionUtil.isNonEmpty(diffs)) {
                    failureMsg.append("statementInfo[" + i + "]: ").append(diffs.toString());
                    failureMsg.append(" are absent but are required; ");
                }
            } else if (expStatementValue.getQcEuLimitValue() != null) {
                QcEuLimitValueType euLimitConf = expStatementValue.getQcEuLimitValue();
                String expCurrency = euLimitConf.getCurrency().toUpperCase();
                int[] expAmountExp = reqQcEuLimits.get(expCurrency);

                Range2Type range = euLimitConf.getAmount();
                int value;
                if (range.getMin() == range.getMax()) {
                    value = range.getMin();
                } else if (expAmountExp != null) {
                    value = expAmountExp[0];
                } else {
                    failureMsg.append("found no QcEuLimit for currency '").append(expCurrency).append("'; ");
                    return;
                }
                // CHECKSTYLE:SKIP
                String expAmount = Integer.toString(value);

                range = euLimitConf.getExponent();
                if (range.getMin() == range.getMax()) {
                    value = range.getMin();
                } else if (expAmountExp != null) {
                    value = expAmountExp[1];
                } else {
                    failureMsg.append("found no QcEuLimit for currency '").append(expCurrency).append("'; ");
                    return;
                }
                String expExponent = Integer.toString(value);

                MonetaryValue monterayValue = MonetaryValue.getInstance(is.getStatementInfo());
                Iso4217CurrencyCode currency = monterayValue.getCurrency();
                String isCurrency = currency.isAlphabetic() ? currency.getAlphabetic()
                        : Integer.toString(currency.getNumeric());
                String isAmount = monterayValue.getAmount().toString();
                String isExponent = monterayValue.getExponent().toString();
                if (!isCurrency.equals(expCurrency)) {
                    addViolation(failureMsg, "statementInfo[" + i + "].qcEuLimit.currency", isCurrency,
                            expCurrency);
                }
                if (!isAmount.equals(expAmount)) {
                    addViolation(failureMsg, "statementInfo[" + i + "].qcEuLimit.amount", isAmount, expAmount);
                }
                if (!isExponent.equals(expExponent)) {
                    addViolation(failureMsg, "statementInfo[" + i + "].qcEuLimit.exponent", isExponent,
                            expExponent);
                }
            } else {
                throw new RuntimeException("statementInfo[" + i + "]should not reach here");
            }
        } catch (IOException ex) {
            failureMsg.append("statementInfo[").append(i).append("] has incorrect syntax; ");
        }
    }
}