List of usage examples for java.security KeyStore getEntry
public final Entry getEntry(String alias, ProtectionParameter protParam) throws NoSuchAlgorithmException, UnrecoverableEntryException, KeyStoreException
From source file:org.apache.juddi.v3.client.cryptor.DigSigUtil.java
/** * Digital signs a UDDI entity, such as a business, service, tmodel or * binding template using the map to provide certificate key stores and * credentials<br><br> The UDDI entity MUST support XML Digital * Signatures (tModel, Business, Service, Binding Template) * * @param <T> Any UDDI entity that supports digital signatures * @param jaxbObj/*from www .j a va 2 s . co m*/ * @return an enveloped signed UDDI element, do not modify this object * after signing */ public <T> T signUddiEntity(T jaxbObj) { DOMResult domResult = new DOMResult(); JAXB.marshal(jaxbObj, domResult); Document doc = ((Document) domResult.getNode()); Element docElement = doc.getDocumentElement(); try { KeyStore ks = KeyStore.getInstance(map.getProperty(SIGNATURE_KEYSTORE_FILETYPE)); URL url = Thread.currentThread().getContextClassLoader() .getResource(map.getProperty(SIGNATURE_KEYSTORE_FILE)); if (url == null) { try { url = new File(map.getProperty(SIGNATURE_KEYSTORE_FILE)).toURI().toURL(); } catch (Exception x) { } } if (url == null) { try { url = this.getClass().getClassLoader().getResource(map.getProperty(SIGNATURE_KEYSTORE_FILE)); } catch (Exception x) { } } KeyStore.PrivateKeyEntry keyEntry = null; if (!map.getProperty(SIGNATURE_KEYSTORE_FILETYPE).equalsIgnoreCase("WINDOWS-MY")) { ks.load(url.openStream(), (map.getProperty(SIGNATURE_KEYSTORE_FILE_PASSWORD)).toCharArray()); if (map.getProperty(SIGNATURE_KEYSTORE_KEY_PASSWORD) == null) { keyEntry = (KeyStore.PrivateKeyEntry) ks.getEntry(map.getProperty(SIGNATURE_KEYSTORE_KEY_ALIAS), new KeyStore.PasswordProtection( map.getProperty(SIGNATURE_KEYSTORE_FILE_PASSWORD).toCharArray())); } else { keyEntry = (KeyStore.PrivateKeyEntry) ks.getEntry(map.getProperty(SIGNATURE_KEYSTORE_KEY_ALIAS), new KeyStore.PasswordProtection( map.getProperty(SIGNATURE_KEYSTORE_KEY_PASSWORD).toCharArray())); } } else { //Windows only ks.load(null, null); keyEntry = (KeyStore.PrivateKeyEntry) ks.getEntry(map.getProperty(SIGNATURE_KEYSTORE_KEY_ALIAS), null); } PrivateKey privateKey = keyEntry.getPrivateKey(); Certificate origCert = keyEntry.getCertificate(); //PublicKey validatingKey = origCert.getPublicKey(); this.signDOM(docElement, privateKey, origCert); DOMSource domSource = new DOMSource(doc); T result = (T) JAXB.unmarshal(domSource, jaxbObj.getClass()); return result; } catch (Exception e) { throw new RuntimeException("Signature failure due to: " + e.getMessage(), e); } }
From source file:be.fedict.eid.idp.model.bean.IdentityServiceSingletonBean.java
/** * Load identity keystore/*from w w w.ja v a 2 s . co m*/ * * @param idPIdentityConfig * identity configuration * @return private key entry of identity * @throws KeyStoreLoadException * failed to load keystore */ public IdPIdentity loadIdentity(IdPIdentityConfig idPIdentityConfig) throws KeyStoreLoadException { try { if (null == idPIdentityConfig) { throw new KeyStoreLoadException("Identity config is empty!"); } FileInputStream keyStoreInputStream = null; if (idPIdentityConfig.getKeyStoreType().equals(KeyStoreType.PKCS11)) { Security.addProvider(new SunPKCS11(idPIdentityConfig.getKeyStorePath())); } else { try { keyStoreInputStream = new FileInputStream(idPIdentityConfig.getKeyStorePath()); } catch (FileNotFoundException e) { throw new KeyStoreLoadException("Can't load keystore from config-specified location: " + idPIdentityConfig.getKeyStorePath(), e); } } // load keystore KeyStore keyStore = KeyStore.getInstance(idPIdentityConfig.getKeyStoreType().getJavaKeyStoreType()); char[] password; if (null != idPIdentityConfig.getKeyStorePassword() && !idPIdentityConfig.getKeyStorePassword().isEmpty()) { password = idPIdentityConfig.getKeyStorePassword().toCharArray(); } else { password = null; } keyStore.load(keyStoreInputStream, password); // find entry alias Enumeration<String> aliases = keyStore.aliases(); if (!aliases.hasMoreElements()) { throw new KeyStoreLoadException("no keystore aliases present"); } String alias; if (null != idPIdentityConfig.getKeyEntryAlias() && !idPIdentityConfig.getKeyEntryAlias().trim().isEmpty()) { boolean found = false; while (aliases.hasMoreElements()) { if (aliases.nextElement().equals(idPIdentityConfig.getKeyEntryAlias())) { found = true; break; } } if (!found) { throw new KeyStoreLoadException( "no keystore entry with alias \"" + idPIdentityConfig.getKeyEntryAlias() + "\""); } alias = idPIdentityConfig.getKeyEntryAlias(); } else { alias = aliases.nextElement(); } LOG.debug("keystore alias: " + alias); // get keystore entry char[] entryPassword; if (null != idPIdentityConfig.getKeyEntryPassword() && !idPIdentityConfig.getKeyEntryPassword().isEmpty()) { entryPassword = idPIdentityConfig.getKeyEntryPassword().toCharArray(); } else { entryPassword = null; } KeyStore.Entry entry = keyStore.getEntry(alias, new KeyStore.PasswordProtection(entryPassword)); if (!(entry instanceof PrivateKeyEntry)) { throw new KeyStoreLoadException("private key entry expected"); } return new IdPIdentity(idPIdentityConfig.getName(), (PrivateKeyEntry) entry); } catch (KeyStoreException e) { throw new KeyStoreLoadException(e); } catch (CertificateException e) { throw new KeyStoreLoadException(e); } catch (NoSuchAlgorithmException e) { throw new KeyStoreLoadException(e); } catch (UnrecoverableEntryException e) { throw new KeyStoreLoadException(e); } catch (IOException e) { throw new KeyStoreLoadException(e); } }
From source file:be.fedict.eid.dss.model.bean.IdentityServiceSingletonBean.java
/** * Load identity keystore/*from w w w . jav a 2 s .c o m*/ * * @param dssIdentityConfig * identity configuration * @return private key entry of identity * @throws KeyStoreLoadException * failed to load keystore */ public PrivateKeyEntry loadIdentity(DSSIdentityConfig dssIdentityConfig) throws KeyStoreLoadException { try { if (null == dssIdentityConfig) { throw new KeyStoreLoadException("Identity config is empty!"); } FileInputStream keyStoreInputStream = null; if (dssIdentityConfig.getKeyStoreType().equals(KeyStoreType.PKCS11)) { Security.addProvider(new SunPKCS11(dssIdentityConfig.getKeyStorePath())); } else { try { keyStoreInputStream = new FileInputStream(dssIdentityConfig.getKeyStorePath()); } catch (FileNotFoundException e) { throw new KeyStoreLoadException("Can't load keystore from config-specified location: " + dssIdentityConfig.getKeyStorePath(), e); } } // load keystore KeyStore keyStore = KeyStore.getInstance(dssIdentityConfig.getKeyStoreType().getJavaKeyStoreType()); char[] password; if (null != dssIdentityConfig.getKeyStorePassword() && !dssIdentityConfig.getKeyStorePassword().isEmpty()) { password = dssIdentityConfig.getKeyStorePassword().toCharArray(); } else { password = null; } keyStore.load(keyStoreInputStream, password); // find entry alias Enumeration<String> aliases = keyStore.aliases(); if (!aliases.hasMoreElements()) { throw new KeyStoreLoadException("no keystore aliases present"); } String alias; if (null != dssIdentityConfig.getKeyEntryAlias() && !dssIdentityConfig.getKeyEntryAlias().trim().isEmpty()) { boolean found = false; while (aliases.hasMoreElements()) { if (aliases.nextElement().equals(dssIdentityConfig.getKeyEntryAlias())) { found = true; break; } } if (!found) { throw new KeyStoreLoadException( "no keystore entry with alias \"" + dssIdentityConfig.getKeyEntryAlias() + "\""); } alias = dssIdentityConfig.getKeyEntryAlias(); } else { alias = aliases.nextElement(); } LOG.debug("keystore alias: " + alias); // get keystore entry char[] entryPassword; if (null != dssIdentityConfig.getKeyEntryPassword() && !dssIdentityConfig.getKeyEntryPassword().isEmpty()) { entryPassword = dssIdentityConfig.getKeyEntryPassword().toCharArray(); } else { entryPassword = null; } KeyStore.Entry entry = keyStore.getEntry(alias, new KeyStore.PasswordProtection(entryPassword)); if (!(entry instanceof PrivateKeyEntry)) { throw new KeyStoreLoadException("private key entry expected"); } return (PrivateKeyEntry) entry; } catch (KeyStoreException e) { throw new KeyStoreLoadException(e); } catch (CertificateException e) { throw new KeyStoreLoadException(e); } catch (NoSuchAlgorithmException e) { throw new KeyStoreLoadException(e); } catch (UnrecoverableEntryException e) { throw new KeyStoreLoadException(e); } catch (IOException e) { throw new KeyStoreLoadException(e); } }
From source file:org.apache.juddi.v3.client.cryptor.DigSigUtil.java
/** * Verifies the signature on an enveloped digital signature on a UDDI * entity, such as a business, service, tmodel or binding template. * <br><Br>/*w w w .j a va2 s . c om*/ * It is expected that either the public key of the signing certificate * is included within the signature keyinfo section OR that sufficient * information is provided in the signature to reference a public key * located within the Trust Store provided<br><Br> Optionally, this * function also validate the signing certificate using the options * provided to the configuration map. * * @param obj an enveloped signed JAXB object * @param OutErrorMessage a human readable error message explaining the * reason for failure * @return true if the validation passes the signature validation test, * and optionally any certificate validation or trust chain validation * @throws IllegalArgumentException for null input */ public boolean verifySignedUddiEntity(Object obj, AtomicReference<String> OutErrorMessage) throws IllegalArgumentException { if (OutErrorMessage == null) { OutErrorMessage = new AtomicReference<String>(); OutErrorMessage.set(""); } if (obj == null) { throw new IllegalArgumentException("obj"); } try { DOMResult domResult = new DOMResult(); JAXB.marshal(obj, domResult); Document doc = ((Document) domResult.getNode()); Element docElement = doc.getDocumentElement(); //this is our signed node X509Certificate signingcert = getSigningCertificatePublicKey(docElement); if (signingcert != null) { logger.info( "verifying signature based on X509 public key " + signingcert.getSubjectDN().toString()); if (map.containsKey(CHECK_TIMESTAMPS) && Boolean.parseBoolean(map.getProperty(CHECK_TIMESTAMPS))) { signingcert.checkValidity(); } if (map.containsKey(CHECK_REVOCATION_STATUS_OCSP) && Boolean.parseBoolean(map.getProperty(CHECK_REVOCATION_STATUS_OCSP))) { logger.info("verifying revocation status via OSCP for X509 public key " + signingcert.getSubjectDN().toString()); X500Principal issuerX500Principal = signingcert.getIssuerX500Principal(); logger.info("certificate " + signingcert.getSubjectDN().toString() + " was issued by " + issuerX500Principal.getName() + ", attempting to retrieve certificate"); Security.setProperty("ocsp.enable", "false"); X509Certificate issuer = FindCertByDN(issuerX500Principal); if (issuer == null) { OutErrorMessage.set( "Unable to verify certificate status from OCSP because the issuer of the certificate is not in the trust store. " + OutErrorMessage.get()); //throw new CertificateException("unable to locate the issuers certificate in the trust store"); } else { RevocationStatus check = OCSP.check(signingcert, issuer); logger.info("certificate " + signingcert.getSubjectDN().toString() + " revocation status is " + check.getCertStatus().toString() + " reason " + check.getRevocationReason().toString()); if (check.getCertStatus() != RevocationStatus.CertStatus.GOOD) { OutErrorMessage .set("Certificate status is " + check.getCertStatus().toString() + " reason " + check.getRevocationReason().toString() + "." + OutErrorMessage.get()); //throw new CertificateException("Certificate status is " + check.getCertStatus().toString() + " reason " + check.getRevocationReason().toString()); } } } if (map.containsKey(CHECK_REVOCATION_STATUS_CRL) && Boolean.parseBoolean(map.getProperty(CHECK_REVOCATION_STATUS_CRL))) { logger.info("verifying revokation status via CRL for X509 public key " + signingcert.getSubjectDN().toString()); Security.setProperty("ocsp.enable", "false"); System.setProperty("com.sun.security.enableCRLDP", "true"); X509CertSelector targetConstraints = new X509CertSelector(); targetConstraints.setCertificate(signingcert); PKIXParameters params = new PKIXParameters(GetTrustStore()); params.setRevocationEnabled(true); CertPath certPath = cf.generateCertPath(Arrays.asList(signingcert)); CertPathValidator certPathValidator = CertPathValidator .getInstance(CertPathValidator.getDefaultType()); CertPathValidatorResult result = certPathValidator.validate(certPath, params); try { PKIXCertPathValidatorResult pkixResult = (PKIXCertPathValidatorResult) result; logger.info("revokation status via CRL PASSED for X509 public key " + signingcert.getSubjectDN().toString()); } catch (Exception ex) { OutErrorMessage.set("Certificate status is via CRL Failed: " + ex.getMessage() + "." + OutErrorMessage.get()); } } if (map.containsKey(CHECK_TRUST_CHAIN) && Boolean.parseBoolean(map.getProperty(CHECK_TRUST_CHAIN))) { logger.info("verifying trust chain X509 public key " + signingcert.getSubjectDN().toString()); try { PKIXParameters params = new PKIXParameters(GetTrustStore()); params.setRevocationEnabled(false); CertPath certPath = cf.generateCertPath(Arrays.asList(signingcert)); CertPathValidator certPathValidator = CertPathValidator .getInstance(CertPathValidator.getDefaultType()); CertPathValidatorResult result = certPathValidator.validate(certPath, params); PKIXCertPathValidatorResult pkixResult = (PKIXCertPathValidatorResult) result; TrustAnchor ta = pkixResult.getTrustAnchor(); X509Certificate cert = ta.getTrustedCert(); logger.info( "trust chain validated X509 public key " + signingcert.getSubjectDN().toString()); } catch (Exception ex) { OutErrorMessage.set("Certificate status Trust validation failed: " + ex.getMessage() + "." + OutErrorMessage.get()); } } boolean b = verifySignature(docElement, signingcert.getPublicKey(), OutErrorMessage); if ((OutErrorMessage.get() == null || OutErrorMessage.get().length() == 0) && b) { //no error message and its cryptographically valid return true; } return false; } //last chance validation logger.info( "signature did not have an embedded X509 public key. reverting to user specified certificate"); //cert wasn't included in the signature, revert to some other means KeyStore ks = KeyStore.getInstance(map.getProperty(SIGNATURE_KEYSTORE_FILETYPE)); URL url = Thread.currentThread().getContextClassLoader() .getResource(map.getProperty(SIGNATURE_KEYSTORE_FILE)); if (url == null) { try { url = new File(map.getProperty(SIGNATURE_KEYSTORE_FILE)).toURI().toURL(); } catch (Exception x) { } } if (url == null) { try { url = this.getClass().getClassLoader().getResource(map.getProperty(SIGNATURE_KEYSTORE_FILE)); } catch (Exception x) { } } if (url == null) { logger.error(""); OutErrorMessage.set("The signed entity is signed but does not have a certificate attached and" + "you didn't specify a keystore for me to look it up in. " + OutErrorMessage.get()); return false; } KeyStore.PrivateKeyEntry keyEntry = null; ks.load(url.openStream(), map.getProperty(SIGNATURE_KEYSTORE_FILE_PASSWORD).toCharArray()); if (map.getProperty(SIGNATURE_KEYSTORE_KEY_PASSWORD) == null) { keyEntry = (KeyStore.PrivateKeyEntry) ks.getEntry(map.getProperty(SIGNATURE_KEYSTORE_KEY_ALIAS), new KeyStore.PasswordProtection( map.getProperty(SIGNATURE_KEYSTORE_FILE_PASSWORD).toCharArray())); } else { keyEntry = (KeyStore.PrivateKeyEntry) ks.getEntry(map.getProperty(SIGNATURE_KEYSTORE_KEY_ALIAS), new KeyStore.PasswordProtection( map.getProperty(SIGNATURE_KEYSTORE_KEY_PASSWORD).toCharArray())); } Certificate origCert = keyEntry.getCertificate(); if (map.containsKey(CHECK_TIMESTAMPS)) { if (origCert.getPublicKey() instanceof X509Certificate) { X509Certificate x = (X509Certificate) origCert.getPublicKey(); x.checkValidity(); } } PublicKey validatingKey = origCert.getPublicKey(); return verifySignature(docElement, validatingKey, OutErrorMessage); } catch (Exception e) { //throw new RuntimeException(e); logger.error("Error caught validating signature", e); OutErrorMessage.set(e.getMessage()); return false; } }
From source file:org.cesecore.certificates.ocsp.OcspResponseGeneratorSessionBean.java
/** Creates a PKCS#12 KeyStore with keys only from an JKS file (no issuer certs or trusted certs) */ @Deprecated //Remove this method as soon as upgrading from 5->6 is dropped private KeyStore makeKeysOnlyP12(KeyStore keyStore, char[] password) throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableEntryException, NoSuchProviderException, CertificateException, IOException { final KeyStore p12 = KeyStore.getInstance("PKCS12", "BC"); final KeyStore.ProtectionParameter protParam = (password != null ? new KeyStore.PasswordProtection(password) : null);/*from w w w.jav a2 s . com*/ p12.load(null, password); // initialize final Enumeration<String> en = keyStore.aliases(); while (en.hasMoreElements()) { final String alias = en.nextElement(); if (!keyStore.isKeyEntry(alias)) continue; try { KeyStore.PrivateKeyEntry entry = (KeyStore.PrivateKeyEntry) keyStore.getEntry(alias, protParam); Certificate[] chain = new Certificate[] { entry.getCertificate() }; p12.setKeyEntry(alias, entry.getPrivateKey(), password, chain); } catch (UnsupportedOperationException uoe) { KeyStore.PrivateKeyEntry entry = (KeyStore.PrivateKeyEntry) keyStore.getEntry(alias, null); Certificate[] chain = new Certificate[] { entry.getCertificate() }; p12.setKeyEntry(alias, entry.getPrivateKey(), null, chain); } } return p12; }
From source file:org.signserver.server.cryptotokens.CryptoTokenHelper.java
public static TokenSearchResults searchTokenEntries(final KeyStore keyStore, final int startIndex, final int max, final QueryCriteria qc, final boolean includeData) throws CryptoTokenOfflineException, QueryException { final TokenSearchResults result; try {//from w ww.j a v a2s. c o m final ArrayList<TokenEntry> tokenEntries = new ArrayList<TokenEntry>(); final Enumeration<String> e = keyStore.aliases(); // We assume the order is the same for every call unless entries has been added or removed final long maxIndex = (long) startIndex + max; for (int i = 0; i < maxIndex && e.hasMoreElements();) { final String keyAlias = e.nextElement(); final String type; if (keyStore.entryInstanceOf(keyAlias, KeyStore.PrivateKeyEntry.class)) { type = TokenEntry.TYPE_PRIVATEKEY_ENTRY; } else if (keyStore.entryInstanceOf(keyAlias, KeyStore.SecretKeyEntry.class)) { type = TokenEntry.TYPE_SECRETKEY_ENTRY; } else if (keyStore.entryInstanceOf(keyAlias, KeyStore.TrustedCertificateEntry.class)) { type = TokenEntry.TYPE_TRUSTED_ENTRY; } else { type = null; } TokenEntry entry = new TokenEntry(keyAlias, type); if (shouldBeIncluded(entry, qc)) { if (i < startIndex) { i++; continue; } if (LOG.isDebugEnabled()) { LOG.debug("checking keyAlias: " + keyAlias); } // Add additional data if (includeData) { Map<String, String> info = new HashMap<String, String>(); try { Date creationDate = keyStore.getCreationDate(keyAlias); entry.setCreationDate(creationDate); } catch (ProviderException ex) { } // NOPMD: We ignore if it is not supported if (TokenEntry.TYPE_PRIVATEKEY_ENTRY.equals(type)) { final Certificate[] chain = keyStore.getCertificateChain(keyAlias); if (chain.length > 0) { info.put(INFO_KEY_ALGORITHM, AlgorithmTools.getKeyAlgorithm(chain[0].getPublicKey())); info.put(INFO_KEY_SPECIFICATION, AlgorithmTools.getKeySpecification(chain[0].getPublicKey())); } try { entry.setParsedChain(chain); } catch (CertificateEncodingException ex) { info.put("Error", ex.getMessage()); LOG.error("Certificate could not be encoded for alias: " + keyAlias, ex); } } else if (TokenEntry.TYPE_TRUSTED_ENTRY.equals(type)) { Certificate certificate = keyStore.getCertificate(keyAlias); try { entry.setParsedTrustedCertificate(certificate); } catch (CertificateEncodingException ex) { info.put("Error", ex.getMessage()); LOG.error("Certificate could not be encoded for alias: " + keyAlias, ex); } } else if (TokenEntry.TYPE_SECRETKEY_ENTRY.equals(type)) { try { KeyStore.Entry entry1 = keyStore.getEntry(keyAlias, null); SecretKey secretKey = ((KeyStore.SecretKeyEntry) entry1).getSecretKey(); info.put(INFO_KEY_ALGORITHM, secretKey.getAlgorithm()); //info.put(INFO_KEY_SPECIFICATION, AlgorithmTools.getKeySpecification(chain[0].getPublicKey())); // TODO: Key specification support for secret keys } catch (NoSuchAlgorithmException ex) { info.put("Error", ex.getMessage()); LOG.error("Unable to get secret key for alias: " + keyAlias, ex); } catch (UnrecoverableEntryException ex) { info.put("Error", ex.getMessage()); LOG.error("Unable to get secret key for alias: " + keyAlias, ex); } } entry.setInfo(info); } tokenEntries.add(entry); // Increase index i++; } } result = new TokenSearchResults(tokenEntries, e.hasMoreElements()); } catch (KeyStoreException ex) { throw new CryptoTokenOfflineException(ex); } return result; }
From source file:net.maritimecloud.identityregistry.utils.CertificateUtil.java
/** * Generates a self-signed certificate based on the keypair and saves it in the keystore. * Should only be used to init the CA.// w w w. j a v a2 s .co m */ public void initCA(String rootCertX500Name, String mcidregCertX500Name, String crlUrl, String ocspUrl, String outputCaCrlPath) { if (KEYSTORE_PASSWORD == null) { KEYSTORE_PASSWORD = "changeit"; } if (ROOT_KEYSTORE_PATH == null) { ROOT_KEYSTORE_PATH = "mc-root-keystore.jks"; } if (INTERMEDIATE_KEYSTORE_PATH == null) { INTERMEDIATE_KEYSTORE_PATH = "mc-it-keystore.jks"; } if (TRUSTSTORE_PASSWORD == null) { TRUSTSTORE_PASSWORD = "changeit"; } if (TRUSTSTORE_PATH == null) { TRUSTSTORE_PATH = "mc-truststore.jks"; } if (CRL_URL == null) { CRL_URL = crlUrl; } if (OCSP_URL == null) { OCSP_URL = ocspUrl; } KeyPair cakp = generateKeyPair(); KeyPair imkp = generateKeyPair(); KeyStore rootks = null; KeyStore itks; KeyStore ts; FileOutputStream rootfos = null; FileOutputStream itfos = null; FileOutputStream tsfos = null; try { rootks = KeyStore.getInstance(KEYSTORE_TYPE); // KeyStore.getDefaultType() rootks.load(null, KEYSTORE_PASSWORD.toCharArray()); itks = KeyStore.getInstance(KEYSTORE_TYPE); // KeyStore.getDefaultType() itks.load(null, KEYSTORE_PASSWORD.toCharArray()); // Store away the keystore. rootfos = new FileOutputStream(ROOT_KEYSTORE_PATH); itfos = new FileOutputStream(INTERMEDIATE_KEYSTORE_PATH); X509Certificate cacert; try { cacert = buildAndSignCert(generateSerialNumber(), cakp.getPrivate(), cakp.getPublic(), cakp.getPublic(), new X500Name(rootCertX500Name), new X500Name(rootCertX500Name), null, "ROOTCA"); } catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } X509Certificate imcert; try { imcert = buildAndSignCert(generateSerialNumber(), cakp.getPrivate(), cakp.getPublic(), imkp.getPublic(), new X500Name(rootCertX500Name), new X500Name(mcidregCertX500Name), null, "INTERMEDIATE"); } catch (Exception e) { throw new RuntimeException(e.getMessage(), e); } Certificate[] certChain = new Certificate[1]; certChain[0] = cacert; rootks.setKeyEntry(ROOT_CERT_ALIAS, cakp.getPrivate(), KEYSTORE_PASSWORD.toCharArray(), certChain); rootks.store(rootfos, KEYSTORE_PASSWORD.toCharArray()); rootks = KeyStore.getInstance(KeyStore.getDefaultType()); rootks.load(null, KEYSTORE_PASSWORD.toCharArray()); certChain = new Certificate[2]; certChain[0] = imcert; certChain[1] = cacert; itks.setKeyEntry(INTERMEDIATE_CERT_ALIAS, imkp.getPrivate(), KEYSTORE_PASSWORD.toCharArray(), certChain); itks.store(itfos, KEYSTORE_PASSWORD.toCharArray()); // Store away the truststore. ts = KeyStore.getInstance(KeyStore.getDefaultType()); ts.load(null, TRUSTSTORE_PASSWORD.toCharArray()); tsfos = new FileOutputStream(TRUSTSTORE_PATH); ts.setCertificateEntry(ROOT_CERT_ALIAS, cacert); ts.setCertificateEntry(INTERMEDIATE_CERT_ALIAS, imcert); ts.store(tsfos, TRUSTSTORE_PASSWORD.toCharArray()); } catch (KeyStoreException | NoSuchAlgorithmException | CertificateException | IOException e) { throw new RuntimeException(e.getMessage(), e); } finally { safeClose(rootfos); safeClose(itfos); safeClose(tsfos); KeyStore.ProtectionParameter protParam = new KeyStore.PasswordProtection( KEYSTORE_PASSWORD.toCharArray()); PrivateKeyEntry rootCertEntry; try { rootCertEntry = (PrivateKeyEntry) rootks.getEntry(ROOT_CERT_ALIAS, protParam); generateRootCACRL(rootCertX500Name, null, rootCertEntry, outputCaCrlPath); } catch (NoSuchAlgorithmException | UnrecoverableEntryException | KeyStoreException e) { // todo, I think is an irrecoverable state, but we should not throw exception from finally, perhaps this code should not be in a finally block log.error("unable to generate RootCACRL", e); } } }