List of usage examples for java.security KeyStore getCertificate
public final Certificate getCertificate(String alias) throws KeyStoreException
From source file:psiprobe.controllers.certificates.ListCertificatesController.java
/** * Gets the certificates.//from www . ja v a 2 s . c o m * * @param storeType the store type * @param storeFile the store file * @param storePassword the store password * @return the certificates * @throws Exception the exception */ public List<Cert> getCertificates(String storeType, String storeFile, String storePassword) throws Exception { KeyStore keyStore; // Get key store if (storeType != null) { keyStore = KeyStore.getInstance(storeType); } else { keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); } // Get password char[] password = null; if (storePassword != null) { password = storePassword.toCharArray(); } // Load key store from file try (InputStream storeInput = getStoreInputStream(storeFile)) { keyStore.load(storeInput, password); } catch (IOException e) { logger.error("Error loading store file {}", storeFile, e); return null; } List<Cert> certs = new ArrayList<>(); for (String alias : Collections.list(keyStore.aliases())) { Certificate[] certificateChains = keyStore.getCertificateChain(alias); if (certificateChains != null) { for (Certificate certificateChain : certificateChains) { X509Certificate x509Cert = (X509Certificate) certificateChain; addToStore(certs, alias, x509Cert); } } else { X509Certificate x509Cert = (X509Certificate) keyStore.getCertificate(alias); addToStore(certs, alias, x509Cert); } } return certs; }
From source file:org.apache.geode.internal.cache.tier.sockets.HandShake.java
/** * Load the private key of the server. This method is not thread safe. *///w ww. j a va2 s. c om public static void initPrivateKey(Properties props) throws Exception { String privateKeyFilePath = props.getProperty(PRIVATE_KEY_FILE_PROP); privateKeyAlias = ""; privateKeyEncrypt = null; if (privateKeyFilePath != null && privateKeyFilePath.length() > 0) { KeyStore ks = KeyStore.getInstance("PKCS12"); privateKeyAlias = props.getProperty(PRIVATE_KEY_ALIAS_PROP); if (privateKeyAlias == null) { privateKeyAlias = ""; } String keyStorePass = props.getProperty(PRIVATE_KEY_PASSWD_PROP); char[] passPhrase = (keyStorePass != null ? keyStorePass.toCharArray() : null); FileInputStream privateKeyFile = new FileInputStream(privateKeyFilePath); try { ks.load(privateKeyFile, passPhrase); } finally { privateKeyFile.close(); } Key key = ks.getKey(privateKeyAlias, passPhrase); Certificate keyCert = ks.getCertificate(privateKeyAlias); if (key instanceof PrivateKey && keyCert instanceof X509Certificate) { privateKeyEncrypt = (PrivateKey) key; privateKeySignAlgo = ((X509Certificate) keyCert).getSigAlgName(); privateKeySubject = ((X509Certificate) keyCert).getSubjectDN().getName(); } } }
From source file:mitm.djigzo.web.pages.certificate.CertificateImportKey.java
private void importPfx() throws KeyStoreException, NoSuchProviderException, SecurityFactoryFactoryException, NoSuchAlgorithmException, CertificateException, IOException, UnrecoverableEntryException, WebServiceCheckedException {/*from w ww . ja v a2 s .co m*/ /* * To prevent timeouts on the SOAP connection we should upload the PFX file in batches if the PFX file * contains a large number of entries. The PFX file should therefore be opened. */ KeyStore allKeys = SecurityFactoryFactory.getSecurityFactory().createKeyStore("PKCS12"); if (password == null) { password = ""; } allKeys.load(file.getStream(), password.toCharArray()); KeyAndCertificateWorkflow.MissingKey missingKey = ignoreMissingKey ? KeyAndCertificateWorkflow.MissingKey.SKIP_CERTIFICATE : KeyAndCertificateWorkflow.MissingKey.ADD_CERTIFICATE; int imported = 0; KeyStore batchKeys = SecurityFactoryFactory.getSecurityFactory().createKeyStore("PKCS12"); batchKeys.load(null, password.toCharArray()); Enumeration<String> aliases = allKeys.aliases(); KeyStore.PasswordProtection passwordProtection = new KeyStore.PasswordProtection(password.toCharArray()); while (aliases.hasMoreElements()) { String alias = aliases.nextElement(); if (allKeys.isKeyEntry(alias)) { KeyStore.Entry entry = allKeys.getEntry(alias, passwordProtection); batchKeys.setEntry(alias, entry, passwordProtection); } else { Certificate certificate = allKeys.getCertificate(alias); batchKeys.setCertificateEntry(alias, certificate); } if (batchKeys.size() >= maxBatchSize) { imported += uploadKeyStore(batchKeys, missingKey, password); batchKeys = SecurityFactoryFactory.getSecurityFactory().createKeyStore("PKCS12"); batchKeys.load(null, password.toCharArray()); } } /* * Check if there are still some entries left to add (happens when the number * of entries is not a multiple of maxBatchSize) */ if (batchKeys.size() > 0) { imported += uploadKeyStore(batchKeys, missingKey, password); } this.importCount = imported; }
From source file:gov.nih.nci.cacisweb.action.SecureFTPAction.java
@Override public String input() throws Exception { log.debug("input() - START"); secureFTPRecepientList = new ArrayList<SecureFTPModel>(); String secureFTPPropertyFileLocation = CaCISUtil .getProperty(CaCISWebConstants.COM_PROPERTY_NAME_SECFTP_PROPERTIES_FILE_LOCATION); String secureFTPKeystoreLocation = CaCISUtil.getPropertyFromPropertiesFile(secureFTPPropertyFileLocation, CaCISUtil.getProperty(CaCISWebConstants.COM_PROPERTY_NAME_SECFTP_TRUSTSTORE_LOCATION_PROP_NAME)); String secureFTPKeystorePassword = CaCISUtil.getPropertyFromPropertiesFile(secureFTPPropertyFileLocation, CaCISUtil.getProperty(CaCISWebConstants.COM_PROPERTY_NAME_SECFTP_TRUSTSTORE_PASSWORD_PROP_NAME)); CaCISUtil caCISUtil = new CaCISUtil(); String propertyFileLocation = CaCISUtil .getProperty(CaCISWebConstants.COM_PROPERTY_NAME_SECFTP_CONFIG_FILE_LOCATION); try {//from w ww. j av a2 s. c o m caCISUtil.isPropertyFileAndKeystoreInSync(propertyFileLocation, secureFTPKeystoreLocation, CaCISWebConstants.COM_KEYSTORE_TYPE_JKS, secureFTPKeystorePassword); } catch (PropFileAndKeystoreOutOfSyncException e) { if (!StringUtils.contains(e.getMessage(), "sftp")) { log.error(e.getMessage()); addActionError(e.getMessage()); } } try { KeyStore keystore = caCISUtil.getKeystore(secureFTPKeystoreLocation, CaCISWebConstants.COM_KEYSTORE_TYPE_JKS, secureFTPKeystorePassword); // // List the aliases // Enumeration<String> enumeration = keystore.aliases(); Properties configFile = new Properties(); InputStream is = new FileInputStream(propertyFileLocation); configFile.load(is); is.close(); Enumeration<Object> enumeration = configFile.keys(); // while (enumeration.hasMoreElements()) { // String alias = (String) enumeration.nextElement(); // X509Certificate x509Certificate = (X509Certificate) keystore.getCertificate(alias); // SecureFTPModel secureFTPModel = new SecureFTPModel(); // secureFTPModel.setCertificateAlias(alias); // secureFTPModel.setCertificateDN(x509Certificate.getSubjectDN().toString()); // secureFTPRecepientList.add(secureFTPModel); // log.debug("Alias: " + alias + " DN: " + x509Certificate.getSubjectDN().getName()); // } while (enumeration.hasMoreElements()) { String alias = (String) enumeration.nextElement(); X509Certificate x509Certificate = (X509Certificate) keystore.getCertificate(alias); String distinguishedName = ""; if (x509Certificate != null) { distinguishedName = x509Certificate.getSubjectDN().toString(); } SecureFTPModel secureFTPModel = new SecureFTPModel(); secureFTPModel.setCertificateAlias(alias); secureFTPModel.setCertificateDN(distinguishedName); secureFTPRecepientList.add(secureFTPModel); log.debug("Alias: " + alias + " DN: " + distinguishedName); } caCISUtil.releaseKeystore(); } catch (KeystoreInstantiationException kie) { log.error(kie.getMessage()); addActionError(getText("exception.keystoreInstantiation")); return ERROR; } log.debug("input() - END"); return INPUT; }
From source file:test.integ.be.fedict.commons.eid.client.JCATest.java
@Test public void testBeIDSignature() throws Exception { Security.addProvider(new BeIDProvider()); final KeyStore keyStore = KeyStore.getInstance("BeID"); final BeIDKeyStoreParameter keyStoreParameter = new BeIDKeyStoreParameter(); final BeIDCard beIDCard = getBeIDCard(); keyStoreParameter.setBeIDCard(beIDCard); keyStoreParameter.setLogoff(true);/*from w w w . ja v a2s. c o m*/ keyStore.load(keyStoreParameter); final Enumeration<String> aliases = keyStore.aliases(); while (aliases.hasMoreElements()) { final String alias = aliases.nextElement(); LOG.debug("alias: " + alias); } assertEquals(2, keyStore.size()); assertTrue(keyStore.containsAlias("Signature")); assertTrue(keyStore.containsAlias("Authentication")); assertNotNull(keyStore.getCreationDate("Signature")); assertNotNull(keyStore.getCreationDate("Authentication")); assertTrue(keyStore.isKeyEntry("Signature")); final X509Certificate signCertificate = (X509Certificate) keyStore.getCertificate("Signature"); assertNotNull(signCertificate); assertTrue(keyStore.isKeyEntry("Authentication")); final X509Certificate authnCertificate = (X509Certificate) keyStore.getCertificate("Authentication"); assertNotNull(authnCertificate); assertNotNull(keyStore.getCertificateChain("Signature")); assertNotNull(keyStore.getCertificateChain("Authentication")); assertTrue(keyStore.isKeyEntry("Authentication")); final PrivateKey authnPrivateKey = (PrivateKey) keyStore.getKey("Authentication", null); assertNotNull(authnPrivateKey); assertTrue(keyStore.isKeyEntry("Signature")); final PrivateKey signPrivateKey = (PrivateKey) keyStore.getKey("Signature", null); assertNotNull(signPrivateKey); verifySignatureAlgorithm("SHA1withRSA", authnPrivateKey, authnCertificate.getPublicKey()); verifySignatureAlgorithm("SHA256withRSA", signPrivateKey, signCertificate.getPublicKey()); verifySignatureAlgorithm("SHA384withRSA", authnPrivateKey, authnCertificate.getPublicKey()); verifySignatureAlgorithm("SHA512withRSA", authnPrivateKey, authnCertificate.getPublicKey()); Security.addProvider(new BouncyCastleProvider()); verifySignatureAlgorithm("SHA1withRSAandMGF1", authnPrivateKey, authnCertificate.getPublicKey()); verifySignatureAlgorithm("SHA256withRSAandMGF1", authnPrivateKey, authnCertificate.getPublicKey()); }
From source file:org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.enrollment.EnrollmentManager.java
public void setEnrollmentStatus() { KeyStore keyStore; try {// w ww. j a v a2 s . c om keyStore = KeyStore.getInstance(AgentConstants.DEVICE_KEYSTORE_TYPE); this.isEnrolled = (keyStore.containsAlias(AgentConstants.DEVICE_CERT_ALIAS) && keyStore.containsAlias(AgentConstants.DEVICE_PRIVATE_KEY_ALIAS) && keyStore.containsAlias(AgentConstants.SERVER_CA_CERT_ALIAS)); } catch (KeyStoreException e) { log.error(AgentConstants.LOG_APPENDER + "An error occurred whilst accessing the device KeyStore '" + AgentConstants.DEVICE_KEYSTORE + "' with keystore type [" + AgentConstants.DEVICE_KEYSTORE_TYPE + "] to ensure enrollment status."); log.error(AgentConstants.LOG_APPENDER + e); log.warn(AgentConstants.LOG_APPENDER + "Device will be re-enrolled."); return; } try { if (this.isEnrolled) { this.SCEPCertificate = (X509Certificate) keyStore.getCertificate(AgentConstants.DEVICE_CERT_ALIAS); this.privateKey = (PrivateKey) keyStore.getKey(AgentConstants.DEVICE_PRIVATE_KEY_ALIAS, AgentConstants.DEVICE_KEYSTORE_PASSWORD.toCharArray()); this.publicKey = SCEPCertificate.getPublicKey(); X509Certificate serverCACert = (X509Certificate) keyStore .getCertificate(AgentConstants.SERVER_CA_CERT_ALIAS); this.serverPublicKey = serverCACert.getPublicKey(); log.info(AgentConstants.LOG_APPENDER + "Device has already been enrolled. Hence, loaded certificate information from device" + " trust-store."); } } catch (UnrecoverableKeyException | NoSuchAlgorithmException | KeyStoreException e) { log.error(AgentConstants.LOG_APPENDER + "An error occurred whilst accessing the device KeyStore '" + AgentConstants.DEVICE_KEYSTORE + "' to ensure enrollment status."); log.error(AgentConstants.LOG_APPENDER + e); log.warn(AgentConstants.LOG_APPENDER + "Device will be re-enrolled."); this.isEnrolled = false; } }
From source file:org.codice.ddf.security.certificate.keystore.editor.KeystoreEditor.java
private synchronized void addToStore(String alias, String keyPassword, String storePassword, String data, String type, String fileName, String path, String storepass, KeyStore store) throws KeystoreEditorException { OutputStream fos = null;/*from ww w . ja v a2 s .c om*/ try (InputStream inputStream = new ByteArrayInputStream(Base64.getDecoder().decode(data))) { if (StringUtils.isBlank(alias)) { throw new IllegalArgumentException("Alias cannot be null."); } Path storeFile = Paths.get(path); //check the two most common key/cert stores first (pkcs12 and jks) if (PKCS12_TYPE.equals(type) || StringUtils.endsWithIgnoreCase(fileName, ".p12")) { //priv key + cert chain KeyStore pkcs12Store = KeyStore.getInstance("PKCS12"); pkcs12Store.load(inputStream, storePassword.toCharArray()); Certificate[] chain = pkcs12Store.getCertificateChain(alias); Key key = pkcs12Store.getKey(alias, keyPassword.toCharArray()); if (key != null) { store.setKeyEntry(alias, key, keyPassword.toCharArray(), chain); fos = Files.newOutputStream(storeFile); store.store(fos, storepass.toCharArray()); } } else if (JKS_TYPE.equals(type) || StringUtils.endsWithIgnoreCase(fileName, ".jks")) { //java keystore file KeyStore jks = KeyStore.getInstance("jks"); jks.load(inputStream, storePassword.toCharArray()); Enumeration<String> aliases = jks.aliases(); //we are going to store all entries from the jks regardless of the passed in alias while (aliases.hasMoreElements()) { String jksAlias = aliases.nextElement(); if (jks.isKeyEntry(jksAlias)) { Key key = jks.getKey(jksAlias, keyPassword.toCharArray()); Certificate[] certificateChain = jks.getCertificateChain(jksAlias); store.setKeyEntry(jksAlias, key, keyPassword.toCharArray(), certificateChain); } else { Certificate certificate = jks.getCertificate(jksAlias); store.setCertificateEntry(jksAlias, certificate); } } fos = Files.newOutputStream(storeFile); store.store(fos, storepass.toCharArray()); //need to parse der separately from pem, der has the same mime type but is binary hence checking both } else if (DER_TYPE.equals(type) && StringUtils.endsWithIgnoreCase(fileName, ".der")) { ASN1InputStream asn1InputStream = new ASN1InputStream(inputStream); ASN1Primitive asn1Primitive = asn1InputStream.readObject(); X509CertificateHolder x509CertificateHolder = new X509CertificateHolder(asn1Primitive.getEncoded()); CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509", "BC"); Certificate certificate = certificateFactory .generateCertificate(new ByteArrayInputStream(x509CertificateHolder.getEncoded())); X500Name x500name = new JcaX509CertificateHolder((X509Certificate) certificate).getSubject(); RDN cn = x500name.getRDNs(BCStyle.CN)[0]; String cnStr = IETFUtils.valueToString(cn.getFirst().getValue()); if (!store.isCertificateEntry(cnStr) && !store.isKeyEntry(cnStr)) { store.setCertificateEntry(cnStr, certificate); } store.setCertificateEntry(alias, certificate); fos = Files.newOutputStream(storeFile); store.store(fos, storepass.toCharArray()); //if it isn't one of the stores we support, it might be a key or cert by itself } else if (isPemParsable(type, fileName)) { //This is the catch all case for PEM, P7B, etc. with common file extensions if the mime type isn't read correctly in the browser Reader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8)); PEMParser pemParser = new PEMParser(reader); Object object; boolean setEntry = false; while ((object = pemParser.readObject()) != null) { if (object instanceof PEMEncryptedKeyPair || object instanceof PEMKeyPair) { PEMKeyPair pemKeyPair; if (object instanceof PEMEncryptedKeyPair) { PEMEncryptedKeyPair pemEncryptedKeyPairKeyPair = (PEMEncryptedKeyPair) object; JcePEMDecryptorProviderBuilder jcePEMDecryptorProviderBuilder = new JcePEMDecryptorProviderBuilder(); pemKeyPair = pemEncryptedKeyPairKeyPair.decryptKeyPair( jcePEMDecryptorProviderBuilder.build(keyPassword.toCharArray())); } else { pemKeyPair = (PEMKeyPair) object; } KeyPair keyPair = new JcaPEMKeyConverter().setProvider("BC").getKeyPair(pemKeyPair); PrivateKey privateKey = keyPair.getPrivate(); Certificate[] chain = store.getCertificateChain(alias); if (chain == null) { chain = buildCertChain(alias, store); } store.setKeyEntry(alias, privateKey, keyPassword.toCharArray(), chain); setEntry = true; } else if (object instanceof X509CertificateHolder) { X509CertificateHolder x509CertificateHolder = (X509CertificateHolder) object; CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509", "BC"); Certificate certificate = certificateFactory .generateCertificate(new ByteArrayInputStream(x509CertificateHolder.getEncoded())); X500Name x500name = new JcaX509CertificateHolder((X509Certificate) certificate) .getSubject(); RDN cn = x500name.getRDNs(BCStyle.CN)[0]; String cnStr = IETFUtils.valueToString(cn.getFirst().getValue()); if (!store.isCertificateEntry(cnStr) && !store.isKeyEntry(cnStr)) { store.setCertificateEntry(cnStr, certificate); } store.setCertificateEntry(alias, certificate); setEntry = true; } else if (object instanceof ContentInfo) { ContentInfo contentInfo = (ContentInfo) object; if (contentInfo.getContentType().equals(CMSObjectIdentifiers.envelopedData)) { CMSEnvelopedData cmsEnvelopedData = new CMSEnvelopedData(contentInfo); OriginatorInfo originatorInfo = cmsEnvelopedData.getOriginatorInfo().toASN1Structure(); ASN1Set certificates = originatorInfo.getCertificates(); setEntry = importASN1CertificatesToStore(store, setEntry, certificates); } else if (contentInfo.getContentType().equals(CMSObjectIdentifiers.signedData)) { SignedData signedData = SignedData.getInstance(contentInfo.getContent()); ASN1Set certificates = signedData.getCertificates(); setEntry = importASN1CertificatesToStore(store, setEntry, certificates); } } else if (object instanceof PKCS8EncryptedPrivateKeyInfo) { PKCS8EncryptedPrivateKeyInfo pkcs8EncryptedPrivateKeyInfo = (PKCS8EncryptedPrivateKeyInfo) object; Certificate[] chain = store.getCertificateChain(alias); if (chain == null) { chain = buildCertChain(alias, store); } try { store.setKeyEntry(alias, pkcs8EncryptedPrivateKeyInfo.getEncoded(), chain); setEntry = true; } catch (KeyStoreException keyEx) { try { PKCS8Key pkcs8Key = new PKCS8Key(pkcs8EncryptedPrivateKeyInfo.getEncoded(), keyPassword.toCharArray()); store.setKeyEntry(alias, pkcs8Key.getPrivateKey(), keyPassword.toCharArray(), chain); setEntry = true; } catch (GeneralSecurityException e) { LOGGER.error( "Unable to add PKCS8 key to keystore with secondary method. Throwing original exception.", e); throw keyEx; } } } } if (setEntry) { fos = Files.newOutputStream(storeFile); store.store(fos, storepass.toCharArray()); } } } catch (Exception e) { LOGGER.error("Unable to add entry {} to store", alias, e); throw new KeystoreEditorException("Unable to add entry " + alias + " to store", e); } finally { if (fos != null) { try { fos.close(); } catch (IOException ignore) { } } } init(); }
From source file:com.tremolosecurity.config.util.UnisonConfigManagerImpl.java
private void initSSL() throws KeyManagementException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException, CertificateException, FileNotFoundException, IOException { if (this.getKeyManagerFactory() == null) { return;/*from w w w . ja v a 2 s . co m*/ } KeyStore cacerts = KeyStore.getInstance(KeyStore.getDefaultType()); String cacertsPath = System.getProperty("javax.net.ssl.trustStore"); if (cacertsPath == null) { cacertsPath = System.getProperty("java.home") + "/lib/security/cacerts"; } cacerts.load(new FileInputStream(cacertsPath), null); Enumeration<String> enumer = cacerts.aliases(); while (enumer.hasMoreElements()) { String alias = enumer.nextElement(); java.security.cert.Certificate cert = cacerts.getCertificate(alias); this.ks.setCertificateEntry(alias, cert); } SSLContext sslctx = SSLContexts.custom().loadTrustMaterial(this.ks) .loadKeyMaterial(this.ks, this.cfg.getKeyStorePassword().toCharArray()).build(); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslctx, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); PlainConnectionSocketFactory sf = PlainConnectionSocketFactory.getSocketFactory(); httpClientRegistry = RegistryBuilder.<ConnectionSocketFactory>create().register("http", sf) .register("https", sslsf).build(); globalHttpClientConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.IGNORE_COOKIES) .setRedirectsEnabled(false).setAuthenticationEnabled(false).build(); }
From source file:org.wso2.carbon.mdm.mobileservices.windowspc.services.wstep.impl.CertificateEnrollmentServiceImpl.java
/** * Method for setting privateKey and rootCACertificate variables. * * @throws KeyStoreGenerationException//from ww w. j ava 2 s . c om * @throws org.wso2.carbon.mdm.mobileservices.windows.common.exceptions * .XMLFileOperationException * @throws CertificateGenerationException */ public void setRootCertAndKey(String storePassword, String keyPassword) throws KeyStoreGenerationException, XMLFileOperationException, CertificateGenerationException { File JKSFile = new File(getClass().getClassLoader() .getResource(Constants.CertificateEnrollment.WSO2_MDM_JKS_FILE).getFile()); String JKSFilePath = JKSFile.getPath(); KeyStore securityJKS; try { securityJKS = KeyStoreGenerator.getKeyStore(); } catch (KeyStoreGenerationException e) { throw new KeyStoreGenerationException("Cannot retrieve the MDM key store.", e); } try { KeyStoreGenerator.loadToStore(securityJKS, storePassword.toCharArray(), JKSFilePath); } catch (KeyStoreGenerationException e) { throw new KeyStoreGenerationException("Cannot load the MDM key store.", e); } PrivateKey CAPrivateKey; try { CAPrivateKey = (PrivateKey) securityJKS.getKey(Constants.CertificateEnrollment.CA_CERT, keyPassword.toCharArray()); } catch (KeyStoreException e) { throw new CertificateGenerationException("Cannot generate private key due to Key store error.", e); } catch (NoSuchAlgorithmException e) { throw new CertificateGenerationException( "Requested cryptographic algorithm is not available in the environment.", e); } catch (UnrecoverableKeyException e) { throw new CertificateGenerationException("Cannot recover private key.", e); } privateKey = CAPrivateKey; Certificate CACertificate; try { CACertificate = securityJKS.getCertificate(Constants.CertificateEnrollment.CA_CERT); } catch (KeyStoreException e) { throw new KeyStoreGenerationException("Keystore cannot be accessed.", e); } CertificateFactory certificateFactory; try { certificateFactory = CertificateFactory.getInstance(Constants.CertificateEnrollment.X_509); } catch (CertificateException e) { throw new CertificateGenerationException("Cannot initiate certificate factory.", e); } ByteArrayInputStream byteArrayInputStream; try { byteArrayInputStream = new ByteArrayInputStream(CACertificate.getEncoded()); } catch (CertificateEncodingException e) { throw new CertificateGenerationException("CA certificate cannot be encoded.", e); } X509Certificate X509CACertificate; try { X509CACertificate = (X509Certificate) certificateFactory.generateCertificate(byteArrayInputStream); } catch (CertificateException e) { throw new CertificateGenerationException("X509 CA certificate cannot be generated.", e); } rootCACertificate = X509CACertificate; }