List of usage examples for org.bouncycastle.asn1 DEROctetString DEROctetString
public DEROctetString(ASN1Encodable obj) throws IOException
From source file:org.xipki.pki.ca.certprofile.commonpki.AdmissionSyntaxOption.java
License:Open Source License
public ExtensionValue getExtensionValue(final List<List<String>> registrationNumbersList) throws BadCertTemplateException { if (!this.inputFromRequestRequired) { return this.extensionValue; }/* w ww . jav a2 s . com*/ if (CollectionUtil.isEmpty(registrationNumbersList)) { throw new BadCertTemplateException("registrationNumbersList must not be empty"); } final int n = registrationNumbersList.size(); if (n != this.admissionsList.size()) { throw new BadCertTemplateException("invalid size of Admissions in AdmissionSyntax: " + "is=" + n + ", expected=" + this.admissionsList.size()); } // check registrationNumbers List<List<String>> newRegNumbersList = new ArrayList<>(this.admissionsList.size()); for (int i = 0; i < n; i++) { AdmissionsOption ao = this.admissionsList.get(i); List<ProfessionInfoOption> pi = ao.getProfessionInfos(); List<String> registrationNumbers = registrationNumbersList.get(i); final int k = registrationNumbers.size(); if (k != pi.size()) { throw new BadCertTemplateException("invalid size of ProfessionInfo in Admissions[" + i + "], is=" + k + ", expected=" + pi.size()); } List<String> newRegNumbers = new ArrayList<>(k); newRegNumbersList.add(newRegNumbers); for (int j = 0; j < k; j++) { RegistrationNumberOption option = pi.get(j).getRegistrationNumberOption(); if (option == null || option.getConstant() != null) { continue; } Pattern regex = option.getRegex(); String regNum = registrationNumbers.get(j); if (regNum == null || !regex.matcher(regNum).matches()) { throw new BadCertTemplateException( "invalid registrationNumber[" + i + "][" + j + "]: '" + regNum + "'"); } newRegNumbers.add(regNum); } } ASN1EncodableVector vec = new ASN1EncodableVector(); for (int i = 0; i < this.admissionsList.size(); i++) { AdmissionsOption ao = this.admissionsList.get(i); List<ProfessionInfoOption> piList = ao.getProfessionInfos(); ProfessionInfo[] pis = new ProfessionInfo[piList.size()]; for (int j = 0; j < pis.length; j++) { ProfessionInfoOption pio = piList.get(j); DirectoryString[] professionItems = null; int size = pio.getProfessionItems().size(); professionItems = new DirectoryString[size]; for (int k = 0; k < size; k++) { professionItems[k] = new DirectoryString(pio.getProfessionItems().get(k)); } ASN1OctetString addProfessionInfo = null; if (pio.getAddProfessionalInfo() != null) { addProfessionInfo = new DEROctetString(pio.getAddProfessionalInfo()); } RegistrationNumberOption regNumOption = pio.getRegistrationNumberOption(); String registrationNumber = null; if (regNumOption != null) { if (regNumOption.getConstant() != null) { registrationNumber = regNumOption.getConstant(); } else { registrationNumber = newRegNumbersList.get(i).get(j); } } pis[i] = new ProfessionInfo(pio.getNamingAuthority(), professionItems, pio.getProfessionOids().toArray(new ASN1ObjectIdentifier[0]), registrationNumber, addProfessionInfo); } vec.add(new Admissions(ao.getAdmissionAuthority(), ao.getNamingAuthority(), pis)); } return new ExtensionValue(critical, new AdmissionSyntax(admissionAuthority, new DERSequence(vec))); }
From source file:org.xipki.pki.ca.certprofile.XmlX509Certprofile.java
License:Open Source License
private void initAuthorizationTemplate(ExtensionsType extensionsType) throws CertprofileException { ASN1ObjectIdentifier type = ObjectIdentifiers.id_xipki_ext_authorizationTemplate; if (!extensionControls.containsKey(type)) { return;/*www. j a va2s.c o m*/ } AuthorizationTemplate extConf = (AuthorizationTemplate) getExtensionValue(type, extensionsType, AuthorizationTemplate.class); if (extConf == null) { return; } ASN1EncodableVector vec = new ASN1EncodableVector(); vec.add(new ASN1ObjectIdentifier(extConf.getType().getValue())); vec.add(new DEROctetString(extConf.getAccessRights().getValue())); ASN1Encodable extValue = new DERSequence(vec); authorizationTemplate = new ExtensionValue(extensionControls.get(type).isCritical(), extValue); }
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; }//from w ww . ja v a 2s . com 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.impl.CmpRequestor.java
License:Open Source License
protected PKIHeader buildPkiHeader(final boolean addImplictConfirm, final ASN1OctetString tid, final CmpUtf8Pairs utf8Pairs, final InfoTypeAndValue... additionalGeneralInfos) { if (additionalGeneralInfos != null) { for (InfoTypeAndValue itv : additionalGeneralInfos) { ASN1ObjectIdentifier type = itv.getInfoType(); if (CMPObjectIdentifiers.it_implicitConfirm.equals(type)) { throw new IllegalArgumentException( "additionGeneralInfos contains not-permitted ITV implicitConfirm"); }//from www. j a v a2 s . c o m if (CMPObjectIdentifiers.regInfo_utf8Pairs.equals(type)) { throw new IllegalArgumentException("additionGeneralInfos contains not-permitted ITV utf8Pairs"); } } } PKIHeaderBuilder hdrBuilder = new PKIHeaderBuilder(PKIHeader.CMP_2000, sender, recipient); hdrBuilder.setMessageTime(new ASN1GeneralizedTime(new Date())); ASN1OctetString tmpTid = (tid == null) ? new DEROctetString(randomTransactionId()) : tid; hdrBuilder.setTransactionID(tmpTid); List<InfoTypeAndValue> itvs = new ArrayList<>(2); if (addImplictConfirm) { itvs.add(CmpUtil.getImplictConfirmGeneralInfo()); } if (utf8Pairs != null) { itvs.add(CmpUtil.buildInfoTypeAndValue(utf8Pairs)); } if (additionalGeneralInfos != null) { for (InfoTypeAndValue itv : additionalGeneralInfos) { if (itv != null) { itvs.add(itv); } } } if (CollectionUtil.isNonEmpty(itvs)) { hdrBuilder.setGeneralInfo(itvs.toArray(new InfoTypeAndValue[0])); } return hdrBuilder.build(); }
From source file:org.xipki.pki.ca.client.impl.X509CmpRequestor.java
License:Open Source License
private PKIMessage buildRevokeCertRequest(final RevokeCertRequest request) throws CmpRequestorException { PKIHeader header = buildPkiHeader(null); List<RevokeCertRequestEntry> requestEntries = request.getRequestEntries(); List<RevDetails> revDetailsArray = new ArrayList<>(requestEntries.size()); for (RevokeCertRequestEntry requestEntry : requestEntries) { CertTemplateBuilder certTempBuilder = new CertTemplateBuilder(); certTempBuilder.setIssuer(requestEntry.getIssuer()); certTempBuilder.setSerialNumber(new ASN1Integer(requestEntry.getSerialNumber())); byte[] aki = requestEntry.getAuthorityKeyIdentifier(); if (aki != null) { Extensions certTempExts = getCertTempExtensions(aki); certTempBuilder.setExtensions(certTempExts); }//from w w w.j a v a 2s .c om Date invalidityDate = requestEntry.getInvalidityDate(); int idx = (invalidityDate == null) ? 1 : 2; Extension[] extensions = new Extension[idx]; try { ASN1Enumerated reason = new ASN1Enumerated(requestEntry.getReason()); extensions[0] = new Extension(Extension.reasonCode, true, new DEROctetString(reason.getEncoded())); if (invalidityDate != null) { ASN1GeneralizedTime time = new ASN1GeneralizedTime(invalidityDate); extensions[1] = new Extension(Extension.invalidityDate, true, new DEROctetString(time.getEncoded())); } } catch (IOException ex) { throw new CmpRequestorException(ex.getMessage(), ex); } Extensions exts = new Extensions(extensions); RevDetails revDetails = new RevDetails(certTempBuilder.build(), exts); revDetailsArray.add(revDetails); } RevReqContent content = new RevReqContent(revDetailsArray.toArray(new RevDetails[0])); PKIBody body = new PKIBody(PKIBody.TYPE_REVOCATION_REQ, content); return new PKIMessage(header, body); }
From source file:org.xipki.pki.ca.client.impl.X509CmpRequestor.java
License:Open Source License
private PKIMessage buildUnrevokeOrRemoveCertRequest(final UnrevokeOrRemoveCertRequest request, final int reasonCode) throws CmpRequestorException { PKIHeader header = buildPkiHeader(null); List<UnrevokeOrRemoveCertEntry> requestEntries = request.getRequestEntries(); List<RevDetails> revDetailsArray = new ArrayList<>(requestEntries.size()); for (UnrevokeOrRemoveCertEntry requestEntry : requestEntries) { CertTemplateBuilder certTempBuilder = new CertTemplateBuilder(); certTempBuilder.setIssuer(requestEntry.getIssuer()); certTempBuilder.setSerialNumber(new ASN1Integer(requestEntry.getSerialNumber())); byte[] aki = requestEntry.getAuthorityKeyIdentifier(); if (aki != null) { Extensions certTempExts = getCertTempExtensions(aki); certTempBuilder.setExtensions(certTempExts); }/*from w w w .j a va 2 s . c o m*/ Extension[] extensions = new Extension[1]; try { ASN1Enumerated reason = new ASN1Enumerated(reasonCode); extensions[0] = new Extension(Extension.reasonCode, true, new DEROctetString(reason.getEncoded())); } catch (IOException ex) { throw new CmpRequestorException(ex.getMessage(), ex); } Extensions exts = new Extensions(extensions); RevDetails revDetails = new RevDetails(certTempBuilder.build(), exts); revDetailsArray.add(revDetails); } RevReqContent content = new RevReqContent(revDetailsArray.toArray(new RevDetails[0])); PKIBody body = new PKIBody(PKIBody.TYPE_REVOCATION_REQ, content); return new PKIMessage(header, body); }
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 ww . j a v a 2 s .co 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.server.impl.cmp.CmpResponder.java
License:Open Source License
public PKIMessage processPkiMessage(final PKIMessage pkiMessage, final X509Certificate tlsClientCert, final String tidStr, final AuditEvent event) { ParamUtil.requireNonNull("pkiMessage", pkiMessage); ParamUtil.requireNonNull("event", event); GeneralPKIMessage message = new GeneralPKIMessage(pkiMessage); PKIHeader reqHeader = message.getHeader(); ASN1OctetString tid = reqHeader.getTransactionID(); String msgId = null;//w ww .ja va 2 s .c o m if (event != null) { msgId = RandomUtil.nextHexLong(); event.addEventData(CaAuditConstants.NAME_mid, msgId); } if (tid == null) { byte[] randomBytes = randomTransactionId(); tid = new DEROctetString(randomBytes); } CmpControl cmpControl = getCmpControl(); Integer failureCode = null; String statusText = null; Date messageTime = null; if (reqHeader.getMessageTime() != null) { try { messageTime = reqHeader.getMessageTime().getDate(); } catch (ParseException ex) { LogUtil.error(LOG, ex, "tid=" + tidStr + ": could not parse messageDate"); } } GeneralName recipient = reqHeader.getRecipient(); boolean intentMe = (recipient == null) ? true : intendsMe(recipient); if (!intentMe) { LOG.warn("tid={}: I am not the intended recipient, but '{}'", tid, reqHeader.getRecipient()); failureCode = PKIFailureInfo.badRequest; statusText = "I am not the intended recipient"; } else if (messageTime == null) { if (cmpControl.isMessageTimeRequired()) { failureCode = PKIFailureInfo.missingTimeStamp; statusText = "missing time-stamp"; } } else { long messageTimeBias = cmpControl.getMessageTimeBias(); if (messageTimeBias < 0) { messageTimeBias *= -1; } long msgTimeMs = messageTime.getTime(); long currentTimeMs = System.currentTimeMillis(); long bias = (msgTimeMs - currentTimeMs) / 1000L; if (bias > messageTimeBias) { failureCode = PKIFailureInfo.badTime; statusText = "message time is in the future"; } else if (bias * -1 > messageTimeBias) { failureCode = PKIFailureInfo.badTime; statusText = "message too old"; } } if (failureCode != null) { if (event != null) { event.setLevel(AuditLevel.INFO); event.setStatus(AuditStatus.FAILED); event.addEventData(CaAuditConstants.NAME_message, statusText); } return buildErrorPkiMessage(tid, reqHeader, failureCode, statusText); } boolean isProtected = message.hasProtection(); CmpRequestorInfo requestor; String errorStatus; if (isProtected) { try { ProtectionVerificationResult verificationResult = verifyProtection(tidStr, message, cmpControl); ProtectionResult pr = verificationResult.getProtectionResult(); switch (pr) { case VALID: errorStatus = null; break; case INVALID: errorStatus = "request is protected by signature but invalid"; break; case NOT_SIGNATURE_BASED: errorStatus = "request is not protected by signature"; break; case SENDER_NOT_AUTHORIZED: errorStatus = "request is protected by signature but the requestor is not authorized"; break; case SIGALGO_FORBIDDEN: errorStatus = "request is protected by signature but the protection algorithm" + " is forbidden"; break; default: throw new RuntimeException("should not reach here, unknown ProtectionResult " + pr); } // end switch requestor = (CmpRequestorInfo) verificationResult.getRequestor(); } catch (Exception ex) { LogUtil.error(LOG, ex, "tid=" + tidStr + ": could not verify the signature"); errorStatus = "request has invalid signature based protection"; requestor = null; } } else if (tlsClientCert != null) { boolean authorized = false; requestor = getRequestor(reqHeader); if (requestor != null) { if (tlsClientCert.equals(requestor.getCert().getCert())) { authorized = true; } } if (authorized) { errorStatus = null; } else { LOG.warn("tid={}: not authorized requestor (TLS client '{}')", tid, X509Util.getRfc4519Name(tlsClientCert.getSubjectX500Principal())); errorStatus = "requestor (TLS client certificate) is not authorized"; } } else { errorStatus = "request has no protection"; requestor = null; } CmpUtf8Pairs keyvalues = CmpUtil.extract(reqHeader.getGeneralInfo()); String username = (keyvalues == null) ? null : keyvalues.getValue(CmpUtf8Pairs.KEY_USER); if (username != null) { if (username.indexOf('*') != -1 || username.indexOf('%') != -1) { errorStatus = "user could not contains characters '*' and '%'"; } } if (errorStatus != null) { if (event != null) { event.setLevel(AuditLevel.INFO); event.setStatus(AuditStatus.FAILED); event.addEventData(CaAuditConstants.NAME_message, errorStatus); } return buildErrorPkiMessage(tid, reqHeader, PKIFailureInfo.badMessageCheck, errorStatus); } PKIMessage resp = doProcessPkiMessage(pkiMessage, requestor, username, tid, message, msgId, event); if (isProtected) { resp = addProtection(resp, event); } else { // protected by TLS connection } return resp; }
From source file:org.xipki.pki.ocsp.client.impl.AbstractOcspRequestor.java
License:Open Source License
private OCSPReq buildRequest(final X509Certificate caCert, final BigInteger[] serialNumbers, final byte[] nonce, final RequestOptions requestOptions) throws OcspRequestorException { HashAlgoType hashAlgo = HashAlgoType.getHashAlgoType(requestOptions.getHashAlgorithmId()); if (hashAlgo == null) { throw new OcspRequestorException("unknown HashAlgo " + requestOptions.getHashAlgorithmId().getId()); }/* w w w . jav a 2 s . c om*/ List<AlgorithmIdentifier> prefSigAlgs = requestOptions.getPreferredSignatureAlgorithms(); DigestCalculator digestCalculator; switch (hashAlgo) { case SHA1: digestCalculator = new SHA1DigestCalculator(); break; case SHA224: digestCalculator = new SHA224DigestCalculator(); break; case SHA256: digestCalculator = new SHA256DigestCalculator(); break; case SHA384: digestCalculator = new SHA384DigestCalculator(); break; case SHA512: digestCalculator = new SHA512DigestCalculator(); break; case SHA3_224: digestCalculator = new SHA3_224DigestCalculator(); break; case SHA3_256: digestCalculator = new SHA3_256DigestCalculator(); break; case SHA3_384: digestCalculator = new SHA3_384DigestCalculator(); break; case SHA3_512: digestCalculator = new SHA3_512DigestCalculator(); break; default: throw new RuntimeException("unknown HashAlgoType: " + hashAlgo); } OCSPReqBuilder reqBuilder = new OCSPReqBuilder(); List<Extension> extensions = new LinkedList<>(); if (nonce != null) { Extension extn = new Extension(OCSPObjectIdentifiers.id_pkix_ocsp_nonce, false, new DEROctetString(nonce)); extensions.add(extn); } if (prefSigAlgs != null && prefSigAlgs.size() > 0) { ASN1EncodableVector vec = new ASN1EncodableVector(); for (AlgorithmIdentifier algId : prefSigAlgs) { ASN1Sequence prefSigAlgObj = new DERSequence(algId); vec.add(prefSigAlgObj); } ASN1Sequence extnValue = new DERSequence(vec); Extension extn; try { extn = new Extension(ObjectIdentifiers.id_pkix_ocsp_prefSigAlgs, false, new DEROctetString(extnValue)); } catch (IOException ex) { throw new OcspRequestorException(ex.getMessage(), ex); } extensions.add(extn); } if (CollectionUtil.isNonEmpty(extensions)) { reqBuilder.setRequestExtensions(new Extensions(extensions.toArray(new Extension[0]))); } try { for (BigInteger serialNumber : serialNumbers) { CertificateID certId = new CertificateID(digestCalculator, new X509CertificateHolder(caCert.getEncoded()), serialNumber); reqBuilder.addRequest(certId); } if (requestOptions.isSignRequest()) { synchronized (signerLock) { if (signer == null) { if (StringUtil.isBlank(signerType)) { throw new OcspRequestorException("signerType is not configured"); } if (StringUtil.isBlank(signerConf)) { throw new OcspRequestorException("signerConf is not configured"); } X509Certificate cert = null; if (StringUtil.isNotBlank(signerCertFile)) { try { cert = X509Util.parseCert(signerCertFile); } catch (CertificateException ex) { throw new OcspRequestorException( "could not parse certificate " + signerCertFile + ": " + ex.getMessage()); } } try { signer = getSecurityFactory().createSigner(signerType, new SignerConf(signerConf), cert); } catch (Exception ex) { throw new OcspRequestorException("could not create signer: " + ex.getMessage()); } } // end if } // end synchronized reqBuilder.setRequestorName(signer.getCertificateAsBcObject().getSubject()); try { return signer.build(reqBuilder, signer.getCertificateChainAsBcObjects()); } catch (NoIdleSignerException ex) { throw new OcspRequestorException("NoIdleSignerException: " + ex.getMessage()); } } else { return reqBuilder.build(); } // end if } catch (OCSPException | CertificateEncodingException | IOException ex) { throw new OcspRequestorException(ex.getMessage(), ex); } }
From source file:org.xipki.pki.ocsp.server.impl.ResponderSigner.java
License:Open Source License
ResponderSigner(final List<ConcurrentContentSigner> signers) throws CertificateException, IOException { this.signers = ParamUtil.requireNonEmpty("signers", signers); X509Certificate[] tmpCertificateChain = signers.get(0).getCertificateChain(); if (tmpCertificateChain == null || tmpCertificateChain.length == 0) { throw new CertificateException("no certificate is bound with the signer"); }/*from w w w. j av a2 s . co m*/ int len = tmpCertificateChain.length; if (len > 1) { X509Certificate cert = tmpCertificateChain[len - 1]; if (cert.getIssuerX500Principal().equals(cert.getSubjectX500Principal())) { len--; } } this.certificateChain = new X509Certificate[len]; System.arraycopy(tmpCertificateChain, 0, this.certificateChain, 0, len); this.certificate = certificateChain[0]; this.bcCertificate = new X509CertificateHolder(this.certificate.getEncoded()); this.bcCertificateChain = new X509CertificateHolder[this.certificateChain.length]; for (int i = 0; i < certificateChain.length; i++) { this.bcCertificateChain[i] = new X509CertificateHolder(this.certificateChain[i].getEncoded()); } this.responderIdByName = new RespID(this.bcCertificate.getSubject()); byte[] keySha1 = HashAlgoType.SHA1 .hash(this.bcCertificate.getSubjectPublicKeyInfo().getPublicKeyData().getBytes()); this.responderIdByKey = new RespID(new ResponderID(new DEROctetString(keySha1))); algoSignerMap = new HashMap<>(); for (ConcurrentContentSigner signer : signers) { String algoName = getSignatureAlgorithmName(signer.getAlgorithmIdentifier()); algoSignerMap.put(algoName, signer); } }