Example usage for org.bouncycastle.asn1.x509 Extension qCStatements

List of usage examples for org.bouncycastle.asn1.x509 Extension qCStatements

Introduction

In this page you can find the example usage for org.bouncycastle.asn1.x509 Extension qCStatements.

Prototype

ASN1ObjectIdentifier qCStatements

To view the source code for org.bouncycastle.asn1.x509 Extension qCStatements.

Click Source Link

Document

QCStatements

Usage

From source file:org.xipki.commons.security.shell.CertRequestGenCommandSupport.java

License:Open Source License

@Override
protected Object doExecute() throws Exception {
    hashAlgo = hashAlgo.trim().toUpperCase();
    if (hashAlgo.indexOf('-') != -1) {
        hashAlgo = hashAlgo.replaceAll("-", "");
    }/* ww w  .j  av a  2s. c  o m*/

    if (needExtensionTypes == null) {
        needExtensionTypes = new LinkedList<>();
    }

    if (wantExtensionTypes == null) {
        wantExtensionTypes = new LinkedList<>();
    }

    // SubjectAltNames
    List<Extension> extensions = new LinkedList<>();

    ASN1OctetString extnValue = createExtnValueSubjectAltName();
    if (extnValue != null) {
        ASN1ObjectIdentifier oid = Extension.subjectAlternativeName;
        extensions.add(new Extension(oid, false, extnValue));
        needExtensionTypes.add(oid.getId());
    }

    // SubjectInfoAccess
    extnValue = createExtnValueSubjectInfoAccess();
    if (extnValue != null) {
        ASN1ObjectIdentifier oid = Extension.subjectInfoAccess;
        extensions.add(new Extension(oid, false, extnValue));
        needExtensionTypes.add(oid.getId());
    }

    // Keyusage
    if (isNotEmpty(keyusages)) {
        Set<KeyUsage> usages = new HashSet<>();
        for (String usage : keyusages) {
            usages.add(KeyUsage.getKeyUsage(usage));
        }
        org.bouncycastle.asn1.x509.KeyUsage extValue = X509Util.createKeyUsage(usages);
        ASN1ObjectIdentifier extType = Extension.keyUsage;
        extensions.add(new Extension(extType, false, extValue.getEncoded()));
        needExtensionTypes.add(extType.getId());
    }

    // ExtendedKeyusage
    if (isNotEmpty(extkeyusages)) {
        ExtendedKeyUsage extValue = X509Util.createExtendedUsage(textToAsn1ObjectIdentifers(extkeyusages));
        ASN1ObjectIdentifier extType = Extension.extendedKeyUsage;
        extensions.add(new Extension(extType, false, extValue.getEncoded()));
        needExtensionTypes.add(extType.getId());
    }

    // QcEuLimitValue
    if (isNotEmpty(qcEuLimits)) {
        ASN1EncodableVector vec = new ASN1EncodableVector();
        for (String m : qcEuLimits) {
            StringTokenizer st = new StringTokenizer(m, ":");
            try {
                String currencyS = st.nextToken();
                String amountS = st.nextToken();
                String exponentS = st.nextToken();

                Iso4217CurrencyCode currency;
                try {
                    int intValue = Integer.parseInt(currencyS);
                    currency = new Iso4217CurrencyCode(intValue);
                } catch (NumberFormatException ex) {
                    currency = new Iso4217CurrencyCode(currencyS);
                }

                int amount = Integer.parseInt(amountS);
                int exponent = Integer.parseInt(exponentS);

                MonetaryValue monterayValue = new MonetaryValue(currency, amount, exponent);
                QCStatement statment = new QCStatement(ObjectIdentifiers.id_etsi_qcs_QcLimitValue,
                        monterayValue);
                vec.add(statment);
            } catch (Exception ex) {
                throw new Exception("invalid qc-eu-limit '" + m + "'");
            }
        }

        ASN1ObjectIdentifier extType = Extension.qCStatements;
        ASN1Sequence extValue = new DERSequence(vec);
        extensions.add(new Extension(extType, false, extValue.getEncoded()));
        needExtensionTypes.add(extType.getId());
    }

    // biometricInfo
    if (biometricType != null && biometricHashAlgo != null && biometricFile != null) {
        TypeOfBiometricData tmpBiometricType = StringUtil.isNumber(biometricType)
                ? new TypeOfBiometricData(Integer.parseInt(biometricType))
                : new TypeOfBiometricData(new ASN1ObjectIdentifier(biometricType));

        ASN1ObjectIdentifier tmpBiometricHashAlgo = AlgorithmUtil.getHashAlg(biometricHashAlgo);
        byte[] biometricBytes = IoUtil.read(biometricFile);
        MessageDigest md = MessageDigest.getInstance(tmpBiometricHashAlgo.getId());
        md.reset();
        byte[] tmpBiometricDataHash = md.digest(biometricBytes);

        DERIA5String tmpSourceDataUri = null;
        if (biometricUri != null) {
            tmpSourceDataUri = new DERIA5String(biometricUri);
        }
        BiometricData biometricData = new BiometricData(tmpBiometricType,
                new AlgorithmIdentifier(tmpBiometricHashAlgo), new DEROctetString(tmpBiometricDataHash),
                tmpSourceDataUri);

        ASN1EncodableVector vec = new ASN1EncodableVector();
        vec.add(biometricData);

        ASN1ObjectIdentifier extType = Extension.biometricInfo;
        ASN1Sequence extValue = new DERSequence(vec);
        extensions.add(new Extension(extType, false, extValue.getEncoded()));
        needExtensionTypes.add(extType.getId());
    } else if (biometricType == null && biometricHashAlgo == null && biometricFile == null) {
        // Do nothing
    } else {
        throw new Exception("either all of biometric triples (type, hash algo, file)"
                + " must be set or none of them should be set");
    }

    for (Extension addExt : getAdditionalExtensions()) {
        extensions.add(addExt);
    }

    needExtensionTypes.addAll(getAdditionalNeedExtensionTypes());
    wantExtensionTypes.addAll(getAdditionalWantExtensionTypes());

    if (isNotEmpty(needExtensionTypes) || isNotEmpty(wantExtensionTypes)) {
        ExtensionExistence ee = new ExtensionExistence(textToAsn1ObjectIdentifers(needExtensionTypes),
                textToAsn1ObjectIdentifers(wantExtensionTypes));
        extensions.add(new Extension(ObjectIdentifiers.id_xipki_ext_cmpRequestExtensions, false,
                ee.toASN1Primitive().getEncoded()));
    }

    ConcurrentContentSigner signer = getSigner(new SignatureAlgoControl(rsaMgf1, dsaPlain));

    Map<ASN1ObjectIdentifier, ASN1Encodable> attributes = new HashMap<>();
    if (CollectionUtil.isNonEmpty(extensions)) {
        attributes.put(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest,
                new Extensions(extensions.toArray(new Extension[0])));
    }

    if (StringUtil.isNotBlank(challengePassword)) {
        attributes.put(PKCSObjectIdentifiers.pkcs_9_at_challengePassword,
                new DERPrintableString(challengePassword));
    }

    SubjectPublicKeyInfo subjectPublicKeyInfo;
    if (signer.getCertificate() != null) {
        Certificate cert = Certificate.getInstance(signer.getCertificate().getEncoded());
        subjectPublicKeyInfo = cert.getSubjectPublicKeyInfo();
    } else {
        subjectPublicKeyInfo = KeyUtil.createSubjectPublicKeyInfo(signer.getPublicKey());
    }

    X500Name subjectDn = getSubject(subject);
    PKCS10CertificationRequest csr = generateRequest(signer, subjectPublicKeyInfo, subjectDn, attributes);

    File file = new File(outputFilename);
    saveVerbose("saved CSR to file", file, csr.getEncoded());
    return null;
}

From source file:org.xipki.console.karaf.impl.completer.ExtensionNameCompleterImpl.java

License:Open Source License

public ExtensionNameCompleterImpl() {
    List<ASN1ObjectIdentifier> oids = new LinkedList<>();
    oids.add(ObjectIdentifiers.id_extension_pkix_ocsp_nocheck);
    oids.add(ObjectIdentifiers.id_extension_admission);
    oids.add(Extension.auditIdentity);
    oids.add(Extension.authorityInfoAccess);
    oids.add(Extension.authorityKeyIdentifier);
    oids.add(Extension.basicConstraints);
    oids.add(Extension.biometricInfo);
    oids.add(Extension.certificateIssuer);
    oids.add(Extension.certificatePolicies);
    oids.add(Extension.cRLDistributionPoints);
    oids.add(Extension.cRLNumber);
    oids.add(Extension.deltaCRLIndicator);
    oids.add(Extension.extendedKeyUsage);
    oids.add(Extension.freshestCRL);
    oids.add(Extension.inhibitAnyPolicy);
    oids.add(Extension.instructionCode);
    oids.add(Extension.invalidityDate);
    oids.add(Extension.issuerAlternativeName);
    oids.add(Extension.issuingDistributionPoint);
    oids.add(Extension.keyUsage);
    oids.add(Extension.logoType);
    oids.add(Extension.nameConstraints);
    oids.add(Extension.noRevAvail);
    oids.add(Extension.policyConstraints);
    oids.add(Extension.policyMappings);
    oids.add(Extension.privateKeyUsagePeriod);
    oids.add(Extension.qCStatements);
    oids.add(Extension.reasonCode);
    oids.add(Extension.subjectAlternativeName);
    oids.add(Extension.subjectDirectoryAttributes);
    oids.add(Extension.subjectInfoAccess);
    oids.add(Extension.subjectKeyIdentifier);
    oids.add(Extension.targetInformation);

    StringBuilder enums = new StringBuilder();

    for (ASN1ObjectIdentifier oid : oids) {
        String name = ObjectIdentifiers.getName(oid);
        if (StringUtil.isBlank(name)) {
            name = oid.getId();//from w  ww .  ja v a  2s. c  o m
        }
        enums.append(name).append(",");
    }
    enums.deleteCharAt(enums.length() - 1);
    setTokens(enums.toString());
}

From source file:org.xipki.pki.ca.certprofile.test.ProfileConfCreatorDemo.java

License:Open Source License

private static X509ProfileType certprofileQc() throws Exception {
    X509ProfileType profile = getBaseProfile("Certprofile QC", X509CertLevel.EndEntity, "5y", false);

    // Subject/*from   www  . j av a2 s .co m*/
    Subject subject = profile.getSubject();
    subject.setIncSerialNumber(false);

    List<RdnType> rdnControls = subject.getRdn();
    rdnControls.add(createRdn(ObjectIdentifiers.DN_C, 1, 1, new String[] { "DE|FR" }, null, null));
    rdnControls.add(createRdn(ObjectIdentifiers.DN_O, 1, 1));
    rdnControls.add(createRdn(ObjectIdentifiers.DN_organizationIdentifier, 0, 1));
    rdnControls.add(createRdn(ObjectIdentifiers.DN_OU, 0, 1));
    rdnControls.add(createRdn(ObjectIdentifiers.DN_SN, 0, 1, new String[] { REGEX_SN }, null, null));
    rdnControls.add(createRdn(ObjectIdentifiers.DN_CN, 1, 1));

    // Extensions
    // Extensions - general
    ExtensionsType extensions = profile.getExtensions();

    // Extensions - controls
    List<ExtensionType> list = extensions.getExtension();
    list.add(createExtension(Extension.subjectKeyIdentifier, true, false, null));
    list.add(createExtension(Extension.cRLDistributionPoints, false, false, null));
    list.add(createExtension(Extension.freshestCRL, false, false, null));

    // Extensions - basicConstraints
    ExtensionValueType extensionValue = null;
    list.add(createExtension(Extension.basicConstraints, true, false, extensionValue));

    // Extensions - AuthorityInfoAccess
    extensionValue = createAuthorityInfoAccess();
    list.add(createExtension(Extension.authorityInfoAccess, true, false, extensionValue));

    // Extensions - AuthorityKeyIdentifier
    extensionValue = createAuthorityKeyIdentifier(true);
    list.add(createExtension(Extension.authorityKeyIdentifier, true, false, extensionValue));

    // Extensions - keyUsage
    extensionValue = createKeyUsages(new KeyUsageEnum[] { KeyUsageEnum.CONTENT_COMMITMENT }, null);
    list.add(createExtension(Extension.keyUsage, true, true, extensionValue));

    // Extensions - extenedKeyUsage
    extensionValue = createExtendedKeyUsage(new ASN1ObjectIdentifier[] { ObjectIdentifiers.id_kp_timeStamping },
            null);
    list.add(createExtension(Extension.extendedKeyUsage, true, true, extensionValue));

    // privateKeyUsagePeriod
    extensionValue = createPrivateKeyUsagePeriod("3y");
    list.add(createExtension(Extension.privateKeyUsagePeriod, true, false, extensionValue));

    // QcStatements
    extensionValue = createQcStatements(false);
    list.add(createExtension(Extension.qCStatements, true, false, extensionValue));

    return profile;
}

From source file:org.xipki.pki.ca.certprofile.test.ProfileConfCreatorDemo.java

License:Open Source License

private static X509ProfileType certprofileEeComplex() throws Exception {
    X509ProfileType profile = getBaseProfile("Certprofile EE complex", X509CertLevel.EndEntity, "5y", true);

    // Subject/*  w ww .jav  a 2s. c o m*/
    Subject subject = profile.getSubject();
    subject.setIncSerialNumber(false);
    subject.setKeepRdnOrder(true);
    List<RdnType> rdnControls = subject.getRdn();
    rdnControls.add(createRdn(ObjectIdentifiers.DN_CN, 1, 1));
    rdnControls.add(createRdn(ObjectIdentifiers.DN_C, 1, 1, new String[] { "DE|FR" }, null, null));
    rdnControls.add(createRdn(ObjectIdentifiers.DN_O, 1, 1));
    rdnControls.add(createRdn(ObjectIdentifiers.DN_OU, 0, 1));
    rdnControls.add(createRdn(ObjectIdentifiers.DN_SN, 0, 1, new String[] { REGEX_SN }, null, null));
    rdnControls.add(createRdn(ObjectIdentifiers.DN_DATE_OF_BIRTH, 0, 1));
    rdnControls.add(createRdn(ObjectIdentifiers.DN_POSTAL_ADDRESS, 0, 1));
    rdnControls.add(createRdn(ObjectIdentifiers.DN_UNIQUE_IDENTIFIER, 1, 1));

    // Extensions
    // Extensions - general
    ExtensionsType extensions = profile.getExtensions();

    // Extensions - controls
    List<ExtensionType> list = extensions.getExtension();
    list.add(createExtension(Extension.subjectKeyIdentifier, true, false, null));
    list.add(createExtension(Extension.cRLDistributionPoints, false, false, null));
    list.add(createExtension(Extension.freshestCRL, false, false, null));

    // Extensions - basicConstraints
    ExtensionValueType extensionValue = null;
    list.add(createExtension(Extension.basicConstraints, true, false, extensionValue));

    // Extensions - AuthorityInfoAccess
    extensionValue = createAuthorityInfoAccess();
    list.add(createExtension(Extension.authorityInfoAccess, true, false, extensionValue));

    // Extensions - AuthorityKeyIdentifier
    extensionValue = createAuthorityKeyIdentifier(true);
    list.add(createExtension(Extension.authorityKeyIdentifier, true, false, extensionValue));

    // Extensions - keyUsage
    extensionValue = createKeyUsages(new KeyUsageEnum[] { KeyUsageEnum.DIGITAL_SIGNATURE,
            KeyUsageEnum.DATA_ENCIPHERMENT, KeyUsageEnum.KEY_ENCIPHERMENT }, null);
    list.add(createExtension(Extension.keyUsage, true, true, extensionValue));

    // Extensions - extenedKeyUsage
    extensionValue = createExtendedKeyUsage(new ASN1ObjectIdentifier[] { ObjectIdentifiers.id_kp_serverAuth },
            new ASN1ObjectIdentifier[] { ObjectIdentifiers.id_kp_clientAuth });
    list.add(createExtension(Extension.extendedKeyUsage, true, false, extensionValue));

    // Extension - subjectDirectoryAttributes
    SubjectDirectoryAttributs subjectDirAttrType = new SubjectDirectoryAttributs();
    List<OidWithDescType> attrTypes = subjectDirAttrType.getType();
    attrTypes.add(createOidType(ObjectIdentifiers.DN_COUNTRY_OF_CITIZENSHIP));
    attrTypes.add(createOidType(ObjectIdentifiers.DN_COUNTRY_OF_RESIDENCE));
    attrTypes.add(createOidType(ObjectIdentifiers.DN_GENDER));
    attrTypes.add(createOidType(ObjectIdentifiers.DN_DATE_OF_BIRTH));
    attrTypes.add(createOidType(ObjectIdentifiers.DN_PLACE_OF_BIRTH));
    extensionValue = createExtensionValueType(subjectDirAttrType);
    list.add(createExtension(Extension.subjectDirectoryAttributes, true, false, extensionValue));

    // Extension - Admission
    AdmissionSyntax admissionSyntax = new AdmissionSyntax();
    admissionSyntax.setAdmissionAuthority(
            new GeneralName(new X500Name("C=DE,CN=admissionAuthority level 1")).getEncoded());

    AdmissionsType admissions = new AdmissionsType();
    admissions.setAdmissionAuthority(
            new GeneralName(new X500Name("C=DE,CN=admissionAuthority level 2")).getEncoded());

    NamingAuthorityType namingAuthorityL2 = new NamingAuthorityType();
    namingAuthorityL2.setOid(createOidType(new ASN1ObjectIdentifier("1.2.3.4.5")));
    namingAuthorityL2.setUrl("http://naming-authority-level2.example.org");
    namingAuthorityL2.setText("namingAuthrityText level 2");
    admissions.setNamingAuthority(namingAuthorityL2);

    admissionSyntax.getContentsOfAdmissions().add(admissions);

    ProfessionInfoType pi = new ProfessionInfoType();
    admissions.getProfessionInfo().add(pi);

    pi.getProfessionOid().add(createOidType(new ASN1ObjectIdentifier("1.2.3.4"), "demo oid"));
    pi.getProfessionItem().add("demo item");

    NamingAuthorityType namingAuthorityL3 = new NamingAuthorityType();
    namingAuthorityL3.setOid(createOidType(new ASN1ObjectIdentifier("1.2.3.4.5")));
    namingAuthorityL3.setUrl("http://naming-authority-level3.example.org");
    namingAuthorityL3.setText("namingAuthrityText level 3");
    pi.setNamingAuthority(namingAuthorityL3);
    pi.setAddProfessionInfo(new byte[] { 1, 2, 3, 4 });

    RegistrationNumber regNum = new RegistrationNumber();
    pi.setRegistrationNumber(regNum);
    regNum.setRegex("a*b");

    // check the syntax
    XmlX509CertprofileUtil.buildAdmissionSyntax(false, admissionSyntax);

    extensionValue = createExtensionValueType(admissionSyntax);
    list.add(createExtension(ObjectIdentifiers.id_extension_admission, true, false, extensionValue));

    // restriction
    extensionValue = createRestriction(DirectoryStringType.UTF_8_STRING, "demo restriction");
    list.add(createExtension(ObjectIdentifiers.id_extension_restriction, true, false, extensionValue));

    // additionalInformation
    extensionValue = createAdditionalInformation(DirectoryStringType.UTF_8_STRING,
            "demo additional information");
    list.add(
            createExtension(ObjectIdentifiers.id_extension_additionalInformation, true, false, extensionValue));

    // validationModel
    extensionValue = createConstantExtValue(new ASN1ObjectIdentifier("1.3.6.1.4.1.8301.3.5.1").getEncoded(),
            "chain");
    list.add(createExtension(ObjectIdentifiers.id_extension_validityModel, true, false, extensionValue));

    // privateKeyUsagePeriod
    extensionValue = createPrivateKeyUsagePeriod("3y");
    list.add(createExtension(Extension.privateKeyUsagePeriod, true, false, extensionValue));

    // QcStatements
    extensionValue = createQcStatements(true);
    list.add(createExtension(Extension.qCStatements, true, false, extensionValue));

    // biometricInfo
    extensionValue = createBiometricInfo();
    list.add(createExtension(Extension.biometricInfo, true, false, extensionValue));

    // authorizationTemplate
    extensionValue = createAuthorizationTemplate();
    list.add(
            createExtension(ObjectIdentifiers.id_xipki_ext_authorizationTemplate, true, false, extensionValue));

    // SubjectAltName
    SubjectAltName subjectAltNameMode = new SubjectAltName();

    OtherName otherName = new OtherName();
    otherName.getType().add(createOidType(new ASN1ObjectIdentifier("1.2.3.1"), "dummy oid 1"));
    otherName.getType().add(createOidType(new ASN1ObjectIdentifier("1.2.3.2"), "dummy oid 2"));
    subjectAltNameMode.setOtherName(otherName);
    subjectAltNameMode.setRfc822Name("");
    subjectAltNameMode.setDnsName("");
    subjectAltNameMode.setDirectoryName("");
    subjectAltNameMode.setEdiPartyName("");
    subjectAltNameMode.setUniformResourceIdentifier("");
    subjectAltNameMode.setIpAddress("");
    subjectAltNameMode.setRegisteredID("");

    extensionValue = createExtensionValueType(subjectAltNameMode);
    list.add(createExtension(Extension.subjectAlternativeName, true, false, extensionValue));

    // SubjectInfoAccess
    List<ASN1ObjectIdentifier> accessMethods = new LinkedList<>();
    accessMethods.add(ObjectIdentifiers.id_ad_caRepository);
    for (int i = 0; i < 10; i++) {
        accessMethods.add(new ASN1ObjectIdentifier("2.3.4." + (i + 1)));
    }

    SubjectInfoAccess subjectInfoAccessMode = new SubjectInfoAccess();
    for (ASN1ObjectIdentifier accessMethod : accessMethods) {
        SubjectInfoAccess.Access access = new SubjectInfoAccess.Access();
        subjectInfoAccessMode.getAccess().add(access);
        access.setAccessMethod(createOidType(accessMethod));

        GeneralNameType accessLocation = new GeneralNameType();
        access.setAccessLocation(accessLocation);

        otherName = new OtherName();
        otherName.getType().add(createOidType(new ASN1ObjectIdentifier("1.2.3.1"), "dummy oid 1"));
        otherName.getType().add(createOidType(new ASN1ObjectIdentifier("1.2.3.2"), "dummy oid 2"));
        accessLocation.setOtherName(otherName);
        accessLocation.setRfc822Name("");
        accessLocation.setDnsName("");
        accessLocation.setDirectoryName("");
        accessLocation.setEdiPartyName("");
        accessLocation.setUniformResourceIdentifier("");
        accessLocation.setIpAddress("");
        accessLocation.setRegisteredID("");
    }

    extensionValue = createExtensionValueType(subjectInfoAccessMode);
    list.add(createExtension(Extension.subjectInfoAccess, true, false, extensionValue));
    return profile;
}

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

License:Open Source License

private void initQcStatements(ExtensionsType extensionsType) throws CertprofileException {
    ASN1ObjectIdentifier type = Extension.qCStatements;
    if (!extensionControls.containsKey(type)) {
        return;/*  w ww . j  a v a 2s  . c  o  m*/
    }

    QcStatements extConf = (QcStatements) getExtensionValue(type, extensionsType, QcStatements.class);

    if (extConf == null) {
        return;
    }

    List<QcStatementType> qcStatementTypes = extConf.getQcStatement();

    this.qcStatementsOption = new ArrayList<>(qcStatementTypes.size());
    Set<String> currencyCodes = new HashSet<>();
    boolean requireInfoFromReq = false;

    for (QcStatementType m : qcStatementTypes) {
        ASN1ObjectIdentifier qcStatementId = new ASN1ObjectIdentifier(m.getStatementId().getValue());
        QcStatementOption qcStatementOption;

        QcStatementValueType statementValue = m.getStatementValue();
        if (statementValue == null) {
            QCStatement qcStatment = new QCStatement(qcStatementId);
            qcStatementOption = new QcStatementOption(qcStatment);
        } else if (statementValue.getQcRetentionPeriod() != null) {
            QCStatement qcStatment = new QCStatement(qcStatementId,
                    new ASN1Integer(statementValue.getQcRetentionPeriod()));
            qcStatementOption = new QcStatementOption(qcStatment);
        } else if (statementValue.getConstant() != null) {
            ASN1Encodable constantStatementValue;
            try {
                constantStatementValue = new ASN1StreamParser(statementValue.getConstant().getValue())
                        .readObject();
            } catch (IOException ex) {
                throw new CertprofileException("can not parse the constant value of QcStatement");
            }
            QCStatement qcStatment = new QCStatement(qcStatementId, constantStatementValue);
            qcStatementOption = new QcStatementOption(qcStatment);
        } else if (statementValue.getQcEuLimitValue() != null) {
            QcEuLimitValueType euLimitType = statementValue.getQcEuLimitValue();
            String tmpCurrency = euLimitType.getCurrency().toUpperCase();
            if (currencyCodes.contains(tmpCurrency)) {
                throw new CertprofileException("Duplicated definition of qcStatments with QCEuLimitValue for "
                        + "the currency " + tmpCurrency);
            }

            Iso4217CurrencyCode currency = StringUtil.isNumber(tmpCurrency)
                    ? new Iso4217CurrencyCode(Integer.parseInt(tmpCurrency))
                    : new Iso4217CurrencyCode(tmpCurrency);

            Range2Type r1 = euLimitType.getAmount();
            Range2Type r2 = euLimitType.getExponent();
            if (r1.getMin() == r1.getMax() && r2.getMin() == r2.getMax()) {
                MonetaryValue monetaryValue = new MonetaryValue(currency, r1.getMin(), r2.getMin());
                QCStatement qcStatement = new QCStatement(qcStatementId, monetaryValue);
                qcStatementOption = new QcStatementOption(qcStatement);
            } else {
                MonetaryValueOption monetaryValueOption = new MonetaryValueOption(currency, r1, r2);
                qcStatementOption = new QcStatementOption(qcStatementId, monetaryValueOption);
                requireInfoFromReq = true;
            }
            currencyCodes.add(tmpCurrency);
        } else if (statementValue.getPdsLocations() != null) {
            ASN1EncodableVector vec = new ASN1EncodableVector();
            for (PdsLocationType pl : statementValue.getPdsLocations().getPdsLocation()) {
                ASN1EncodableVector vec2 = new ASN1EncodableVector();
                vec2.add(new DERIA5String(pl.getUrl()));
                String lang = pl.getLanguage();
                if (lang.length() != 2) {
                    throw new RuntimeException("invalid language '" + lang + "'");
                }
                vec2.add(new DERPrintableString(lang));
                DERSequence seq = new DERSequence(vec2);
                vec.add(seq);
            }
            QCStatement qcStatement = new QCStatement(qcStatementId, new DERSequence(vec));
            qcStatementOption = new QcStatementOption(qcStatement);
        } else {
            throw new RuntimeException("unknown value of qcStatment");
        }

        this.qcStatementsOption.add(qcStatementOption);
    } // end for

    if (requireInfoFromReq) {
        return;
    }

    ASN1EncodableVector vec = new ASN1EncodableVector();
    for (QcStatementOption m : qcStatementsOption) {
        if (m.getStatement() == null) {
            throw new RuntimeException("should not reach here");
        }
        vec.add(m.getStatement());
    }
    ASN1Sequence seq = new DERSequence(vec);
    qcStatments = new ExtensionValue(extensionControls.get(type).isCritical(), seq);
    qcStatementsOption = null;
}

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;
    }// www.j a v 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.client.shell.EnrollCertCommandSupport.java

License:Open Source License

@Override
protected Object doExecute() throws Exception {
    CertTemplateBuilder certTemplateBuilder = new CertTemplateBuilder();

    ConcurrentContentSigner signer = getSigner(new SignatureAlgoControl(rsaMgf1, dsaPlain));
    X509CertificateHolder ssCert = signer.getCertificateAsBcObject();

    X500Name x500Subject = new X500Name(subject);
    certTemplateBuilder.setSubject(x500Subject);
    certTemplateBuilder.setPublicKey(ssCert.getSubjectPublicKeyInfo());

    if (StringUtil.isNotBlank(notBeforeS) || StringUtil.isNotBlank(notAfterS)) {
        Time notBefore = StringUtil.isNotBlank(notBeforeS)
                ? new Time(DateUtil.parseUtcTimeyyyyMMddhhmmss(notBeforeS))
                : null;// w w w.  j av  a 2s .  c  o m
        Time notAfter = StringUtil.isNotBlank(notAfterS)
                ? new Time(DateUtil.parseUtcTimeyyyyMMddhhmmss(notAfterS))
                : null;
        OptionalValidity validity = new OptionalValidity(notBefore, notAfter);
        certTemplateBuilder.setValidity(validity);
    }

    if (needExtensionTypes == null) {
        needExtensionTypes = new LinkedList<>();
    }

    // SubjectAltNames
    List<Extension> extensions = new LinkedList<>();
    if (isNotEmpty(subjectAltNames)) {
        extensions.add(X509Util.createExtensionSubjectAltName(subjectAltNames, false));
        needExtensionTypes.add(Extension.subjectAlternativeName.getId());
    }

    // SubjectInfoAccess
    if (isNotEmpty(subjectInfoAccesses)) {
        extensions.add(X509Util.createExtensionSubjectInfoAccess(subjectInfoAccesses, false));
        needExtensionTypes.add(Extension.subjectInfoAccess.getId());
    }

    // Keyusage
    if (isNotEmpty(keyusages)) {
        Set<KeyUsage> usages = new HashSet<>();
        for (String usage : keyusages) {
            usages.add(KeyUsage.getKeyUsage(usage));
        }
        org.bouncycastle.asn1.x509.KeyUsage extValue = X509Util.createKeyUsage(usages);
        ASN1ObjectIdentifier extType = Extension.keyUsage;
        extensions.add(new Extension(extType, false, extValue.getEncoded()));
        needExtensionTypes.add(extType.getId());
    }

    // ExtendedKeyusage
    if (isNotEmpty(extkeyusages)) {
        ExtendedKeyUsage extValue = X509Util.createExtendedUsage(textToAsn1ObjectIdentifers(extkeyusages));
        ASN1ObjectIdentifier extType = Extension.extendedKeyUsage;
        extensions.add(new Extension(extType, false, extValue.getEncoded()));
        needExtensionTypes.add(extType.getId());
    }

    // QcEuLimitValue
    if (isNotEmpty(qcEuLimits)) {
        ASN1EncodableVector vec = new ASN1EncodableVector();
        for (String m : qcEuLimits) {
            StringTokenizer st = new StringTokenizer(m, ":");
            try {
                String currencyS = st.nextToken();
                String amountS = st.nextToken();
                String exponentS = st.nextToken();

                Iso4217CurrencyCode currency;
                try {
                    int intValue = Integer.parseInt(currencyS);
                    currency = new Iso4217CurrencyCode(intValue);
                } catch (NumberFormatException ex) {
                    currency = new Iso4217CurrencyCode(currencyS);
                }

                int amount = Integer.parseInt(amountS);
                int exponent = Integer.parseInt(exponentS);

                MonetaryValue monterayValue = new MonetaryValue(currency, amount, exponent);
                QCStatement statment = new QCStatement(ObjectIdentifiers.id_etsi_qcs_QcLimitValue,
                        monterayValue);
                vec.add(statment);
            } catch (Exception ex) {
                throw new Exception("invalid qc-eu-limit '" + m + "'");
            }
        }

        ASN1ObjectIdentifier extType = Extension.qCStatements;
        ASN1Sequence extValue = new DERSequence(vec);
        extensions.add(new Extension(extType, false, extValue.getEncoded()));
        needExtensionTypes.add(extType.getId());
    }

    // biometricInfo
    if (biometricType != null && biometricHashAlgo != null && biometricFile != null) {
        TypeOfBiometricData objBiometricType = StringUtil.isNumber(biometricType)
                ? new TypeOfBiometricData(Integer.parseInt(biometricType))
                : new TypeOfBiometricData(new ASN1ObjectIdentifier(biometricType));

        ASN1ObjectIdentifier objBiometricHashAlgo = AlgorithmUtil.getHashAlg(biometricHashAlgo);
        byte[] biometricBytes = IoUtil.read(biometricFile);
        MessageDigest md = MessageDigest.getInstance(objBiometricHashAlgo.getId());
        md.reset();
        byte[] biometricDataHash = md.digest(biometricBytes);

        DERIA5String sourceDataUri = null;
        if (biometricUri != null) {
            sourceDataUri = new DERIA5String(biometricUri);
        }
        BiometricData biometricData = new BiometricData(objBiometricType,
                new AlgorithmIdentifier(objBiometricHashAlgo), new DEROctetString(biometricDataHash),
                sourceDataUri);

        ASN1EncodableVector vec = new ASN1EncodableVector();
        vec.add(biometricData);

        ASN1ObjectIdentifier extType = Extension.biometricInfo;
        ASN1Sequence extValue = new DERSequence(vec);
        extensions.add(new Extension(extType, false, extValue.getEncoded()));
        needExtensionTypes.add(extType.getId());
    } else if (biometricType == null && biometricHashAlgo == null && biometricFile == null) {
        // Do nothing
    } else {
        throw new Exception("either all of biometric triples (type, hash algo, file)"
                + " must be set or none of them should be set");
    }

    if (isNotEmpty(needExtensionTypes) || isNotEmpty(wantExtensionTypes)) {
        ExtensionExistence ee = new ExtensionExistence(textToAsn1ObjectIdentifers(needExtensionTypes),
                textToAsn1ObjectIdentifers(wantExtensionTypes));
        extensions.add(new Extension(ObjectIdentifiers.id_xipki_ext_cmpRequestExtensions, false,
                ee.toASN1Primitive().getEncoded()));
    }

    if (isNotEmpty(extensions)) {
        Extensions asn1Extensions = new Extensions(extensions.toArray(new Extension[0]));
        certTemplateBuilder.setExtensions(asn1Extensions);
    }

    CertRequest certReq = new CertRequest(1, certTemplateBuilder.build(), null);

    ProofOfPossessionSigningKeyBuilder popoBuilder = new ProofOfPossessionSigningKeyBuilder(certReq);
    POPOSigningKey popoSk = signer.build(popoBuilder);

    ProofOfPossession popo = new ProofOfPossession(popoSk);
    EnrollCertRequestEntry reqEntry = new EnrollCertRequestEntry("id-1", profile, certReq, popo);
    EnrollCertRequest request = new EnrollCertRequest(EnrollCertRequest.Type.CERT_REQ);
    request.addRequestEntry(reqEntry);

    RequestResponseDebug debug = getRequestResponseDebug();
    EnrollCertResult result;
    try {
        result = caClient.requestCerts(caName, request, user, debug);
    } finally {
        saveRequestResponse(debug);
    }

    X509Certificate cert = null;
    if (result != null) {
        String id = result.getAllIds().iterator().next();
        CertOrError certOrError = result.getCertificateOrError(id);
        cert = (X509Certificate) certOrError.getCertificate();
    }

    if (cert == null) {
        throw new CmdFailure("no certificate received from the server");
    }

    File certFile = new File(outputFile);
    saveVerbose("saved certificate to file", certFile, cert.getEncoded());

    return null;
}

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

License:Open Source License

public ExtensionsChecker(final X509ProfileType conf, final XmlX509Certprofile certProfile)
        throws CertprofileException {
    this.certProfile = ParamUtil.requireNonNull("certProfile", certProfile);

    ParamUtil.requireNonNull("conf", conf);

    // Extensions
    ExtensionsType extensionsType = conf.getExtensions();

    // Extension controls
    Map<ASN1ObjectIdentifier, ExtensionControl> extensionControls = certProfile.getExtensionControls();

    // Certificate Policies
    ASN1ObjectIdentifier type = Extension.certificatePolicies;
    if (extensionControls.containsKey(type)) {
        org.xipki.pki.ca.certprofile.x509.jaxb.CertificatePolicies extConf = (org.xipki.pki.ca.certprofile.x509.jaxb.CertificatePolicies) getExtensionValue(
                type, extensionsType, org.xipki.pki.ca.certprofile.x509.jaxb.CertificatePolicies.class);
        if (extConf != null) {
            this.certificatePolicies = new QaCertificatePolicies(extConf);
        }//from ww w .j  a v  a2s . c  o m
    }

    // Policy Mappings
    type = Extension.policyMappings;
    if (extensionControls.containsKey(type)) {
        PolicyMappings extConf = (PolicyMappings) getExtensionValue(type, extensionsType, PolicyMappings.class);
        if (extConf != null) {
            this.policyMappings = new QaPolicyMappingsOption(extConf);
        }
    }

    // Name Constrains
    type = Extension.nameConstraints;
    if (extensionControls.containsKey(type)) {
        org.xipki.pki.ca.certprofile.x509.jaxb.NameConstraints extConf = (org.xipki.pki.ca.certprofile.x509.jaxb.NameConstraints) getExtensionValue(
                type, extensionsType, org.xipki.pki.ca.certprofile.x509.jaxb.NameConstraints.class);
        if (extConf != null) {
            this.nameConstraints = new QaNameConstraints(extConf);
        }
    }

    // Policy Constraints
    type = Extension.policyConstraints;
    if (extensionControls.containsKey(type)) {
        PolicyConstraints extConf = (PolicyConstraints) getExtensionValue(type, extensionsType,
                PolicyConstraints.class);
        if (extConf != null) {
            this.policyConstraints = new QaPolicyConstraints(extConf);
        }
    }

    // Inhibit anyPolicy
    type = Extension.inhibitAnyPolicy;
    if (extensionControls.containsKey(type)) {
        InhibitAnyPolicy extConf = (InhibitAnyPolicy) getExtensionValue(type, extensionsType,
                InhibitAnyPolicy.class);
        if (extConf != null) {
            this.inhibitAnyPolicy = new QaInhibitAnyPolicy(extConf);
        }
    }

    // restriction
    type = ObjectIdentifiers.id_extension_restriction;
    if (extensionControls.containsKey(type)) {
        Restriction extConf = (Restriction) getExtensionValue(type, extensionsType, Restriction.class);
        if (extConf != null) {
            restriction = new QaDirectoryString(
                    XmlX509CertprofileUtil.convertDirectoryStringType(extConf.getType()), extConf.getText());
        }
    }

    // additionalInformation
    type = ObjectIdentifiers.id_extension_additionalInformation;
    if (extensionControls.containsKey(type)) {
        AdditionalInformation extConf = (AdditionalInformation) getExtensionValue(type, extensionsType,
                AdditionalInformation.class);
        if (extConf != null) {
            additionalInformation = new QaDirectoryString(
                    XmlX509CertprofileUtil.convertDirectoryStringType(extConf.getType()), extConf.getText());
        }
    }

    // validityModel
    type = ObjectIdentifiers.id_extension_validityModel;
    if (extensionControls.containsKey(type)) {
        ValidityModel extConf = (ValidityModel) getExtensionValue(type, extensionsType, ValidityModel.class);
        if (extConf != null) {
            validityModelId = new ASN1ObjectIdentifier(extConf.getModelId().getValue());
        }
    }

    // QCStatements
    type = Extension.qCStatements;
    if (extensionControls.containsKey(type)) {
        QcStatements extConf = (QcStatements) getExtensionValue(type, extensionsType, QcStatements.class);
        if (extConf != null) {
            qcStatements = extConf;
        }
    }

    // tlsFeature
    type = ObjectIdentifiers.id_pe_tlsfeature;
    if (extensionControls.containsKey(type)) {
        TlsFeature extConf = (TlsFeature) getExtensionValue(type, extensionsType, TlsFeature.class);
        if (extConf != null) {
            tlsFeature = new QaTlsFeature(extConf);
        }
    }

    // AuthorizationTemplate
    type = ObjectIdentifiers.id_xipki_ext_authorizationTemplate;
    if (extensionControls.containsKey(type)) {
        AuthorizationTemplate extConf = (AuthorizationTemplate) getExtensionValue(type, extensionsType,
                AuthorizationTemplate.class);
        if (extConf != null) {
            authorizationTemplate = new QaAuthorizationTemplate(extConf);
        }
    }

    // SMIMECapabilities
    type = ObjectIdentifiers.id_smimeCapabilities;
    if (extensionControls.containsKey(type)) {
        SMIMECapabilities extConf = (SMIMECapabilities) getExtensionValue(type, extensionsType,
                SMIMECapabilities.class);
        List<SMIMECapability> list = extConf.getSMIMECapability();

        ASN1EncodableVector vec = new ASN1EncodableVector();
        for (SMIMECapability m : list) {
            ASN1ObjectIdentifier oid = new ASN1ObjectIdentifier(m.getCapabilityID().getValue());
            ASN1Encodable params = null;
            org.xipki.pki.ca.certprofile.x509.jaxb.SMIMECapability.Parameters capParams = m.getParameters();
            if (capParams != null) {
                if (capParams.getInteger() != null) {
                    params = new ASN1Integer(capParams.getInteger());
                } else if (capParams.getBase64Binary() != null) {
                    params = readAsn1Encodable(capParams.getBase64Binary().getValue());
                }
            }
            org.bouncycastle.asn1.smime.SMIMECapability cap = new org.bouncycastle.asn1.smime.SMIMECapability(
                    oid, params);
            vec.add(cap);
        }

        DERSequence extValue = new DERSequence(vec);
        try {
            smimeCapabilities = new QaExtensionValue(extensionControls.get(type).isCritical(),
                    extValue.getEncoded());
        } catch (IOException ex) {
            throw new CertprofileException("Cannot encode SMIMECapabilities: " + ex.getMessage());
        }
    }

    // constant extensions
    this.constantExtensions = buildConstantExtesions(extensionsType);
}

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

License:Open Source License

public List<ValidationIssue> checkExtensions(final Certificate cert, final X509IssuerInfo issuerInfo,
        final Extensions requestedExtensions, final X500Name requestedSubject) {
    ParamUtil.requireNonNull("cert", cert);
    ParamUtil.requireNonNull("issuerInfo", issuerInfo);

    X509Certificate jceCert;/*  w ww  . ja va2 s. c  o m*/
    try {
        jceCert = X509Util.toX509Cert(cert);
    } catch (CertificateException ex) {
        throw new IllegalArgumentException("invalid cert: " + ex.getMessage());
    }

    List<ValidationIssue> result = new LinkedList<>();

    // detect the list of extension types in certificate
    Set<ASN1ObjectIdentifier> presentExtenionTypes = getExensionTypes(cert, issuerInfo, requestedExtensions);

    Extensions extensions = cert.getTBSCertificate().getExtensions();
    ASN1ObjectIdentifier[] oids = extensions.getExtensionOIDs();

    if (oids == null) {
        ValidationIssue issue = new ValidationIssue("X509.EXT.GEN", "extension general");
        result.add(issue);
        issue.setFailureMessage("no extension is present");
        return result;
    }

    List<ASN1ObjectIdentifier> certExtTypes = Arrays.asList(oids);

    for (ASN1ObjectIdentifier extType : presentExtenionTypes) {
        if (!certExtTypes.contains(extType)) {
            ValidationIssue issue = createExtensionIssue(extType);
            result.add(issue);
            issue.setFailureMessage("extension is absent but is required");
        }
    }

    Map<ASN1ObjectIdentifier, ExtensionControl> extensionControls = certProfile.getExtensionControls();
    for (ASN1ObjectIdentifier oid : certExtTypes) {
        ValidationIssue issue = createExtensionIssue(oid);
        result.add(issue);
        if (!presentExtenionTypes.contains(oid)) {
            issue.setFailureMessage("extension is present but is not permitted");
            continue;
        }

        Extension ext = extensions.getExtension(oid);
        StringBuilder failureMsg = new StringBuilder();
        ExtensionControl extControl = extensionControls.get(oid);

        if (extControl.isCritical() != ext.isCritical()) {
            addViolation(failureMsg, "critical", ext.isCritical(), extControl.isCritical());
        }

        byte[] extensionValue = ext.getExtnValue().getOctets();
        try {
            if (Extension.authorityKeyIdentifier.equals(oid)) {
                // AuthorityKeyIdentifier
                checkExtensionIssuerKeyIdentifier(failureMsg, extensionValue, issuerInfo);
            } else if (Extension.subjectKeyIdentifier.equals(oid)) {
                // SubjectKeyIdentifier
                checkExtensionSubjectKeyIdentifier(failureMsg, extensionValue, cert.getSubjectPublicKeyInfo());
            } else if (Extension.keyUsage.equals(oid)) {
                // KeyUsage
                checkExtensionKeyUsage(failureMsg, extensionValue, jceCert.getKeyUsage(), requestedExtensions,
                        extControl);
            } else if (Extension.certificatePolicies.equals(oid)) {
                // CertificatePolicies
                checkExtensionCertificatePolicies(failureMsg, extensionValue, requestedExtensions, extControl);
            } else if (Extension.policyMappings.equals(oid)) {
                // Policy Mappings
                checkExtensionPolicyMappings(failureMsg, extensionValue, requestedExtensions, extControl);
            } else if (Extension.subjectAlternativeName.equals(oid)) {
                // SubjectAltName
                checkExtensionSubjectAltName(failureMsg, extensionValue, requestedExtensions, extControl,
                        requestedSubject);
            } else if (Extension.subjectDirectoryAttributes.equals(oid)) {
                // SubjectDirectoryAttributes
                checkExtensionSubjectDirAttrs(failureMsg, extensionValue, requestedExtensions, extControl);
            } else if (Extension.issuerAlternativeName.equals(oid)) {
                // IssuerAltName
                checkExtensionIssuerAltNames(failureMsg, extensionValue, issuerInfo);
            } else if (Extension.basicConstraints.equals(oid)) {
                // Basic Constraints
                checkExtensionBasicConstraints(failureMsg, extensionValue);
            } else if (Extension.nameConstraints.equals(oid)) {
                // Name Constraints
                checkExtensionNameConstraints(failureMsg, extensionValue, extensions, extControl);
            } else if (Extension.policyConstraints.equals(oid)) {
                // PolicyConstrains
                checkExtensionPolicyConstraints(failureMsg, extensionValue, requestedExtensions, extControl);
            } else if (Extension.extendedKeyUsage.equals(oid)) {
                // ExtendedKeyUsage
                checkExtensionExtendedKeyUsage(failureMsg, extensionValue, requestedExtensions, extControl);
            } else if (Extension.cRLDistributionPoints.equals(oid)) {
                // CRL Distribution Points
                checkExtensionCrlDistributionPoints(failureMsg, extensionValue, issuerInfo);
            } else if (Extension.inhibitAnyPolicy.equals(oid)) {
                // Inhibit anyPolicy
                checkExtensionInhibitAnyPolicy(failureMsg, extensionValue, extensions, extControl);
            } else if (Extension.freshestCRL.equals(oid)) {
                // Freshest CRL
                checkExtensionDeltaCrlDistributionPoints(failureMsg, extensionValue, issuerInfo);
            } else if (Extension.authorityInfoAccess.equals(oid)) {
                // Authority Information Access
                checkExtensionAuthorityInfoAccess(failureMsg, extensionValue, issuerInfo);
            } else if (Extension.subjectInfoAccess.equals(oid)) {
                // SubjectInfoAccess
                checkExtensionSubjectInfoAccess(failureMsg, extensionValue, requestedExtensions, extControl);
            } else if (ObjectIdentifiers.id_extension_admission.equals(oid)) {
                // Admission
                checkExtensionAdmission(failureMsg, extensionValue, requestedExtensions, extControl);
            } else if (ObjectIdentifiers.id_extension_pkix_ocsp_nocheck.equals(oid)) {
                // ocsp-nocheck
                checkExtensionOcspNocheck(failureMsg, extensionValue);
            } else if (ObjectIdentifiers.id_extension_restriction.equals(oid)) {
                // restriction
                checkExtensionRestriction(failureMsg, extensionValue, requestedExtensions, extControl);
            } else if (ObjectIdentifiers.id_extension_additionalInformation.equals(oid)) {
                // additionalInformation
                checkExtensionAdditionalInformation(failureMsg, extensionValue, requestedExtensions,
                        extControl);
            } else if (ObjectIdentifiers.id_extension_validityModel.equals(oid)) {
                // validityModel
                checkExtensionValidityModel(failureMsg, extensionValue, requestedExtensions, extControl);
            } else if (Extension.privateKeyUsagePeriod.equals(oid)) {
                // privateKeyUsagePeriod
                checkExtensionPrivateKeyUsagePeriod(failureMsg, extensionValue, jceCert.getNotBefore(),
                        jceCert.getNotAfter());
            } else if (Extension.qCStatements.equals(oid)) {
                // qCStatements
                checkExtensionQcStatements(failureMsg, extensionValue, requestedExtensions, extControl);
            } else if (Extension.biometricInfo.equals(oid)) {
                // biometricInfo
                checkExtensionBiometricInfo(failureMsg, extensionValue, requestedExtensions, extControl);
            } else if (ObjectIdentifiers.id_pe_tlsfeature.equals(oid)) {
                // tlsFeature
                checkExtensionTlsFeature(failureMsg, extensionValue, requestedExtensions, extControl);
            } else if (ObjectIdentifiers.id_xipki_ext_authorizationTemplate.equals(oid)) {
                // authorizationTemplate
                checkExtensionAuthorizationTemplate(failureMsg, extensionValue, requestedExtensions,
                        extControl);
            } else {
                byte[] expected;
                if (ObjectIdentifiers.id_smimeCapabilities.equals(oid)) {
                    // SMIMECapabilities
                    expected = smimeCapabilities.getValue();
                } else {
                    expected = getExpectedExtValue(oid, requestedExtensions, extControl);
                }

                if (!Arrays.equals(expected, extensionValue)) {
                    addViolation(failureMsg, "extension valus", hex(extensionValue),
                            (expected == null) ? "not present" : hex(expected));
                }
            }

            if (failureMsg.length() > 0) {
                issue.setFailureMessage(failureMsg.toString());
            }

        } catch (IllegalArgumentException | ClassCastException | ArrayIndexOutOfBoundsException ex) {
            LOG.debug("extension value does not have correct syntax", ex);
            issue.setFailureMessage("extension value does not have correct syntax");
        }
    }

    return result;
}

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  a va 2  s.co  m
    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; ");
        }
    }
}