List of usage examples for java.security KeyStore setKeyEntry
public final void setKeyEntry(String alias, Key key, char[] password, Certificate[] chain) throws KeyStoreException
From source file:org.ejbca.core.model.ca.catoken.CATokenContainerImpl.java
/** * /*from w ww. ja va2 s .c o m*/ * @throws CATokenAuthenticationFailedException * @see org.ejbca.core.model.ca.catoken.CATokenContainer#activateNextSignKey(java.lang.String) */ public void activateNextSignKey(String authenticationCode) throws CATokenOfflineException, KeyStoreException, NoSuchProviderException, NoSuchAlgorithmException, CertificateException, IOException, InvalidKeyException, SignatureException, CATokenAuthenticationFailedException { if (log.isTraceEnabled()) { log.trace(">activateNextSignKey: " + (authenticationCode == null ? "null" : "hidden")); } // First make a check that we have a next sign key CATokenInfo catokeninfo = getCATokenInfo(); String oldSequence = getKeySequence(); log.debug("Current old sequence: " + oldSequence); // If we don't give an authentication code, perhaps we have autoactivation enabled char[] authCode = getAuthCodeOrAutoactivationPin(authenticationCode); Properties properties = getProperties(); String tokentype = null; // Then we can move on to actually move the keys if (catokeninfo instanceof SoftCATokenInfo) { // If we have an existing soft keystore verify that the password is correct checkSoftKeystorePassword(authenticationCode); SoftCATokenInfo info = (SoftCATokenInfo) catokeninfo; ICAToken token = getCAToken(); PublicKey pubEnc = token.getPublicKey(SecConst.CAKEYPURPOSE_KEYENCRYPT); PrivateKey privEnc = token.getPrivateKey(SecConst.CAKEYPURPOSE_KEYENCRYPT); PublicKey pubSign = token.getPublicKey(SecConst.CAKEYPURPOSE_CERTSIGN); PrivateKey privSign = token.getPrivateKey(SecConst.CAKEYPURPOSE_CERTSIGN); PublicKey nextPubSign = token.getPublicKey(SecConst.CAKEYPURPOSE_CERTSIGN_NEXT); PrivateKey nextPrivSign = token.getPrivateKey(SecConst.CAKEYPURPOSE_CERTSIGN_NEXT); // Create the new keystore and add the new signature keys KeyStore keystore = KeyStore.getInstance("PKCS12", "BC"); keystore.load(null, null); // Insert the old "next" keys into the now active keys log.debug("Setting nextPrivSign as " + SoftCAToken.PRIVATESIGNKEYALIAS + " in soft CA token."); Certificate[] certchain = new Certificate[1]; // generate dummy certificate String sigAlg = (String) AlgorithmTools.getSignatureAlgorithms(nextPubSign).iterator().next(); certchain[0] = CertTools.genSelfCert("CN=dummy", 36500, null, nextPrivSign, nextPubSign, sigAlg, true); keystore.setKeyEntry(SoftCAToken.PRIVATESIGNKEYALIAS, nextPrivSign, null, certchain); // Insert the old active keys into the now "old" keys log.debug("Setting privSign as " + SoftCAToken.PREVIOUSPRIVATESIGNKEYALIAS + " in soft CA token."); sigAlg = (String) AlgorithmTools.getSignatureAlgorithms(pubSign).iterator().next(); certchain[0] = CertTools.genSelfCert("CN=dummy2", 36500, null, privSign, pubSign, sigAlg, true); keystore.setKeyEntry(SoftCAToken.PREVIOUSPRIVATESIGNKEYALIAS, privSign, null, certchain); properties.setProperty(KeyStrings.CAKEYPURPOSE_CERTSIGN_STRING_PREVIOUS, SoftCAToken.PREVIOUSPRIVATESIGNKEYALIAS); // Finally install the old encryption/decryption keys as well sigAlg = (String) AlgorithmTools.getSignatureAlgorithms(pubEnc).iterator().next(); certchain[0] = CertTools.genSelfCert("CN=dummy2", 36500, null, privEnc, pubEnc, sigAlg, true); keystore.setKeyEntry(SoftCAToken.PRIVATEDECKEYALIAS, privEnc, null, certchain); activateKeyFixProperties(oldSequence, properties); // Serialize and store the soft keystore storeSoftKeyStore(authCode, info, properties, keystore); tokentype = "Soft"; // for logging } else if (catokeninfo instanceof HardCATokenInfo) { ICAToken token = getCAToken(); if (token instanceof PKCS11CAToken) { String nextKeyLabel = token.getKeyLabel(SecConst.CAKEYPURPOSE_CERTSIGN_NEXT); String currentKeyLabel = token.getKeyLabel(SecConst.CAKEYPURPOSE_CERTSIGN); String crlKeyLabel = token.getKeyLabel(SecConst.CAKEYPURPOSE_CRLSIGN); log.debug("Old key label is: " + currentKeyLabel); KeyStrings kstr = new KeyStrings(properties); String certsignkeystr = kstr.getKey(SecConst.CAKEYPURPOSE_CERTSIGN); log.debug("CAKEYPURPOSE_CERTSIGN keystring is: " + certsignkeystr); String crlsignkeystr = kstr.getKey(SecConst.CAKEYPURPOSE_CRLSIGN); log.debug("CAKEYPURPOSE_CRLSIGN keystring is: " + crlsignkeystr); log.debug("Setting sertsignkeystr to " + nextKeyLabel); properties.setProperty(certsignkeystr, nextKeyLabel); if (!StringUtils.equals(certsignkeystr, crlsignkeystr) && StringUtils.equals(currentKeyLabel, crlKeyLabel)) { log.debug("Also setting crlsignkeystr to " + nextKeyLabel); properties.setProperty(crlsignkeystr, nextKeyLabel); } log.debug("Set previousCertSignKey: " + currentKeyLabel); properties.setProperty(KeyStrings.CAKEYPURPOSE_CERTSIGN_STRING_PREVIOUS, currentKeyLabel); activateKeyFixProperties(oldSequence, properties); // Store updated properties setProperties(properties); tokentype = "PKCS#11"; // for logging } } // Finally reset the token so it will be re-read when we want to use it this.catoken = null; String msg = intres.getLocalizedMessage("catoken.activatednextkey", tokentype); log.info(msg); if (log.isTraceEnabled()) { log.trace("<activateNextSignKey"); } }
From source file:org.alfresco.encryption.AlfrescoKeyStoreImpl.java
protected void createKeyStore(KeyStoreParameters keyStoreParameters, KeyMap keys) { KeyInfoManager keyInfoManager = null; try {//from ww w.j a v a2 s .c o m if (!keyStoreExists(keyStoreParameters.getLocation())) { keyInfoManager = getKeyInfoManager(keyStoreParameters.getKeyMetaDataFileLocation()); KeyStore ks = initialiseKeyStore(keyStoreParameters.getType(), keyStoreParameters.getProvider()); String keyStorePassword = keyInfoManager.getKeyStorePassword(); if (keyStorePassword == null) { throw new AlfrescoRuntimeException("Key store password is null for keystore at location " + getKeyStoreParameters().getLocation() + ", key store meta data location" + getKeyMetaDataFileLocation()); } for (String keyAlias : keys.getKeyAliases()) { KeyInformation keyInfo = keyInfoManager.getKeyInformation(keyAlias); Key key = keys.getKey(keyAlias); if (key == null) { logger.warn("Key with alias " + keyAlias + " is null when creating keystore at location " + keyStoreParameters.getLocation()); } else { ks.setKeyEntry(keyAlias, key, keyInfo.getPassword().toCharArray(), null); } } // try // { // throw new Exception("Keystore creation: " + ); // } // catch(Throwable e) // { // logger.debug(e.getMessage()); // e.printStackTrace(); // } ks.store(new FileOutputStream(keyStoreParameters.getLocation()), keyStorePassword.toCharArray()); } else { logger.warn("Can't create key store " + keyStoreParameters.getLocation() + ", already exists."); } } catch (Throwable e) { throw new AlfrescoRuntimeException("Failed to create keystore: \n" + " Location: " + keyStoreParameters.getLocation() + "\n" + " Provider: " + keyStoreParameters.getProvider() + "\n" + " Type: " + keyStoreParameters.getType(), e); } finally { if (keyInfoManager != null) { keyInfoManager.clear(); } } }
From source file:org.ejbca.core.model.ca.caadmin.extendedcaservices.CmsCAService.java
@Override public void init(final CryptoToken cryptoToken, final CA ca, final AvailableCustomCertificateExtensionsConfiguration cceConfig) throws Exception { if (log.isTraceEnabled()) { log.trace(">init"); }// ww w . jav a2s. c o m if (info.getStatus() != ExtendedCAServiceInfo.STATUS_ACTIVE) { if (log.isDebugEnabled()) { log.debug("Not generating certificates for inactive service"); } } else { // lookup keystore passwords final String keystorepass = StringTools.passwordDecryption(EjbcaConfiguration.getCaCmsKeyStorePass(), "ca.cmskeystorepass"); // Currently only RSA keys are supported final CmsCAServiceInfo info = (CmsCAServiceInfo) getExtendedCAServiceInfo(); // Create KeyStore final KeyStore keystore = KeyStore.getInstance("PKCS12", "BC"); keystore.load(null, null); final KeyPair cmskeys = KeyTools.genKeys(info.getKeySpec(), info.getKeyAlgorithm()); // A simple hard coded certificate profile that works for the CMS CA service final CertificateProfile certProfile = new CertificateProfile( CertificateProfileConstants.CERTPROFILE_FIXED_ENDUSER); certProfile.setUseKeyUsage(true); certProfile.setKeyUsage(new boolean[9]); certProfile.setKeyUsage(CertificateConstants.DIGITALSIGNATURE, true); certProfile.setKeyUsage(CertificateConstants.KEYENCIPHERMENT, true); certProfile.setKeyUsage(CertificateConstants.DATAENCIPHERMENT, true); certProfile.setKeyUsageCritical(true); final EndEntityInformation eeInformation = new EndEntityInformation("NOUSERNAME", info.getSubjectDN(), 0, info.getSubjectAltName(), "NOEMAIL", 0, new EndEntityType(), 0, 0, null, null, 0, 0, null); final Certificate certificate = ca.generateCertificate(cryptoToken, eeInformation, cmskeys.getPublic(), -1, null, ca.getEncodedValidity(), certProfile, null, cceConfig); certificatechain = new ArrayList<Certificate>(); certificatechain.add(certificate); certificatechain.addAll(ca.getCertificateChain()); privKey = cmskeys.getPrivate(); keystore.setKeyEntry(PRIVATESIGNKEYALIAS, cmskeys.getPrivate(), null, (Certificate[]) certificatechain.toArray(new Certificate[certificatechain.size()])); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); keystore.store(baos, keystorepass.toCharArray()); data.put(KEYSTORE, new String(Base64.encode(baos.toByteArray()))); } setStatus(info.getStatus()); this.info = new CmsCAServiceInfo(info.getStatus(), getSubjectDN(), getSubjectAltName(), (String) data.get(KEYSPEC), (String) data.get(KEYALGORITHM), certificatechain); if (log.isTraceEnabled()) { log.trace("<init"); } }
From source file:it.cnr.icar.eric.common.security.KeystoreMover.java
public void move(String sourceKeystoreType, String sourceKeystorePath, String sourceKeystorePassword, String sourceAlias, String sourceKeyPassword, String destinationKeystoreType, String destinationKeystorePath, String destinationKeystorePassword, String destinationAlias, String destinationKeyPassword) throws Exception { char[] sourceKeystorePasswordArr = null; if (sourceKeystorePassword != null) { sourceKeystorePasswordArr = sourceKeystorePassword.toCharArray(); }/*from w w w .ja v a 2s. c o m*/ char[] sourceKeyPasswordArr = sourceKeystorePasswordArr; if (sourceKeyPassword != null) { sourceKeyPasswordArr = sourceKeyPassword.toCharArray(); } char[] destinationKeystorePasswordArr = null; if (destinationKeystorePassword != null) { destinationKeystorePasswordArr = destinationKeystorePassword.toCharArray(); } char[] destinationKeyPasswordArr = destinationKeystorePasswordArr; if (destinationKeyPassword != null) { destinationKeyPasswordArr = destinationKeyPassword.toCharArray(); } FileInputStream in; // -------- Load source keystore to memory --------- in = new FileInputStream(sourceKeystorePath); KeyStore ksin = KeyStore.getInstance(sourceKeystoreType); ksin.load(in, sourceKeystorePasswordArr); in.close(); // -------- Load destination keystore initial contents to memory --------- KeyStore ksout = KeyStore.getInstance(destinationKeystoreType); try { in = new FileInputStream(destinationKeystorePath); ksout.load(in, destinationKeystorePasswordArr); } catch (java.io.FileNotFoundException e) { ksout.load(null, destinationKeystorePasswordArr); } finally { in.close(); } Enumeration<String> en = ksin.aliases(); while (en.hasMoreElements()) { String alias = en.nextElement(); if ((sourceAlias == null) || (sourceAlias.equalsIgnoreCase(alias))) { if (ksout.containsAlias(alias)) { log.info(CommonResourceBundle.getInstance().getString( "message.destinationKeystorePathAlreadyContains", new Object[] { destinationKeystorePath, alias })); continue; } //Use existing alias if no destinationAlias specified if (destinationAlias == null) { destinationAlias = alias; } if (ksin.isCertificateEntry(alias)) { log.debug(CommonResourceBundle.getInstance().getString("message.importingCertificate", new Object[] { alias })); ksout.setCertificateEntry(destinationAlias, ksin.getCertificate(alias)); } if (ksin.isKeyEntry(alias)) { log.debug(CommonResourceBundle.getInstance().getString("message.importingKey", new Object[] { alias })); Certificate[] certChain = ksin.getCertificateChain(alias); ksout.setKeyEntry(destinationAlias, ksin.getKey(alias, sourceKeyPasswordArr), destinationKeyPasswordArr, certChain); } } } //--------- Overwrite the destination keystore with new keys/certs which is a merge of source and original destination keystores-------------- FileOutputStream out = new FileOutputStream(destinationKeystorePath); ksout.store(out, destinationKeystorePasswordArr); out.close(); log.debug(CommonResourceBundle.getInstance().getString("message.keystoreCopySuccessful")); }
From source file:org.tolven.config.model.CredentialManager.java
private void createKeyStore(CertificateGroupDetail certGroup, char[] password) throws IOException, GeneralSecurityException { File file = null;//from w w w . j a v a 2 s .c o m try { CertificateKeyStoreDetail certificateKeyStore = certGroup.getKeyStore(); KeyStore keyStore = KeyStore.getInstance(certificateKeyStore.getFormat()); char[] keystorepass = password; if (keystorepass == null) { keystorepass = getPasswordHolder().getPassword(certGroup.getId()); if (keystorepass == null) { throw new RuntimeException( "Password for keystore in group " + certGroup.getId() + " cannot be null"); } } if (getPasswordHolder().getPassword(certGroup.getId()) == null) { getPasswordHolder().addPassword(certGroup.getId(), PasswordHolder.CREDENTIAL_PASSWORD, keystorepass); } keyStore.load(null, keystorepass); CertificateKeyDetail keyDetail = certGroup.getKey(); X509Certificate[] certificates = getX509CertificateChain(certGroup); char[] keypass = getPasswordHolder().getPassword(certGroup.getId()); PrivateKey privateKey = getPrivateKey(keyDetail, keypass); String alias = certificates[0].getSubjectDN().getName(); keyStore.setKeyEntry(alias, privateKey, keypass, certificates); file = new File(certificateKeyStore.getSource()); write(keyStore, file, keystorepass); } catch (IOException ex) { ex.printStackTrace(); if (file != null) file.delete(); throw ex; } catch (GeneralSecurityException ex) { ex.printStackTrace(); if (file != null) file.delete(); throw ex; } }
From source file:com.sun.identity.console.user.model.UMChangeUserPasswordModelImpl.java
public void changePwd(String userId, String oldPassword, String newPassword) throws AMConsoleException { String[] params = { userId, AMAdminConstants.ATTR_USER_OLD_PASSWORD }; try {/* w ww . j a v a 2 s .co m*/ logEvent("ATTEMPT_MODIFY_IDENTITY_ATTRIBUTE_VALUE", params); AMIdentity amIdentity = IdUtils.getIdentity(getUserSSOToken(), userId); boolean verified = verifyOldPassword(amIdentity, userId, oldPassword.toCharArray()); if (!verified) { String strError = "Authorized for password changed denied"; String[] paramsEx = { userId, AMAdminConstants.ATTR_USER_OLD_PASSWORD, strError }; logEvent("SSO_EXCEPTION_MODIFY_IDENTITY_ATTRIBUTE_VALUE", paramsEx); throw new AMConsoleException(strError); } Map passwordMap = new AMHashMap(2); Set set = new HashSet(2); set.add(newPassword); passwordMap.put(AMAdminConstants.ATTR_USER_PASSWORD, set); Set<String> attributeNames = new HashSet<String>(); attributeNames.add(USERPKCS12_BINARY_ATTRNAME); Map<String, byte[][]> userPKCS12Map = amIdentity.getBinaryAttributes(attributeNames); if (userPKCS12Map != null && userPKCS12Map.get(USERPKCS12_BINARY_ATTRNAME) != null) { KeyStore keyStore = null; try { keyStore = KeyStore.getInstance(TOLVEN_CREDENTIAL_FORMAT_PKCS12); } catch (Exception e) { String strError = "Could not get an instance of KeyStore to create user KeyStore: " + getErrorString(e); String[] paramsEx = { userId, AMAdminConstants.ATTR_USER_OLD_PASSWORD, strError }; logEvent("SSO_EXCEPTION_MODIFY_IDENTITY_ATTRIBUTE_VALUE", paramsEx); throw new AMConsoleException(strError); } byte[][] oldUserPKCS12ByteArrs = (byte[][]) userPKCS12Map.get(USERPKCS12_BINARY_ATTRNAME); byte[] oldUserPKCS12 = oldUserPKCS12ByteArrs[0]; ByteArrayInputStream bais = new ByteArrayInputStream(oldUserPKCS12); try { keyStore.load(bais, oldPassword.toCharArray()); } catch (Exception e) { String strError = "Could not get user KeyStore using old password: " + getErrorString(e); String[] paramsEx = { userId, AMAdminConstants.ATTR_USER_OLD_PASSWORD, strError }; logEvent("SSO_EXCEPTION_MODIFY_IDENTITY_ATTRIBUTE_VALUE", paramsEx); throw new AMConsoleException(strError); } ByteArrayOutputStream baos = null; try { String alias = keyStore.aliases().nextElement(); PrivateKey privateKey = (PrivateKey) keyStore.getKey(alias, oldPassword.toCharArray()); keyStore.setKeyEntry(alias, privateKey, newPassword.toCharArray(), keyStore.getCertificateChain(alias)); baos = new ByteArrayOutputStream(); } catch (Exception e) { String strError = "Could not get Key from user KeyStore: " + getErrorString(e); String[] paramsEx = { userId, AMAdminConstants.ATTR_USER_OLD_PASSWORD, strError }; logEvent("SSO_EXCEPTION_MODIFY_IDENTITY_ATTRIBUTE_VALUE", paramsEx); throw new AMConsoleException(strError); } try { keyStore.store(baos, newPassword.toCharArray()); } catch (Exception e) { String strError = "Could not save user KeyStore: " + getErrorString(e); String[] paramsEx = { userId, AMAdminConstants.ATTR_USER_OLD_PASSWORD, strError }; logEvent("SSO_EXCEPTION_MODIFY_IDENTITY_ATTRIBUTE_VALUE", paramsEx); throw new AMConsoleException(strError); } byte[] newUserPKCS12 = baos.toByteArray(); byte[][] newUserPKCS12ByteArrs = new byte[1][]; newUserPKCS12ByteArrs[0] = newUserPKCS12; Map<String, byte[][]> newUserPKCS12Map = newUserPKCS12Map = new HashMap<String, byte[][]>(); newUserPKCS12Map.put(USERPKCS12_BINARY_ATTRNAME, newUserPKCS12ByteArrs); // Ensure that the following two lines are never out of sync (one would expect store() to be a transaction) amIdentity.setBinaryAttributes(newUserPKCS12Map); amIdentity.setAttributes(passwordMap); amIdentity.store(); } else { amIdentity.setAttributes(passwordMap); amIdentity.store(); } logEvent("SUCCEED_MODIFY_IDENTITY_ATTRIBUTE_VALUE", params); } catch (SSOException e) { String strError = getErrorString(e); String[] paramsEx = { userId, AMAdminConstants.ATTR_USER_OLD_PASSWORD, strError }; logEvent("SSO_EXCEPTION_MODIFY_IDENTITY_ATTRIBUTE_VALUE", paramsEx); throw new AMConsoleException(strError); } catch (IdRepoException e) { String strError = getErrorString(e); String[] paramsEx = { userId, AMAdminConstants.ATTR_USER_OLD_PASSWORD, strError }; logEvent("IDM_EXCEPTION_MODIFY_IDENTITY_ATTRIBUTE_VALUE", paramsEx); throw new AMConsoleException(strError); } }
From source file:org.guanxi.idp.Bootstrap.java
public boolean createSelfSignedKeystore(String cn, String keystoreFile, String keystorePassword, String privateKeyPassword, String privateKeyAlias) { KeyStore ks = null; try {/*from w w w .j a va2 s. c om*/ ks = KeyStore.getInstance("JKS"); ks.load(null, null); KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DSA"); keyGen.initialize(1024, new SecureRandom()); KeyPair keypair = keyGen.generateKeyPair(); PrivateKey privkey = keypair.getPrivate(); PublicKey pubkey = keypair.getPublic(); Hashtable<DERObjectIdentifier, String> attrs = new Hashtable<DERObjectIdentifier, String>(); Vector<DERObjectIdentifier> ordering = new Vector<DERObjectIdentifier>(); ordering.add(X509Name.CN); attrs.put(X509Name.CN, cn); X509Name issuerDN = new X509Name(ordering, attrs); X509Name subjectDN = new X509Name(ordering, attrs); Date validFrom = new Date(); validFrom.setTime(validFrom.getTime() - (10 * 60 * 1000)); Date validTo = new Date(); validTo.setTime(validTo.getTime() + (20 * (24 * 60 * 60 * 1000))); X509V3CertificateGenerator x509 = new X509V3CertificateGenerator(); x509.setSignatureAlgorithm("SHA1withDSA"); x509.setIssuerDN(issuerDN); x509.setSubjectDN(subjectDN); x509.setPublicKey(pubkey); x509.setNotBefore(validFrom); x509.setNotAfter(validTo); x509.setSerialNumber(new BigInteger(128, new Random())); X509Certificate[] cert = new X509Certificate[1]; cert[0] = x509.generate(privkey, "BC"); java.security.cert.Certificate[] chain = new java.security.cert.Certificate[1]; chain[0] = cert[0]; ks.setKeyEntry(privateKeyAlias, privkey, privateKeyPassword.toCharArray(), cert); ks.setKeyEntry(privateKeyAlias, privkey, privateKeyPassword.toCharArray(), chain); ks.store(new FileOutputStream(keystoreFile), keystorePassword.toCharArray()); String IDP_RFC_CERT = "WEB-INF/guanxi_idp/keystore/guanxi_idp_cert.txt"; PEMWriter pemWriter = new PEMWriter(new FileWriter(servletContext.getRealPath(IDP_RFC_CERT))); pemWriter.writeObject(cert[0]); pemWriter.close(); return true; } catch (Exception se) { return false; } }
From source file:com.cws.esolutions.security.dao.certmgmt.impl.CertificateManagerImpl.java
/** * @see com.cws.esolutions.security.dao.certmgmt.interfaces.ICertificateManager#applyCertificateRequest(String, File, File, String) *///from w w w . j a v a2 s . c om public synchronized boolean applyCertificateRequest(final String commonName, final File certificateFile, final File keystoreFile, final String storePassword) throws CertificateManagementException { final String methodName = ICertificateManager.CNAME + "#applyCertificateRequest(final String commonName, final File certificateFile, final File keystoreFile, final String storePassword) throws CertificateManagementException"; if (DEBUG) { DEBUGGER.debug(methodName); DEBUGGER.debug("Value: {}", commonName); DEBUGGER.debug("Value: {}", certificateFile); DEBUGGER.debug("Value: {}", keystoreFile); } final File rootDirectory = certConfig.getRootDirectory(); final File certificateDirectory = FileUtils .getFile(certConfig.getCertificateDirectory() + "/" + commonName); final File storeDirectory = FileUtils.getFile(certConfig.getStoreDirectory() + "/" + commonName); if (DEBUG) { DEBUGGER.debug("rootDirectory: {}", rootDirectory); DEBUGGER.debug("certificateDirectory: {}", certificateDirectory); DEBUGGER.debug("storeDirectory: {}", storeDirectory); DEBUGGER.debug("certificateFile: {}", certificateFile); DEBUGGER.debug("keystoreFile: {}", keystoreFile); } boolean isComplete = false; FileInputStream certStream = null; FileOutputStream storeStream = null; FileInputStream keystoreInput = null; FileInputStream rootCertStream = null; FileInputStream intermediateCertStream = null; try { if (!(rootDirectory.exists())) { throw new CertificateManagementException( "Root certificate directory either does not exist or cannot be written to. Cannot continue."); } if (!(rootDirectory.canWrite())) { throw new CertificateManagementException( "Root certificate directory either does not exist or cannot be written to. Cannot continue."); } if (!(certConfig.getRootCertificateFile().exists())) { throw new CertificateManagementException("Root certificate file does not exist. Cannot continue."); } if (!(certConfig.getIntermediateCertificateFile().exists())) { throw new CertificateManagementException( "Intermediate certificate file does not exist. Cannot continue."); } if (!(storeDirectory.canWrite())) { throw new CertificateManagementException( "Keystore directory either does not exist or cannot be written to. Cannot continue."); } if (!(keystoreFile.canWrite())) { throw new CertificateManagementException( "Unable to write to applicable keystore. Cannot continue."); } keystoreInput = FileUtils.openInputStream(keystoreFile); certStream = FileUtils.openInputStream(certificateFile); if (DEBUG) { DEBUGGER.debug("keystoreInput: {}", keystoreInput); DEBUGGER.debug("certStream: {}", certStream); } KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); keyStore.load(keystoreInput, storePassword.toCharArray()); if (DEBUG) { DEBUGGER.debug("KeyStore: {}", keyStore); } Key privateKey = keyStore.getKey(commonName, storePassword.toCharArray()); CertificateFactory certFactory = CertificateFactory.getInstance(certConfig.getCertificateType()); if (DEBUG) { DEBUGGER.debug("CertificateFactory: {}", certFactory); } rootCertStream = FileUtils.openInputStream(FileUtils.getFile(certConfig.getRootCertificateFile())); intermediateCertStream = FileUtils .openInputStream(FileUtils.getFile(certConfig.getIntermediateCertificateFile())); if (DEBUG) { DEBUGGER.debug("rootCertStream: {}", rootCertStream); DEBUGGER.debug("intermediateCertStream: {}", intermediateCertStream); } X509Certificate[] responseCert = new X509Certificate[] { (X509Certificate) certFactory.generateCertificate(rootCertStream), (X509Certificate) certFactory.generateCertificate(intermediateCertStream), (X509Certificate) certFactory.generateCertificate(certStream) }; if (DEBUG) { DEBUGGER.debug("X509Certificate[]", (Object) responseCert); } storeStream = FileUtils.openOutputStream(keystoreFile); keyStore.setKeyEntry(commonName, privateKey, storePassword.toCharArray(), responseCert); keyStore.store(storeStream, storePassword.toCharArray()); isComplete = true; } catch (FileNotFoundException fnfx) { throw new CertificateManagementException(fnfx.getMessage(), fnfx); } catch (IOException iox) { throw new CertificateManagementException(iox.getMessage(), iox); } catch (NoSuchAlgorithmException nsax) { throw new CertificateManagementException(nsax.getMessage(), nsax); } catch (IllegalStateException isx) { throw new CertificateManagementException(isx.getMessage(), isx); } catch (KeyStoreException ksx) { throw new CertificateManagementException(ksx.getMessage(), ksx); } catch (CertificateException cx) { throw new CertificateManagementException(cx.getMessage(), cx); } catch (UnrecoverableKeyException ukx) { throw new CertificateManagementException(ukx.getMessage(), ukx); } finally { if (storeStream != null) { IOUtils.closeQuietly(storeStream); } if (intermediateCertStream != null) { IOUtils.closeQuietly(intermediateCertStream); } if (rootCertStream != null) { IOUtils.closeQuietly(rootCertStream); } if (certStream != null) { IOUtils.closeQuietly(certStream); } if (keystoreInput != null) { IOUtils.closeQuietly(keystoreInput); } } return isComplete; }