List of usage examples for org.bouncycastle.asn1.x500 RDN RDN
public RDN(ASN1ObjectIdentifier oid, ASN1Encodable value)
From source file:org.xipki.ca.api.profile.x509.BaseX509Certprofile.java
License:Open Source License
protected RDN createSubjectRDN(final String text, final ASN1ObjectIdentifier type, final RDNControl rdnControl, final int index) throws BadCertTemplateException { DirectoryStringType dsEnum = rdnControl == null ? null : rdnControl.getDirectoryStringEnum(); if (dsEnum == null) { if (ObjectIdentifiers.DN_SERIALNUMBER.equals(type) || ObjectIdentifiers.DN_C.equals(type)) { dsEnum = DirectoryStringType.printableString; } else {//from w ww. j av a2s.c o m dsEnum = DirectoryStringType.utf8String; } } ASN1Encodable dnValue = dsEnum.createDirectoryString(text.trim()); return new RDN(type, dnValue); }
From source file:org.xipki.ca.server.impl.store.CertStoreQueryExecutor.java
License:Open Source License
String getLatestSN(final X500Name nameWithSN) throws OperationException { RDN[] rdns1 = nameWithSN.getRDNs();// w ww . j a va 2s .co m RDN[] rdns2 = new RDN[rdns1.length]; for (int i = 0; i < rdns1.length; i++) { RDN rdn = rdns1[i]; if (rdn.getFirst().getType().equals(ObjectIdentifiers.DN_SERIALNUMBER)) { rdns2[i] = new RDN(ObjectIdentifiers.DN_SERIALNUMBER, new DERPrintableString("%")); } else { rdns2[i] = rdn; } } String namePattern = X509Util.getRFC4519Name(new X500Name(rdns2)); final String sql = dataSource.createFetchFirstSelectSQL("SUBJECT FROM CERT WHERE SUBJECT LIKE ?", 1, "NOTBEFORE DESC"); ResultSet rs = null; PreparedStatement ps; try { ps = borrowPreparedStatement(sql); } catch (DataAccessException e) { throw new OperationException(ErrorCode.DATABASE_FAILURE, e.getMessage()); } try { ps.setString(1, namePattern); rs = ps.executeQuery(); if (rs.next()) { String str = rs.getString("SUBJECT"); X500Name lastName = new X500Name(str); RDN[] rdns = lastName.getRDNs(ObjectIdentifiers.DN_SERIALNUMBER); if (rdns == null || rdns.length == 0) { return null; } else { return X509Util.rdnValueToString(rdns[0].getFirst().getValue()); } } } catch (SQLException e) { throw new OperationException(ErrorCode.DATABASE_FAILURE, e.getMessage()); } finally { releaseDbResources(ps, rs); } return null; }
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 w w.ja va2s. co 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.ca.server.impl.X509CA.java
License:Open Source License
private static Object[] incSerialNumber(final IdentifiedX509Certprofile profile, final X500Name origName, final String latestSN) throws BadFormatException { RDN[] rdns = origName.getRDNs();/*from ww w. j a v a2 s .c o m*/ int commonNameIndex = -1; int serialNumberIndex = -1; for (int i = 0; i < rdns.length; i++) { RDN rdn = rdns[i]; ASN1ObjectIdentifier type = rdn.getFirst().getType(); if (ObjectIdentifiers.DN_CN.equals(type)) { commonNameIndex = i; } else if (ObjectIdentifiers.DN_SERIALNUMBER.equals(type)) { serialNumberIndex = i; } } String newSerialNumber = profile.incSerialNumber(latestSN); RDN serialNumberRdn = new RDN(ObjectIdentifiers.DN_SERIALNUMBER, new DERPrintableString(newSerialNumber)); X500Name newName; if (serialNumberIndex != -1) { rdns[serialNumberIndex] = serialNumberRdn; newName = new X500Name(rdns); } else { List<RDN> newRdns = new ArrayList<>(rdns.length + 1); if (commonNameIndex == -1) { newRdns.add(serialNumberRdn); } for (int i = 0; i < rdns.length; i++) { newRdns.add(rdns[i]); if (i == commonNameIndex) { newRdns.add(serialNumberRdn); } } newName = new X500Name(newRdns.toArray(new RDN[0])); } return new Object[] { newName, newSerialNumber }; }
From source file:org.xipki.commons.security.shell.p12.P12ComplexCertRequestGenCmd.java
License:Open Source License
@Override protected X500Name getSubject(final String subject) { X500Name name = new X500Name(subject); List<RDN> list = new LinkedList<>(); RDN[] rs = name.getRDNs();/*from ww w . java2 s .co m*/ for (RDN m : rs) { list.add(m); } ASN1ObjectIdentifier id; // dateOfBirth if (complexSubject.booleanValue()) { id = ObjectIdentifiers.DN_DATE_OF_BIRTH; RDN[] rdns = name.getRDNs(id); if (rdns == null || rdns.length == 0) { ASN1Encodable atvValue = new DERGeneralizedTime("19950102120000Z"); RDN rdn = new RDN(id, atvValue); list.add(rdn); } } // postalAddress if (complexSubject.booleanValue()) { id = ObjectIdentifiers.DN_POSTAL_ADDRESS; RDN[] rdns = name.getRDNs(id); if (rdns == null || rdns.length == 0) { ASN1EncodableVector vec = new ASN1EncodableVector(); vec.add(new DERUTF8String("my street 1")); vec.add(new DERUTF8String("12345 Germany")); ASN1Sequence atvValue = new DERSequence(vec); RDN rdn = new RDN(id, atvValue); list.add(rdn); } } // DN_UNIQUE_IDENTIFIER id = ObjectIdentifiers.DN_UNIQUE_IDENTIFIER; RDN[] rdns = name.getRDNs(id); if (rdns == null || rdns.length == 0) { DERUTF8String atvValue = new DERUTF8String("abc-def-ghi"); RDN rdn = new RDN(id, atvValue); list.add(rdn); } return new X500Name(list.toArray(new RDN[0])); }
From source file:org.xipki.pki.ca.api.profile.x509.BaseX509Certprofile.java
License:Open Source License
protected RDN createSubjectRdn(final String text, final ASN1ObjectIdentifier type, final RdnControl option, final int index) throws BadCertTemplateException { ASN1Encodable rdnValue = createRdnValue(text, type, option, index); return (rdnValue == null) ? null : new RDN(type, rdnValue); }
From source file:org.xipki.pki.ca.api.profile.x509.BaseX509Certprofile.java
License:Open Source License
private static RDN createDateOfBirthRdn(final ASN1ObjectIdentifier type, final ASN1Encodable rdnValue) throws BadCertTemplateException { ParamUtil.requireNonNull("type", type); String text;//from w w w. ja v a2 s .co m ASN1Encodable newRdnValue = null; if (rdnValue instanceof ASN1GeneralizedTime) { text = ((ASN1GeneralizedTime) rdnValue).getTimeString(); newRdnValue = rdnValue; } else if (rdnValue instanceof ASN1String && !(rdnValue instanceof DERUniversalString)) { text = ((ASN1String) rdnValue).getString(); } else { throw new BadCertTemplateException("Value of RDN dateOfBirth has incorrect syntax"); } if (!SubjectDnSpec.PATTERN_DATE_OF_BIRTH.matcher(text).matches()) { throw new BadCertTemplateException("Value of RDN dateOfBirth does not have format YYYMMDD000000Z"); } if (newRdnValue == null) { newRdnValue = new DERGeneralizedTime(text); } return new RDN(type, newRdnValue); }
From source file:org.xipki.pki.ca.api.profile.x509.BaseX509Certprofile.java
License:Open Source License
private static RDN createPostalAddressRdn(final ASN1ObjectIdentifier type, final ASN1Encodable rdnValue, final RdnControl control, final int index) throws BadCertTemplateException { ParamUtil.requireNonNull("type", type); if (!(rdnValue instanceof ASN1Sequence)) { throw new BadCertTemplateException("rdnValue of RDN postalAddress has incorrect syntax"); }//w w w.jav a2s .com ASN1Sequence seq = (ASN1Sequence) rdnValue; final int size = seq.size(); if (size < 1 || size > 6) { throw new BadCertTemplateException("Sequence size of RDN postalAddress is not within [1, 6]: " + size); } ASN1EncodableVector vec = new ASN1EncodableVector(); for (int i = 0; i < size; i++) { ASN1Encodable line = seq.getObjectAt(i); String text; if (line instanceof ASN1String && !(line instanceof DERUniversalString)) { text = ((ASN1String) line).getString(); } else { throw new BadCertTemplateException(String.format("postalAddress[%d] has incorrect syntax", i)); } ASN1Encodable asn1Line = createRdnValue(text, type, control, index); vec.add(asn1Line); } return new RDN(type, new DERSequence(vec)); }
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 ww w . j a va 2s . com 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.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"); }//from w w w .j a v a 2 s .c o m 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; }