List of usage examples for org.bouncycastle.asn1.x500 X500Name getRDNs
public RDN[] getRDNs(ASN1ObjectIdentifier attributeType)
From source file:org.xipki.ca.api.profile.x509.BaseX509Certprofile.java
License:Open Source License
protected static String getSubjectFieldFirstValue(final X500Name subject, final ASN1ObjectIdentifier type, final int index) { RDN[] rdns = subject.getRDNs(type); if (index < 0 || rdns == null || rdns.length <= index) { return null; }/*from w w w . j a v a 2 s.com*/ RDN rdn = rdns[index]; return X509Util.rdnValueToString(rdn.getFirst().getValue()); }
From source file:org.xipki.ca.qa.impl.X509CertprofileQAImpl.java
License:Open Source License
private ValidationIssue checkSubjectAttribute(final ASN1ObjectIdentifier type, final X500Name subject, final X500Name requestedSubject) { ValidationIssue issue = createSubjectIssue(type); // control//from w w w. j a v a 2 s .co m int minOccurs; int maxOccurs; RDNControl rdnControl = getSubjectDNControl(type); if (rdnControl == null) { minOccurs = 0; maxOccurs = 0; } else { minOccurs = rdnControl.getMinOccurs(); maxOccurs = rdnControl.getMaxOccurs(); } RDN[] rdns = subject.getRDNs(type); int rdnsSize = rdns == null ? 0 : rdns.length; if (rdnsSize < minOccurs || rdnsSize > maxOccurs) { issue.setFailureMessage( "number of RDNs '" + rdnsSize + "' is not within [" + minOccurs + ", " + maxOccurs + "]"); return issue; } RDN[] requestedRdns = requestedSubject.getRDNs(type); if (rdnsSize == 0) { // check optional attribute but is present in requestedSubject if (maxOccurs > 0 && requestedRdns != null && requestedRdns.length > 0) { issue.setFailureMessage("is absent but expected present"); } return issue; } SubjectDNOption rdnOption = subjectDNOptions.get(type); // check the encoding DirectoryStringType stringType = rdnControl.getDirectoryStringEnum(); if (stringType == null) { if (ObjectIdentifiers.DN_C.equals(type) || ObjectIdentifiers.DN_SERIALNUMBER.equals(type)) { stringType = DirectoryStringType.printableString; } else { stringType = DirectoryStringType.utf8String; } } List<String> requestedCoreAtvTextValues = new LinkedList<>(); if (requestedRdns != null) { for (RDN requestedRdn : requestedRdns) { String textValue = X509Util.rdnValueToString(requestedRdn.getFirst().getValue()); requestedCoreAtvTextValues.add(textValue); } if (rdnOption != null && rdnOption.getPatterns() != null) { // sort the requestedRDNs requestedCoreAtvTextValues = sort(requestedCoreAtvTextValues, rdnOption.getPatterns()); } } StringBuilder failureMsg = new StringBuilder(); for (int i = 0; i < rdns.length; i++) { RDN rdn = rdns[i]; AttributeTypeAndValue[] atvs = rdn.getTypesAndValues(); if (atvs.length > 1) { failureMsg.append("size of RDN + [" + i + "] is '" + atvs.length + "' but expected '1'"); failureMsg.append("; "); continue; } ASN1Encodable atvValue = atvs[0].getValue(); boolean correctStringType = true; switch (stringType) { case bmpString: correctStringType = (atvValue instanceof DERBMPString); break; case printableString: correctStringType = (atvValue instanceof DERPrintableString); break; case teletexString: correctStringType = (atvValue instanceof DERT61String); break; case utf8String: correctStringType = (atvValue instanceof DERUTF8String); break; default: throw new RuntimeException("should not reach here, unknown DirectoryStringType " + stringType); } // end switch if (correctStringType == false) { failureMsg.append("RDN + [" + i + "] is not of type DirectoryString." + stringType.name()); failureMsg.append("; "); continue; } String atvTextValue = X509Util.rdnValueToString(atvValue); String coreAtvTextValue = atvTextValue; if (rdnOption != null) { String prefix = rdnOption.getPrefix(); if (prefix != null) { if (coreAtvTextValue.startsWith(prefix) == false) { failureMsg.append("RDN + [" + i + "] '" + atvTextValue + "' does not start with prefix '" + prefix + "'"); failureMsg.append("; "); continue; } else { coreAtvTextValue = coreAtvTextValue.substring(prefix.length()); } } String suffix = rdnOption.getSufix(); if (suffix != null) { if (coreAtvTextValue.endsWith(suffix) == false) { failureMsg.append("RDN + [" + i + "] '" + atvTextValue + "' does not end with suffx '" + suffix + "'"); failureMsg.append("; "); continue; } else { coreAtvTextValue = coreAtvTextValue.substring(0, coreAtvTextValue.length() - suffix.length()); } } List<Pattern> patterns = rdnOption.getPatterns(); if (patterns != null) { Pattern pattern = patterns.get(i); boolean matches = pattern.matcher(coreAtvTextValue).matches(); if (matches == false) { failureMsg.append("RDN + [" + i + "] '" + coreAtvTextValue + "' is not valid against regex '" + pattern.pattern() + "'"); failureMsg.append("; "); continue; } } } if (CollectionUtil.isEmpty(requestedCoreAtvTextValues)) { if (type.equals(ObjectIdentifiers.DN_SERIALNUMBER) == false) { failureMsg.append("is present but not contained in the request"); failureMsg.append("; "); } } else { String requestedCoreAtvTextValue = requestedCoreAtvTextValues.get(i); if (ObjectIdentifiers.DN_CN.equals(type) && specialBehavior != null && "gematik_gSMC_K".equals(specialBehavior)) { if (coreAtvTextValue.startsWith(requestedCoreAtvTextValue + "-") == false) { failureMsg.append("content '" + coreAtvTextValue + "' does not start with '" + requestedCoreAtvTextValue + "-'"); failureMsg.append("; "); } } else if (type.equals(ObjectIdentifiers.DN_SERIALNUMBER)) { } else { if (coreAtvTextValue.equals(requestedCoreAtvTextValue) == false) { failureMsg.append("content '" + coreAtvTextValue + "' but expected '" + requestedCoreAtvTextValue + "'"); failureMsg.append("; "); } } } } int n = failureMsg.length(); if (n > 2) { failureMsg.delete(n - 2, n); issue.setFailureMessage(failureMsg.toString()); } return issue; }
From source file:org.xipki.ca.server.impl.X509CA.java
License:Open Source License
private X509CertificateInfo intern_generateCertificate(final boolean requestedByRA, final RequestorInfo requestor, final String certprofileLocalName, final String user, X500Name requestedSubject, SubjectPublicKeyInfo publicKeyInfo, Date notBefore, Date notAfter, final org.bouncycastle.asn1.x509.Extensions extensions, final boolean keyUpdate) throws OperationException { if (caInfo.getRevocationInfo() != null) { throw new OperationException(ErrorCode.NOT_PERMITTED, "CA is revoked"); }/*from w ww . j a va 2s . c o m*/ IdentifiedX509Certprofile certprofile = getX509Certprofile(certprofileLocalName); if (certprofile == null) { throw new OperationException(ErrorCode.UNKNOWN_CERT_PROFILE, "unknown cert profile " + certprofileLocalName); } ConcurrentContentSigner signer = caInfo.getSigner(certprofile.getSignatureAlgorithms()); if (signer == null) { throw new OperationException(ErrorCode.SYSTEM_FAILURE, "CA does not support any signature algorithm restricted by the cert profile"); } final String certprofileName = certprofile.getName(); if (certprofile.getVersion() != X509CertVersion.V3) { throw new OperationException(ErrorCode.SYSTEM_FAILURE, "unknown cert version " + certprofile); } if (certprofile.isOnlyForRA() && requestedByRA == false) { throw new OperationException(ErrorCode.INSUFFICIENT_PERMISSION, "profile " + certprofileName + " not applied to non-RA"); } requestedSubject = removeEmptyRDNs(requestedSubject); if (certprofile.isSerialNumberInReqPermitted() == false) { RDN[] rdns = requestedSubject.getRDNs(ObjectIdentifiers.DN_SN); if (rdns != null && rdns.length > 0) { throw new OperationException(ErrorCode.BAD_CERT_TEMPLATE, "subjectDN SerialNumber in request is not permitted"); } } notBefore = certprofile.getNotBefore(notBefore); if (notBefore == null) { notBefore = new Date(); } if (certprofile.hasMidnightNotBefore()) { notBefore = setToMidnight(notBefore, certprofile.getTimezone()); } if (notBefore.before(caInfo.getNotBefore())) { notBefore = caInfo.getNotBefore(); if (certprofile.hasMidnightNotBefore()) { notBefore = setToMidnight(new Date(notBefore.getTime() + DAY), certprofile.getTimezone()); } } long t = caInfo.getNoNewCertificateAfter(); if (notBefore.getTime() > t) { throw new OperationException(ErrorCode.NOT_PERMITTED, "CA is not permitted to issue certifate after " + new Date(t)); } try { publicKeyInfo = X509Util.toRfc3279Style(publicKeyInfo); } catch (InvalidKeySpecException e) { throw new OperationException(ErrorCode.BAD_CERT_TEMPLATE, "invalid SubjectPublicKeyInfo"); } // public key try { publicKeyInfo = certprofile.checkPublicKey(publicKeyInfo); } catch (BadCertTemplateException e) { throw new OperationException(ErrorCode.BAD_CERT_TEMPLATE, e.getMessage()); } Date gSMC_KFirstNotBefore = null; if (certprofile.getSpecialCertprofileBehavior() == SpecialX509CertprofileBehavior.gematik_gSMC_K) { gSMC_KFirstNotBefore = notBefore; RDN[] cnRDNs = requestedSubject.getRDNs(ObjectIdentifiers.DN_CN); if (cnRDNs != null && cnRDNs.length > 0) { String requestedCN = X509Util.rdnValueToString(cnRDNs[0].getFirst().getValue()); Long gsmckFirstNotBeforeInSecond = certstore.getNotBeforeOfFirstCertStartsWithCN(requestedCN, certprofileName); if (gsmckFirstNotBeforeInSecond != null) { gSMC_KFirstNotBefore = new Date(gsmckFirstNotBeforeInSecond * MS_PER_SECOND); } // append the commonName with '-' + yyyyMMdd SimpleDateFormat dateF = new SimpleDateFormat("yyyyMMdd"); dateF.setTimeZone(new SimpleTimeZone(0, "Z")); String yyyyMMdd = dateF.format(gSMC_KFirstNotBefore); String suffix = "-" + yyyyMMdd; // append the -yyyyMMdd to the commonName RDN[] rdns = requestedSubject.getRDNs(); for (int i = 0; i < rdns.length; i++) { if (ObjectIdentifiers.DN_CN.equals(rdns[i].getFirst().getType())) { rdns[i] = new RDN(ObjectIdentifiers.DN_CN, new DERUTF8String(requestedCN + suffix)); } } requestedSubject = new X500Name(rdns); } } // end if // subject SubjectInfo subjectInfo; try { subjectInfo = certprofile.getSubject(requestedSubject); } catch (CertprofileException e) { throw new OperationException(ErrorCode.SYSTEM_FAILURE, "exception in cert profile " + certprofileName); } catch (BadCertTemplateException e) { throw new OperationException(ErrorCode.BAD_CERT_TEMPLATE, e.getMessage()); } X500Name grantedSubject = subjectInfo.getGrantedSubject(); // make sure that the grantedSubject does not equal the CA's subject if (grantedSubject.equals(caInfo.getPublicCAInfo().getX500Subject())) { throw new OperationException(ErrorCode.ALREADY_ISSUED, "certificate with the same subject as CA is not allowed"); } DuplicationMode keyMode = caInfo.getDuplicateKeyMode(); if (keyMode == DuplicationMode.PERMITTED && certprofile.isDuplicateKeyPermitted() == false) { keyMode = DuplicationMode.FORBIDDEN_WITHIN_PROFILE; } DuplicationMode subjectMode = caInfo.getDuplicateSubjectMode(); if (subjectMode == DuplicationMode.PERMITTED && certprofile.isDuplicateSubjectPermitted() == false) { subjectMode = DuplicationMode.FORBIDDEN_WITHIN_PROFILE; } String sha1FpSubject = X509Util.sha1sum_canonicalized_name(grantedSubject); String grandtedSubjectText = X509Util.getRFC4519Name(grantedSubject); byte[] subjectPublicKeyData = publicKeyInfo.getPublicKeyData().getBytes(); String sha1FpPublicKey = SecurityUtil.sha1sum(subjectPublicKeyData); if (keyUpdate) { CertStatus certStatus = certstore.getCertStatusForSubject(caInfo.getCertificate(), grantedSubject); if (certStatus == CertStatus.Revoked) { throw new OperationException(ErrorCode.CERT_REVOKED); } else if (certStatus == CertStatus.Unknown) { throw new OperationException(ErrorCode.UNKNOWN_CERT); } } else { // try to get certificate with the same subject, key and certificate profile SubjectKeyProfileBundle bundle = certstore.getLatestCert(caInfo.getCertificate(), sha1FpSubject, sha1FpPublicKey, certprofileName); if (bundle != null) { /* * If there exists a certificate whose public key, subject and profile match the request, * returns the certificate if it is not revoked, otherwise OperationException with * ErrorCode CERT_REVOKED will be thrown */ if (bundle.isRevoked()) { throw new OperationException(ErrorCode.CERT_REVOKED); } else { X509CertWithDBCertId issuedCert = certstore.getCertForId(bundle.getCertId()); if (issuedCert == null) { throw new OperationException(ErrorCode.SYSTEM_FAILURE, "could not find certificate in table RAWCERT for CERT_ID " + bundle.getCertId()); } else { X509CertificateInfo certInfo; try { certInfo = new X509CertificateInfo(issuedCert, caInfo.getCertificate(), subjectPublicKeyData, certprofileName); } catch (CertificateEncodingException e) { throw new OperationException(ErrorCode.SYSTEM_FAILURE, "could not construct CertificateInfo: " + e.getMessage()); } certInfo.setAlreadyIssued(true); return certInfo; } } } // end if(bundle) if (keyMode != DuplicationMode.PERMITTED) { if (keyMode == DuplicationMode.FORBIDDEN) { if (certstore.isCertForKeyIssued(caInfo.getCertificate(), sha1FpPublicKey)) { throw new OperationException(ErrorCode.ALREADY_ISSUED, "certificate for the given public key already issued"); } } else if (keyMode == DuplicationMode.FORBIDDEN_WITHIN_PROFILE) { if (certstore.isCertForKeyIssued(caInfo.getCertificate(), sha1FpPublicKey, certprofileName)) { throw new OperationException(ErrorCode.ALREADY_ISSUED, "certificate for the given public key and profile " + certprofileName + " already issued"); } } else { throw new RuntimeException("should not reach here, unknown key DuplicationMode " + keyMode); } } // end if(keyMode) if (subjectMode != DuplicationMode.PERMITTED) { final boolean incSerial = certprofile.incSerialNumberIfSubjectExists(); final boolean certIssued; if (subjectMode == DuplicationMode.FORBIDDEN) { certIssued = certstore.isCertForSubjectIssued(caInfo.getCertificate(), sha1FpSubject); if (certIssued && incSerial == false) { throw new OperationException(ErrorCode.ALREADY_ISSUED, "certificate for the given subject " + grandtedSubjectText + " already issued"); } } else if (subjectMode == DuplicationMode.FORBIDDEN_WITHIN_PROFILE) { certIssued = certstore.isCertForSubjectIssued(caInfo.getCertificate(), sha1FpSubject, certprofileName); if (certIssued && incSerial == false) { throw new OperationException(ErrorCode.ALREADY_ISSUED, "certificate for the given subject " + grandtedSubjectText + " and profile " + certprofileName + " already issued"); } } else { throw new RuntimeException("should not reach here, unknown subject DuplicationMode " + keyMode); } // end if(subjectMode) if (certIssued) { String latestSN; try { Object[] objs = incSerialNumber(certprofile, grantedSubject, null); latestSN = certstore.getLatestSN((X500Name) objs[0]); } catch (BadFormatException e) { throw new OperationException(ErrorCode.SYSTEM_FAILURE, "BadFormatException: " + e.getMessage()); } boolean foundUniqueSubject = false; // maximal 100 tries for (int i = 0; i < 100; i++) { try { Object[] objs = incSerialNumber(certprofile, grantedSubject, latestSN); grantedSubject = (X500Name) objs[0]; latestSN = (String) objs[1]; } catch (BadFormatException e) { throw new OperationException(ErrorCode.SYSTEM_FAILURE, "BadFormatException: " + e.getMessage()); } foundUniqueSubject = (certstore.certIssuedForSubject(caInfo.getCertificate(), X509Util.sha1sum_canonicalized_name(grantedSubject)) == false); if (foundUniqueSubject) { break; } } if (foundUniqueSubject == false) { throw new OperationException(ErrorCode.ALREADY_ISSUED, "certificate for the given subject " + grandtedSubjectText + " and profile " + certprofileName + " already issued, and could not create new unique serial number"); } } // end if(certIssued) } } // end if(subjectMode != DuplicationMode.PERMITTED) try { boolean addedCertInProcess = certstore.addCertInProcess(sha1FpPublicKey, sha1FpSubject); if (addedCertInProcess == false) { throw new OperationException(ErrorCode.ALREADY_ISSUED, "certificate with the given subject " + grandtedSubjectText + " and/or public key already in process"); } StringBuilder msgBuilder = new StringBuilder(); if (subjectInfo.getWarning() != null) { msgBuilder.append(", ").append(subjectInfo.getWarning()); } CertValidity validity = certprofile.getValidity(); if (validity == null) { validity = caInfo.getMaxValidity(); } else if (validity.compareTo(caInfo.getMaxValidity()) > 0) { validity = caInfo.getMaxValidity(); } Date maxNotAfter = validity.add(notBefore); Date origMaxNotAfter = maxNotAfter; if (certprofile.getSpecialCertprofileBehavior() == SpecialX509CertprofileBehavior.gematik_gSMC_K) { String s = certprofile.getParameter(SpecialX509CertprofileBehavior.PARAMETER_MAXLIFTIME); long maxLifetimeInDays = Long.parseLong(s); Date maxLifetime = new Date( gSMC_KFirstNotBefore.getTime() + maxLifetimeInDays * DAY - MS_PER_SECOND); if (maxNotAfter.after(maxLifetime)) { maxNotAfter = maxLifetime; } } if (notAfter != null) { if (notAfter.after(maxNotAfter)) { notAfter = maxNotAfter; msgBuilder.append(", NotAfter modified"); } } else { notAfter = maxNotAfter; } if (notAfter.after(caInfo.getNotAfter())) { ValidityMode mode = caInfo.getValidityMode(); if (mode == ValidityMode.CUTOFF) { notAfter = caInfo.getNotAfter(); } else if (mode == ValidityMode.STRICT) { throw new OperationException(ErrorCode.NOT_PERMITTED, "notAfter outside of CA's validity is not permitted"); } else if (mode == ValidityMode.LAX) { // permitted } else { throw new RuntimeException("should not reach here, unknown CA ValidityMode " + mode); } // end if(mode) } // end if(notAfter) if (certprofile.hasMidnightNotBefore() && maxNotAfter.equals(origMaxNotAfter) == false) { Calendar c = Calendar.getInstance(certprofile.getTimezone()); c.setTime(new Date(notAfter.getTime() - DAY)); c.set(Calendar.HOUR_OF_DAY, 23); c.set(Calendar.MINUTE, 59); c.set(Calendar.SECOND, 59); c.set(Calendar.MILLISECOND, 0); notAfter = c.getTime(); } try { RdnUpperBounds.checkUpperBounds(grantedSubject); } catch (BadCertTemplateException e) { throw new OperationException(ErrorCode.BAD_CERT_TEMPLATE, e.getMessage()); } X509v3CertificateBuilder certBuilder = new X509v3CertificateBuilder( caInfo.getPublicCAInfo().getX500Subject(), caInfo.nextSerial(), notBefore, notAfter, grantedSubject, publicKeyInfo); X509CertificateInfo ret; try { X509CrlSignerEntryWrapper crlSigner = getCrlSigner(); X509Certificate crlSignerCert = crlSigner == null ? null : crlSigner.getCert(); ExtensionValues extensionTuples = certprofile.getExtensions(requestedSubject, extensions, publicKeyInfo, caInfo.getPublicCAInfo(), crlSignerCert); if (extensionTuples != null) { for (ASN1ObjectIdentifier extensionType : extensionTuples.getExtensionTypes()) { ExtensionValue extValue = extensionTuples.getExtensionValue(extensionType); certBuilder.addExtension(extensionType, extValue.isCritical(), extValue.getValue()); } } ContentSigner contentSigner; try { contentSigner = signer.borrowContentSigner(); } catch (NoIdleSignerException e) { throw new OperationException(ErrorCode.SYSTEM_FAILURE, "NoIdleSignerException: " + e.getMessage()); } Certificate bcCert; try { bcCert = certBuilder.build(contentSigner).toASN1Structure(); } finally { signer.returnContentSigner(contentSigner); } byte[] encodedCert = bcCert.getEncoded(); X509Certificate cert = (X509Certificate) cf .engineGenerateCertificate(new ByteArrayInputStream(encodedCert)); if (verifySignature(cert) == false) { throw new OperationException(ErrorCode.SYSTEM_FAILURE, "could not verify the signature of generated certificate"); } X509CertWithDBCertId certWithMeta = new X509CertWithDBCertId(cert, encodedCert); ret = new X509CertificateInfo(certWithMeta, caInfo.getCertificate(), subjectPublicKeyData, certprofileName); ret.setUser(user); ret.setRequestor(requestor); if (intern_publishCertificate(ret) == 1) { throw new OperationException(ErrorCode.SYSTEM_FAILURE, "could not save certificate"); } } catch (BadCertTemplateException e) { throw new OperationException(ErrorCode.BAD_CERT_TEMPLATE, e.getMessage()); } catch (Throwable t2) { final String message = "could not generate certificate"; if (LOG.isErrorEnabled()) { LOG.error(LogUtil.buildExceptionLogFormat(message), t2.getClass().getName(), t2.getMessage()); } LOG.debug(message, t2); throw new OperationException(ErrorCode.SYSTEM_FAILURE, t2.getClass().getName() + ": " + t2.getMessage()); } if (msgBuilder.length() > 2) { ret.setWarningMessage(msgBuilder.substring(2)); } return ret; } finally { try { certstore.delteCertInProcess(sha1FpPublicKey, sha1FpSubject); } catch (OperationException e) { } } }
From source file:org.xipki.common.util.X509Util.java
License:Open Source License
public static String getCommonName(final X500Name name) { RDN[] rdns = name.getRDNs(ObjectIdentifiers.DN_CN); if (rdns != null && rdns.length > 0) { return rdnValueToString(rdns[0].getFirst().getValue()); }//from w w w.jav a 2s . c o m return null; }
From source file:org.xipki.common.util.X509Util.java
License:Open Source License
public static String canonicalizName(final X500Name name) { ASN1ObjectIdentifier[] _types = name.getAttributeTypes(); int n = _types.length; List<String> types = new ArrayList<>(n); for (ASN1ObjectIdentifier type : _types) { types.add(type.getId());/*from w w w . j a va 2s. co m*/ } Collections.sort(types); StringBuilder sb = new StringBuilder(); for (int i = 0; i < n; i++) { String type = types.get(i); if (i > 0) { sb.append(","); } sb.append(type).append("="); RDN[] rdns = name.getRDNs(new ASN1ObjectIdentifier(type)); for (int j = 0; j < rdns.length; j++) { if (j > 0) { sb.append(";"); } RDN rdn = rdns[j]; String textValue = IETFUtils.valueToString(rdn.getFirst().getValue()).toLowerCase(); sb.append(textValue); } } return sb.toString(); }
From source file:org.xipki.commons.security.util.X509Util.java
License:Open Source License
public static String getCommonName(final X500Name name) { ParamUtil.requireNonNull("name", name); RDN[] rdns = name.getRDNs(ObjectIdentifiers.DN_CN); if (rdns != null && rdns.length > 0) { RDN rdn = rdns[0];/*from w w w .j a va 2 s. com*/ AttributeTypeAndValue atv = null; if (rdn.isMultiValued()) { for (AttributeTypeAndValue m : rdn.getTypesAndValues()) { if (m.getType().equals(ObjectIdentifiers.DN_CN)) { atv = m; break; } } } else { atv = rdn.getFirst(); } return (atv == null) ? null : rdnValueToString(atv.getValue()); } return null; }
From source file:org.xipki.commons.security.util.X509Util.java
License:Open Source License
public static String canonicalizName(final X500Name name) { ParamUtil.requireNonNull("name", name); ASN1ObjectIdentifier[] tmpTypes = name.getAttributeTypes(); int len = tmpTypes.length; List<String> types = new ArrayList<>(len); for (ASN1ObjectIdentifier type : tmpTypes) { types.add(type.getId());/*from ww w . j av a2s. c o m*/ } Collections.sort(types); StringBuilder sb = new StringBuilder(); for (int i = 0; i < len; i++) { String type = types.get(i); if (i > 0) { sb.append(","); } sb.append(type).append("="); RDN[] rdns = name.getRDNs(new ASN1ObjectIdentifier(type)); List<String> values = new ArrayList<>(1); for (int j = 0; j < rdns.length; j++) { RDN rdn = rdns[j]; if (rdn.isMultiValued()) { AttributeTypeAndValue[] atvs = rdn.getTypesAndValues(); for (AttributeTypeAndValue atv : atvs) { if (type.equals(atv.getType().getId())) { String textValue = IETFUtils.valueToString(atv.getValue()).toLowerCase(); values.add(textValue); } } } else { String textValue = IETFUtils.valueToString(rdn.getFirst().getValue()).toLowerCase(); values.add(textValue); } } // end for(j) sb.append(values.get(0)); final int n2 = values.size(); if (n2 > 1) { for (int j = 1; j < n2; j++) { sb.append(";").append(values.get(j)); } } } // end for(i) return sb.toString(); }
From source file:org.xipki.pki.ca.api.profile.x509.BaseX509Certprofile.java
License:Open Source License
protected void verifySubjectDnOccurence(final X500Name requestedSubject) throws BadCertTemplateException { ParamUtil.requireNonNull("requestedSubject", requestedSubject); SubjectControl occurences = getSubjectControl(); if (occurences == null) { return;//from w ww.j a v a2 s.c o m } ASN1ObjectIdentifier[] types = requestedSubject.getAttributeTypes(); for (ASN1ObjectIdentifier type : types) { RdnControl occu = occurences.getControl(type); if (occu == null) { throw new BadCertTemplateException( String.format("subject DN of type %s is not allowed", oidToDisplayName(type))); } RDN[] rdns = requestedSubject.getRDNs(type); if (rdns.length > occu.getMaxOccurs() || rdns.length < occu.getMinOccurs()) { throw new BadCertTemplateException(String.format( "occurrence of subject DN of type %s not within the allowed range. " + "%d is not within [%d, %d]", oidToDisplayName(type), rdns.length, occu.getMinOccurs(), occu.getMaxOccurs())); } } for (ASN1ObjectIdentifier m : occurences.getTypes()) { RdnControl occurence = occurences.getControl(m); if (occurence.getMinOccurs() == 0) { continue; } boolean present = false; for (ASN1ObjectIdentifier type : types) { if (occurence.getType().equals(type)) { present = true; break; } } if (!present) { throw new BadCertTemplateException(String.format("required subject DN of type %s is not present", oidToDisplayName(occurence.getType()))); } } }
From source file:org.xipki.pki.ca.certprofile.XmlX509Certprofile.java
License:Open Source License
private GeneralNames createRequestedSubjectAltNames(final X500Name requestedSubject, final X500Name grantedSubject, final Extensions requestedExtensions) throws BadCertTemplateException { ASN1Encodable extValue = (requestedExtensions == null) ? null : requestedExtensions.getExtensionParsedValue(Extension.subjectAlternativeName); if (extValue == null && subjectToSubjectAltNameModes == null) { return null; }/*w w w . j a v a 2 s . c o m*/ GeneralNames reqNames = (extValue == null) ? null : GeneralNames.getInstance(extValue); if (subjectAltNameModes == null && subjectToSubjectAltNameModes == null) { return reqNames; } List<GeneralName> grantedNames = new LinkedList<>(); // copy the required attributes of Subject if (subjectToSubjectAltNameModes != null) { for (ASN1ObjectIdentifier attrType : subjectToSubjectAltNameModes.keySet()) { GeneralNameTag tag = subjectToSubjectAltNameModes.get(attrType); RDN[] rdns = grantedSubject.getRDNs(attrType); if (rdns == null) { rdns = requestedSubject.getRDNs(attrType); } if (rdns == null) { continue; } for (RDN rdn : rdns) { String rdnValue = X509Util.rdnValueToString(rdn.getFirst().getValue()); switch (tag) { case rfc822Name: case dNSName: case uniformResourceIdentifier: case iPAddress: case directoryName: case registeredID: grantedNames.add(new GeneralName(tag.getTag(), rdnValue)); break; default: throw new RuntimeException("should not reach here, unknown GeneralName tag " + tag); } // end switch (tag) } } } // copy the requested SubjectAltName entries if (reqNames != null) { GeneralName[] reqL = reqNames.getNames(); for (int i = 0; i < reqL.length; i++) { grantedNames.add(X509CertprofileUtil.createGeneralName(reqL[i], subjectAltNameModes)); } } return grantedNames.isEmpty() ? null : new GeneralNames(grantedNames.toArray(new GeneralName[0])); }
From source file:org.xipki.pki.ca.qa.ExtensionsChecker.java
License:Open Source License
private GeneralName[] getRequestedSubjectAltNames(final X500Name requestedSubject, final Extensions requestedExtensions) throws CertprofileException, BadCertTemplateException { ASN1Encodable extValue = (requestedExtensions == null) ? null : requestedExtensions.getExtensionParsedValue(Extension.subjectAlternativeName); Map<ASN1ObjectIdentifier, GeneralNameTag> subjectToSubjectAltNameModes = certProfile .getSubjectToSubjectAltNameModes(); if (extValue == null && subjectToSubjectAltNameModes == null) { return null; }//from ww w. j a va 2 s .c om GeneralNames reqNames = (extValue == null) ? null : GeneralNames.getInstance(extValue); Set<GeneralNameMode> subjectAltNameModes = certProfile.getSubjectAltNameModes(); if (subjectAltNameModes == null && subjectToSubjectAltNameModes == null) { return (reqNames == null) ? null : reqNames.getNames(); } List<GeneralName> grantedNames = new LinkedList<>(); // copy the required attributes of Subject if (subjectToSubjectAltNameModes != null) { X500Name grantedSubject; try { grantedSubject = certProfile.getSubject(requestedSubject).getGrantedSubject(); } catch (CertprofileException | BadCertTemplateException ex) { if (certProfile.getSpecialCertprofileBehavior() == null) { throw ex; } LogUtil.warn(LOG, ex, "could not derive granted subject from requested subject"); grantedSubject = requestedSubject; } for (ASN1ObjectIdentifier attrType : subjectToSubjectAltNameModes.keySet()) { GeneralNameTag tag = subjectToSubjectAltNameModes.get(attrType); RDN[] rdns = grantedSubject.getRDNs(attrType); if (rdns == null) { rdns = requestedSubject.getRDNs(attrType); } if (rdns == null) { continue; } for (RDN rdn : rdns) { String rdnValue = X509Util.rdnValueToString(rdn.getFirst().getValue()); switch (tag) { case rfc822Name: case dNSName: case uniformResourceIdentifier: case iPAddress: case directoryName: case registeredID: grantedNames.add(new GeneralName(tag.getTag(), rdnValue)); break; default: throw new RuntimeException("should not reach here, unknown GeneralName tag " + tag); } // end switch (tag) } } } // copy the requested SubjectAltName entries if (reqNames != null) { GeneralName[] reqL = reqNames.getNames(); for (int i = 0; i < reqL.length; i++) { grantedNames.add(reqL[i]); } } return grantedNames.isEmpty() ? null : grantedNames.toArray(new GeneralName[0]); }