List of usage examples for org.bouncycastle.asn1.x500 X500Name X500Name
public X500Name(String dirName)
From source file:org.xipki.pki.ca.api.profile.x509.BaseX509Certprofile.java
License:Open Source License
@Override public SubjectInfo getSubject(final X500Name requestedSubject) throws CertprofileException, BadCertTemplateException { ParamUtil.requireNonNull("requestedSubject", requestedSubject); verifySubjectDnOccurence(requestedSubject); RDN[] requstedRdns = requestedSubject.getRDNs(); SubjectControl scontrol = getSubjectControl(); List<RDN> rdns = new LinkedList<>(); for (ASN1ObjectIdentifier type : scontrol.getTypes()) { RdnControl control = scontrol.getControl(type); if (control == null) { continue; }//from w w w . ja v a2 s .c o m RDN[] thisRdns = getRdns(requstedRdns, type); if (thisRdns == null) { continue; } int len = thisRdns.length; if (len == 0) { continue; } if (ObjectIdentifiers.DN_EmailAddress.equals(type)) { throw new BadCertTemplateException("emailAddress is not allowed"); } if (len == 1) { ASN1Encodable rdnValue = thisRdns[0].getFirst().getValue(); RDN rdn; if (ObjectIdentifiers.DN_DATE_OF_BIRTH.equals(type)) { rdn = createDateOfBirthRdn(type, rdnValue); } else if (ObjectIdentifiers.DN_POSTAL_ADDRESS.equals(type)) { rdn = createPostalAddressRdn(type, rdnValue, control, 0); } else { String value = X509Util.rdnValueToString(rdnValue); rdn = createSubjectRdn(value, type, control, 0); } if (rdn != null) { rdns.add(rdn); } } else { if (ObjectIdentifiers.DN_DATE_OF_BIRTH.equals(type)) { for (int i = 0; i < len; i++) { RDN rdn = createDateOfBirthRdn(type, thisRdns[i].getFirst().getValue()); rdns.add(rdn); } } else if (ObjectIdentifiers.DN_POSTAL_ADDRESS.equals(type)) { for (int i = 0; i < len; i++) { RDN rdn = createPostalAddressRdn(type, thisRdns[i].getFirst().getValue(), control, i); rdns.add(rdn); } } else { String[] values = new String[len]; for (int i = 0; i < len; i++) { values[i] = X509Util.rdnValueToString(thisRdns[i].getFirst().getValue()); } values = sortRdns(control, values); int idx = 0; for (String value : values) { rdns.add(createSubjectRdn(value, type, control, idx++)); } } // if } // if } // for Set<String> subjectDnGroups = scontrol.getGroups(); if (CollectionUtil.isNonEmpty(subjectDnGroups)) { Set<String> consideredGroups = new HashSet<>(); final int n = rdns.size(); List<RDN> newRdns = new ArrayList<>(rdns.size()); for (int i = 0; i < n; i++) { RDN rdn = rdns.get(i); ASN1ObjectIdentifier type = rdn.getFirst().getType(); String group = scontrol.getGroup(type); if (group == null) { newRdns.add(rdn); } else if (!consideredGroups.contains(group)) { List<AttributeTypeAndValue> atvs = new LinkedList<>(); atvs.add(rdn.getFirst()); for (int j = i + 1; j < n; j++) { RDN rdn2 = rdns.get(j); ASN1ObjectIdentifier type2 = rdn2.getFirst().getType(); String group2 = scontrol.getGroup(type2); if (group.equals(group2)) { atvs.add(rdn2.getFirst()); } } newRdns.add(new RDN(atvs.toArray(new AttributeTypeAndValue[0]))); consideredGroups.add(group); } } // for rdns = newRdns; } // if X500Name grantedSubject = new X500Name(rdns.toArray(new RDN[0])); return new SubjectInfo(grantedSubject, null); }
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/*from w ww. j a v a 2s . co 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.XmlX509CertprofileUtil.java
License:Open Source License
private static GeneralSubtree buildGeneralSubtree(final GeneralSubtreeBaseType type) throws CertprofileException { ParamUtil.requireNonNull("type", type); GeneralName base = null;/*from w w w. ja v a 2s. c o m*/ if (type.getDirectoryName() != null) { base = new GeneralName(X509Util.reverse(new X500Name(type.getDirectoryName()))); } else if (type.getDnsName() != null) { base = new GeneralName(GeneralName.dNSName, type.getDnsName()); } else if (type.getIpAddress() != null) { base = new GeneralName(GeneralName.iPAddress, type.getIpAddress()); } else if (type.getRfc822Name() != null) { base = new GeneralName(GeneralName.rfc822Name, type.getRfc822Name()); } else if (type.getUri() != null) { base = new GeneralName(GeneralName.uniformResourceIdentifier, type.getUri()); } else { throw new RuntimeException("should not reach here, unknown child of GeneralSubtreeBaseType"); } Integer min = type.getMinimum(); if (min != null && min < 0) { throw new CertprofileException("negative minimum is not allowed: " + min); } BigInteger minimum = (min == null) ? null : BigInteger.valueOf(min.intValue()); Integer max = type.getMaximum(); if (max != null && max < 0) { throw new CertprofileException("negative maximum is not allowed: " + max); } BigInteger maximum = (max == null) ? null : BigInteger.valueOf(max.intValue()); return new GeneralSubtree(base, minimum, maximum); }
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 .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
private void checkExtensionNameConstraintsSubtrees(final StringBuilder failureMsg, final String description, final GeneralSubtree[] subtrees, final List<QaGeneralSubtree> expectedSubtrees) { int isSize = (subtrees == null) ? 0 : subtrees.length; int expSize = (expectedSubtrees == null) ? 0 : expectedSubtrees.size(); if (isSize != expSize) { addViolation(failureMsg, "size of " + description, isSize, expSize); return;//from ww w . j a v a2 s . c o m } if (subtrees == null || expectedSubtrees == null) { return; } for (int i = 0; i < isSize; i++) { GeneralSubtree isSubtree = subtrees[i]; QaGeneralSubtree expSubtree = expectedSubtrees.get(i); BigInteger bigInt = isSubtree.getMinimum(); int isMinimum = (bigInt == null) ? 0 : bigInt.intValue(); Integer minimum = expSubtree.getMinimum(); int expMinimum = (minimum == null) ? 0 : minimum.intValue(); String desc = description + " [" + i + "]"; if (isMinimum != expMinimum) { addViolation(failureMsg, "minimum of " + desc, isMinimum, expMinimum); } bigInt = isSubtree.getMaximum(); Integer isMaximum = (bigInt == null) ? null : bigInt.intValue(); Integer expMaximum = expSubtree.getMaximum(); if (!CompareUtil.equalsObject(isMaximum, expMaximum)) { addViolation(failureMsg, "maxmum of " + desc, isMaximum, expMaximum); } GeneralName isBase = isSubtree.getBase(); GeneralName expBase; if (expSubtree.getDirectoryName() != null) { expBase = new GeneralName(X509Util.reverse(new X500Name(expSubtree.getDirectoryName()))); } else if (expSubtree.getDnsName() != null) { expBase = new GeneralName(GeneralName.dNSName, expSubtree.getDnsName()); } else if (expSubtree.getIpAddress() != null) { expBase = new GeneralName(GeneralName.iPAddress, expSubtree.getIpAddress()); } else if (expSubtree.getRfc822Name() != null) { expBase = new GeneralName(GeneralName.rfc822Name, expSubtree.getRfc822Name()); } else if (expSubtree.getUri() != null) { expBase = new GeneralName(GeneralName.uniformResourceIdentifier, expSubtree.getUri()); } else { throw new RuntimeException("should not reach here, unknown child of GeneralName"); } if (!isBase.equals(expBase)) { addViolation(failureMsg, "base of " + desc, isBase, expBase); } } }
From source file:org.xipki.pki.ca.qa.shell.NegEnrollCertCommandSupport.java
License:Open Source License
@Override protected Object doExecute() throws Exception { EnrollCertRequest request = new EnrollCertRequest(EnrollCertRequest.Type.CERT_REQ); CertTemplateBuilder certTemplateBuilder = new CertTemplateBuilder(); ConcurrentContentSigner signer = getSigner(new SignatureAlgoControl(rsaMgf1, dsaPlain)); X509CertificateHolder ssCert = signer.getCertificateAsBcObject(); X500Name x500Subject = (subject == null) ? ssCert.getSubject() : new X500Name(subject); certTemplateBuilder.setSubject(x500Subject); certTemplateBuilder.setPublicKey(ssCert.getSubjectPublicKeyInfo()); 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); request.addRequestEntry(reqEntry);/*from www . jav a 2 s . c om*/ EnrollCertResult result; RequestResponseDebug debug = getRequestResponseDebug(); 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 is excepted, but received one"); } return null; }
From source file:org.xipki.pki.ca.server.impl.store.CertStoreQueryExecutor.java
License:Open Source License
List<CertListInfo> listCertificates(final X509Cert caCert, final X500Name subjectPattern, final Date validFrom, final Date validTo, final CertListOrderBy orderBy, final int numEntries) throws DataAccessException, OperationException { ParamUtil.requireNonNull("caCert", caCert); ParamUtil.requireMin("numEntries", numEntries, 1); int caId = getCaId(caCert); StringBuilder sb = new StringBuilder(200); sb.append("SN,NBEFORE,NAFTER,SUBJECT FROM CERT WHERE CA_ID=?"); //.append(caId) Integer idxNotBefore = null;/* w ww . j a v a 2 s . co m*/ Integer idxNotAfter = null; Integer idxSubject = null; int idx = 2; if (validFrom != null) { idxNotBefore = idx++; sb.append(" AND NBEFORE<?"); } if (validTo != null) { idxNotAfter = idx++; sb.append(" AND NAFTER>?"); } String subjectLike = null; if (subjectPattern != null) { idxSubject = idx++; sb.append(" AND SUBJECT LIKE ?"); StringBuilder buffer = new StringBuilder(100); buffer.append("%"); RDN[] rdns = subjectPattern.getRDNs(); for (int i = 0; i < rdns.length; i++) { X500Name rdnName = new X500Name(new RDN[] { rdns[i] }); String rdnStr = X509Util.getRfc4519Name(rdnName); if (rdnStr.indexOf('%') != -1) { throw new OperationException(ErrorCode.BAD_REQUEST, "the character '%' is not allowed in subjectPattern"); } if (rdnStr.indexOf('*') != -1) { rdnStr = rdnStr.replace('*', '%'); } buffer.append(rdnStr); buffer.append("%"); } subjectLike = buffer.toString(); } String sortByStr = null; if (orderBy != null) { switch (orderBy) { case NOT_BEFORE: sortByStr = "NBEFORE"; break; case NOT_BEFORE_DESC: sortByStr = "NBEFORE DESC"; break; case NOT_AFTER: sortByStr = "NAFTER"; break; case NOT_AFTER_DESC: sortByStr = "NAFTER DESC"; break; case SUBJECT: sortByStr = "SUBJECT"; break; case SUBJECT_DESC: sortByStr = "SUBJECT DESC"; break; default: throw new RuntimeException("unknown CertListOrderBy " + orderBy); } } final String sql = datasource.buildSelectFirstSql(sb.toString(), numEntries, sortByStr); ResultSet rs = null; PreparedStatement ps = borrowPreparedStatement(sql); List<CertListInfo> ret = new LinkedList<>(); try { ps.setInt(1, caId); if (idxNotBefore != null) { @SuppressWarnings("null") long time = validFrom.getTime() / 1000; ps.setLong(idxNotBefore, time - 1); } if (idxNotAfter != null) { @SuppressWarnings("null") long time = validTo.getTime() / 1000; ps.setLong(idxNotAfter, time); } if (idxSubject != null) { ps.setString(idxSubject, subjectLike); } rs = ps.executeQuery(); while (rs.next()) { String snStr = rs.getString("SN"); BigInteger sn = new BigInteger(snStr, 16); Date notBefore = new Date(rs.getLong("NBEFORE") * 1000); Date notAfter = new Date(rs.getLong("NAFTER") * 1000); String subject = rs.getString("SUBJECT"); CertListInfo info = new CertListInfo(sn, subject, notBefore, notAfter); ret.add(info); } } catch (SQLException ex) { throw datasource.translate(sql, ex); } finally { releaseDbResources(ps, rs); } return ret; }
From source file:org.xipki.pki.ca.server.impl.store.CertStoreQueryExecutor.java
License:Open Source License
String getLatestSerialNumber(final X500Name nameWithSn) throws OperationException { RDN[] rdns1 = nameWithSn.getRDNs();//from w w w. j a va2 s. c o m RDN[] rdns2 = new RDN[rdns1.length]; for (int i = 0; i < rdns1.length; i++) { RDN rdn = rdns1[i]; rdns2[i] = rdn.getFirst().getType().equals(ObjectIdentifiers.DN_SERIALNUMBER) ? new RDN(ObjectIdentifiers.DN_SERIALNUMBER, new DERPrintableString("%")) : rdn; } String namePattern = X509Util.getRfc4519Name(new X500Name(rdns2)); final String sql = sqls.sqlLatestSerialForSubjectLike; ; ResultSet rs = null; PreparedStatement ps; try { ps = borrowPreparedStatement(sql); } catch (DataAccessException ex) { throw new OperationException(ErrorCode.DATABASE_FAILURE, ex.getMessage()); } String subjectStr; try { ps.setString(1, namePattern); rs = ps.executeQuery(); if (!rs.next()) { return null; } subjectStr = rs.getString("SUBJECT"); } catch (SQLException ex) { throw new OperationException(ErrorCode.DATABASE_FAILURE, ex.getMessage()); } finally { releaseDbResources(ps, rs); } X500Name lastName = new X500Name(subjectStr); RDN[] rdns = lastName.getRDNs(ObjectIdentifiers.DN_SERIALNUMBER); if (rdns == null || rdns.length == 0) { return null; } return X509Util.rdnValueToString(rdns[0].getFirst().getValue()); }
From source file:org.xipki.pki.ca.server.impl.util.CaUtil.java
License:Open Source License
public static X500Name sortX509Name(final X500Name name) { ParamUtil.requireNonNull("name", name); RDN[] requstedRdns = name.getRDNs(); List<RDN> rdns = new LinkedList<>(); List<ASN1ObjectIdentifier> sortedDNs = SubjectDnSpec.getForwardDNs(); int size = sortedDNs.size(); for (int i = 0; i < size; i++) { ASN1ObjectIdentifier type = sortedDNs.get(i); RDN[] thisRdns = getRdns(requstedRdns, type); if (thisRdns == null) { continue; }//from w w w . jav a2 s . c o m if (thisRdns.length == 0) { continue; } for (RDN m : thisRdns) { rdns.add(m); } } return new X500Name(rdns.toArray(new RDN[0])); }
From source file:org.xipki.pki.ca.server.impl.X509Ca.java
License:Open Source License
private GrantedCertTemplate createGrantedCertTemplate(final CertTemplateData certTemplate, final boolean requestedByRa, final RequestorInfo requestor, final boolean keyUpdate) throws OperationException { ParamUtil.requireNonNull("certTemplate", certTemplate); if (caInfo.getRevocationInfo() != null) { throw new OperationException(ErrorCode.NOT_PERMITTED, "CA is revoked"); }/*w w w.ja va 2 s . com*/ IdentifiedX509Certprofile certprofile = getX509Certprofile(certTemplate.getCertprofileName()); if (certprofile == null) { throw new OperationException(ErrorCode.UNKNOWN_CERT_PROFILE, "unknown cert profile " + certTemplate.getCertprofileName()); } 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.getVersion()); } if (certprofile.isOnlyForRa() && !requestedByRa) { throw new OperationException(ErrorCode.NOT_PERMITTED, "profile " + certprofileName + " not applied to non-RA"); } X500Name requestedSubject = removeEmptyRdns(certTemplate.getSubject()); if (!certprofile.isSerialNumberInReqPermitted()) { 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"); } } Date now = new Date(); Date reqNotBefore; if (certTemplate.getNotBefore() != null && certTemplate.getNotBefore().after(now)) { reqNotBefore = certTemplate.getNotBefore(); } else { reqNotBefore = now; } Date grantedNotBefore = certprofile.getNotBefore(reqNotBefore); // notBefore in the past is not permitted if (grantedNotBefore.before(now)) { grantedNotBefore = now; } if (certprofile.hasMidnightNotBefore()) { grantedNotBefore = setToMidnight(grantedNotBefore, certprofile.getTimezone()); } if (grantedNotBefore.before(caInfo.getNotBefore())) { grantedNotBefore = caInfo.getNotBefore(); if (certprofile.hasMidnightNotBefore()) { grantedNotBefore = setToMidnight(grantedNotBefore, certprofile.getTimezone()); } } long time = caInfo.getNoNewCertificateAfter(); if (grantedNotBefore.getTime() > time) { throw new OperationException(ErrorCode.NOT_PERMITTED, "CA is not permitted to issue certifate after " + new Date(time)); } SubjectPublicKeyInfo grantedPublicKeyInfo; try { grantedPublicKeyInfo = X509Util.toRfc3279Style(certTemplate.getPublicKeyInfo()); } catch (InvalidKeySpecException ex) { throw new OperationException(ErrorCode.BAD_CERT_TEMPLATE, "invalid SubjectPublicKeyInfo"); } // public key try { grantedPublicKeyInfo = certprofile.checkPublicKey(grantedPublicKeyInfo); } catch (BadCertTemplateException ex) { throw new OperationException(ErrorCode.BAD_CERT_TEMPLATE, ex); } Date gsmckFirstNotBefore = null; if (certprofile.getSpecialCertprofileBehavior() == SpecialX509CertprofileBehavior.gematik_gSMC_K) { gsmckFirstNotBefore = grantedNotBefore; RDN[] cnRdns = requestedSubject.getRDNs(ObjectIdentifiers.DN_CN); if (cnRdns != null && cnRdns.length > 0) { String requestedCn = X509Util.rdnValueToString(cnRdns[0].getFirst().getValue()); Long gsmckFirstNotBeforeInSecond = certstore .getNotBeforeOfFirstCertStartsWithCommonName(requestedCn, certprofileName); if (gsmckFirstNotBeforeInSecond != null) { gsmckFirstNotBefore = 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(gsmckFirstNotBefore); 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 } // end if // subject SubjectInfo subjectInfo; try { subjectInfo = certprofile.getSubject(requestedSubject); } catch (CertprofileException ex) { throw new OperationException(ErrorCode.SYSTEM_FAILURE, "exception in cert profile " + certprofileName); } catch (BadCertTemplateException ex) { throw new OperationException(ErrorCode.BAD_CERT_TEMPLATE, ex); } X500Name grantedSubject = subjectInfo.getGrantedSubject(); // make sure that empty subject is not permitted ASN1ObjectIdentifier[] attrTypes = grantedSubject.getAttributeTypes(); if (attrTypes == null || attrTypes.length == 0) { throw new OperationException(ErrorCode.BAD_CERT_TEMPLATE, "empty subject is not permitted"); } // make sure that the grantedSubject does not equal the CA's subject if (X509Util.canonicalizName(grantedSubject).equals(caInfo.getPublicCaInfo().getC14nSubject())) { throw new OperationException(ErrorCode.ALREADY_ISSUED, "certificate with the same subject as CA is not allowed"); } boolean duplicateKeyPermitted = caInfo.isDuplicateKeyPermitted(); if (duplicateKeyPermitted && !certprofile.isDuplicateKeyPermitted()) { duplicateKeyPermitted = false; } byte[] subjectPublicKeyData = grantedPublicKeyInfo.getPublicKeyData().getBytes(); long fpPublicKey = FpIdCalculator.hash(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 { if (!duplicateKeyPermitted) { if (certstore.isCertForKeyIssued(caInfo.getCertificate(), fpPublicKey)) { throw new OperationException(ErrorCode.ALREADY_ISSUED, "certificate for the given public key already issued"); } } // duplicateSubject check will be processed later } // end if(keyUpdate) 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(grantedNotBefore); if (maxNotAfter.getTime() > MAX_CERT_TIME_MS) { maxNotAfter = new Date(MAX_CERT_TIME_MS); } // CHECKSTYLE:SKIP Date origMaxNotAfter = maxNotAfter; if (certprofile.getSpecialCertprofileBehavior() == SpecialX509CertprofileBehavior.gematik_gSMC_K) { String str = certprofile.getParameter(SpecialX509CertprofileBehavior.PARAMETER_MAXLIFTIME); long maxLifetimeInDays = Long.parseLong(str); @SuppressWarnings("null") Date maxLifetime = new Date( gsmckFirstNotBefore.getTime() + maxLifetimeInDays * DAY_IN_MS - MS_PER_SECOND); if (maxNotAfter.after(maxLifetime)) { maxNotAfter = maxLifetime; } } Date grantedNotAfter = certTemplate.getNotAfter(); if (grantedNotAfter != null) { if (grantedNotAfter.after(maxNotAfter)) { grantedNotAfter = maxNotAfter; msgBuilder.append(", notAfter modified"); } } else { grantedNotAfter = maxNotAfter; } if (grantedNotAfter.after(caInfo.getNotAfter())) { ValidityMode mode = caInfo.getValidityMode(); if (mode == ValidityMode.CUTOFF) { grantedNotAfter = 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)) { Calendar cal = Calendar.getInstance(certprofile.getTimezone()); cal.setTime(new Date(grantedNotAfter.getTime() - DAY_IN_MS)); cal.set(Calendar.HOUR_OF_DAY, 23); cal.set(Calendar.MINUTE, 59); cal.set(Calendar.SECOND, 59); cal.set(Calendar.MILLISECOND, 0); grantedNotAfter = cal.getTime(); } String warning = null; if (msgBuilder.length() > 2) { warning = msgBuilder.substring(2); } GrantedCertTemplate gct = new GrantedCertTemplate(certTemplate.getExtensions(), certprofile, grantedNotBefore, grantedNotAfter, requestedSubject, grantedPublicKeyInfo, fpPublicKey, subjectPublicKeyData, signer, warning); gct.setGrantedSubject(grantedSubject); return gct; }