List of usage examples for java.security KeyStore getCertificateChain
public final Certificate[] getCertificateChain(String alias) throws KeyStoreException
From source file:net.sf.keystore_explorer.gui.actions.SignCsrAction.java
/** * Do action./*from w ww . java 2s.c om*/ */ @Override protected void doAction() { FileOutputStream fos = null; File caReplyFile = null; try { KeyStoreHistory history = kseFrame.getActiveKeyStoreHistory(); KeyStoreState currentState = history.getCurrentState(); String alias = kseFrame.getSelectedEntryAlias(); Password password = getEntryPassword(alias, currentState); if (password == null) { return; } KeyStore keyStore = currentState.getKeyStore(); PrivateKey privateKey = (PrivateKey) keyStore.getKey(alias, password.toCharArray()); Certificate[] certs = keyStore.getCertificateChain(alias); KeyPairType keyPairType = KeyPairUtil.getKeyPairType(privateKey); File csrFile = chooseCsrFile(); if (csrFile == null) { return; } PKCS10CertificationRequest pkcs10Csr = null; Spkac spkacCsr = null; try { CryptoFileType fileType = CryptoFileUtil.detectFileType(new FileInputStream(csrFile)); if (fileType == CryptoFileType.PKCS10_CSR) { pkcs10Csr = Pkcs10Util.loadCsr(new FileInputStream(csrFile)); if (!Pkcs10Util.verifyCsr(pkcs10Csr)) { JOptionPane.showMessageDialog(frame, res.getString("SignCsrAction.NoVerifyPkcs10Csr.message"), res.getString("SignCsrAction.SignCsr.Title"), JOptionPane.WARNING_MESSAGE); return; } } else if (fileType == CryptoFileType.SPKAC_CSR) { spkacCsr = new Spkac(new FileInputStream(csrFile)); if (!spkacCsr.verify()) { JOptionPane.showMessageDialog(frame, res.getString("SignCsrAction.NoVerifySpkacCsr.message"), res.getString("SignCsrAction.SignCsr.Title"), JOptionPane.WARNING_MESSAGE); return; } } else { JOptionPane.showMessageDialog(frame, MessageFormat.format(res.getString("SignCsrAction.FileNotRecognisedType.message"), csrFile), res.getString("SignCsrAction.SignCsr.Title"), JOptionPane.WARNING_MESSAGE); return; } } catch (FileNotFoundException ex) { JOptionPane.showMessageDialog(frame, MessageFormat.format(res.getString("SignCsrAction.NotFile.message"), csrFile), res.getString("SignCsrAction.SignCsr.Title"), JOptionPane.WARNING_MESSAGE); return; } catch (Exception ex) { String problemStr = MessageFormat.format(res.getString("SignCsrAction.NoOpenCsr.Problem"), csrFile.getName()); String[] causes = new String[] { res.getString("SignCsrAction.NotCsr.Cause"), res.getString("SignCsrAction.CorruptedCsr.Cause") }; Problem problem = new Problem(problemStr, causes, ex); DProblem dProblem = new DProblem(frame, res.getString("SignCsrAction.ProblemOpeningCsr.Title"), problem); dProblem.setLocationRelativeTo(frame); dProblem.setVisible(true); return; } X509Certificate[] signingChain = X509CertUtil .orderX509CertChain(X509CertUtil.convertCertificates(certs)); X509Certificate signingCert = signingChain[0]; PublicKey publicKey = null; X500Name subject = null; DSignCsr dSignCsr = null; Provider provider = history.getExplicitProvider(); if (pkcs10Csr != null) { publicKey = new JcaPKCS10CertificationRequest(pkcs10Csr).getPublicKey(); subject = pkcs10Csr.getSubject(); dSignCsr = new DSignCsr(frame, pkcs10Csr, csrFile, privateKey, keyPairType, signingCert, provider); } else { publicKey = spkacCsr.getPublicKey(); subject = spkacCsr.getSubject().getName(); dSignCsr = new DSignCsr(frame, spkacCsr, csrFile, privateKey, keyPairType, signingCert, provider); } dSignCsr.setLocationRelativeTo(frame); dSignCsr.setVisible(true); X509CertificateVersion version = dSignCsr.getVersion(); SignatureType signatureType = dSignCsr.getSignatureType(); long validityPeriod = dSignCsr.getValidityPeriod(); BigInteger serialNumber = dSignCsr.getSerialNumber(); caReplyFile = dSignCsr.getCaReplyFile(); X509ExtensionSet extensions = dSignCsr.getExtensions(); if (version == null) { return; } X500Name issuer = X500NameUtils.x500PrincipalToX500Name(signingCert.getSubjectX500Principal()); // CA Reply is a cert with subject from CSR and issuer from signing cert's subject X509CertificateGenerator generator = new X509CertificateGenerator(version); X509Certificate caReplyCert = generator.generate(subject, issuer, validityPeriod, publicKey, privateKey, signatureType, serialNumber, extensions, provider); X509Certificate[] caReplyChain = new X509Certificate[signingChain.length + 1]; caReplyChain[0] = caReplyCert; // Add all of the signing chain to the reply System.arraycopy(signingChain, 0, caReplyChain, 1, signingChain.length); byte[] caCertEncoded = X509CertUtil.getCertsEncodedPkcs7(caReplyChain); fos = new FileOutputStream(caReplyFile); fos.write(caCertEncoded); } catch (FileNotFoundException ex) { JOptionPane.showMessageDialog(frame, MessageFormat.format(res.getString("SignJarAction.NoWriteFile.message"), caReplyFile), res.getString("SignCsrAction.SignCsr.Title"), JOptionPane.WARNING_MESSAGE); return; } catch (Exception ex) { DError.displayError(frame, ex); return; } finally { IOUtils.closeQuietly(fos); } JOptionPane.showMessageDialog(frame, res.getString("SignCsrAction.SignCsrSuccessful.message"), res.getString("SignCsrAction.SignCsr.Title"), JOptionPane.INFORMATION_MESSAGE); }
From source file:org.kse.gui.actions.SignCsrAction.java
/** * Do action.//from ww w .j a v a 2s. co m */ @Override protected void doAction() { FileOutputStream fos = null; File caReplyFile = null; try { KeyStoreHistory history = kseFrame.getActiveKeyStoreHistory(); KeyStoreState currentState = history.getCurrentState(); String alias = kseFrame.getSelectedEntryAlias(); Password password = getEntryPassword(alias, currentState); if (password == null) { return; } KeyStore keyStore = currentState.getKeyStore(); PrivateKey privateKey = (PrivateKey) keyStore.getKey(alias, password.toCharArray()); Certificate[] certs = keyStore.getCertificateChain(alias); KeyPairType keyPairType = KeyPairUtil.getKeyPairType(privateKey); File csrFile = chooseCsrFile(); if (csrFile == null) { return; } PKCS10CertificationRequest pkcs10Csr = null; Spkac spkacCsr = null; try { CryptoFileType fileType = CryptoFileUtil.detectFileType(new FileInputStream(csrFile)); if (fileType == CryptoFileType.PKCS10_CSR) { pkcs10Csr = Pkcs10Util.loadCsr(new FileInputStream(csrFile)); if (!Pkcs10Util.verifyCsr(pkcs10Csr)) { JOptionPane.showMessageDialog(frame, res.getString("SignCsrAction.NoVerifyPkcs10Csr.message"), res.getString("SignCsrAction.SignCsr.Title"), JOptionPane.WARNING_MESSAGE); return; } } else if (fileType == CryptoFileType.SPKAC_CSR) { spkacCsr = new Spkac(new FileInputStream(csrFile)); if (!spkacCsr.verify()) { JOptionPane.showMessageDialog(frame, res.getString("SignCsrAction.NoVerifySpkacCsr.message"), res.getString("SignCsrAction.SignCsr.Title"), JOptionPane.WARNING_MESSAGE); return; } } else { JOptionPane.showMessageDialog(frame, MessageFormat.format(res.getString("SignCsrAction.FileNotRecognisedType.message"), csrFile), res.getString("SignCsrAction.SignCsr.Title"), JOptionPane.WARNING_MESSAGE); return; } } catch (FileNotFoundException ex) { JOptionPane.showMessageDialog(frame, MessageFormat.format(res.getString("SignCsrAction.NotFile.message"), csrFile), res.getString("SignCsrAction.SignCsr.Title"), JOptionPane.WARNING_MESSAGE); return; } catch (Exception ex) { String problemStr = MessageFormat.format(res.getString("SignCsrAction.NoOpenCsr.Problem"), csrFile.getName()); String[] causes = new String[] { res.getString("SignCsrAction.NotCsr.Cause"), res.getString("SignCsrAction.CorruptedCsr.Cause") }; Problem problem = new Problem(problemStr, causes, ex); DProblem dProblem = new DProblem(frame, res.getString("SignCsrAction.ProblemOpeningCsr.Title"), problem); dProblem.setLocationRelativeTo(frame); dProblem.setVisible(true); return; } X509Certificate[] signingChain = X509CertUtil .orderX509CertChain(X509CertUtil.convertCertificates(certs)); X509Certificate signingCert = signingChain[0]; PublicKey publicKey = null; X500Name subject = null; DSignCsr dSignCsr = null; Provider provider = history.getExplicitProvider(); if (pkcs10Csr != null) { publicKey = new JcaPKCS10CertificationRequest(pkcs10Csr).getPublicKey(); subject = pkcs10Csr.getSubject(); dSignCsr = new DSignCsr(frame, pkcs10Csr, csrFile, privateKey, keyPairType, signingCert, provider); } else { publicKey = spkacCsr.getPublicKey(); subject = spkacCsr.getSubject().getName(); dSignCsr = new DSignCsr(frame, spkacCsr, csrFile, privateKey, keyPairType, signingCert, provider); } dSignCsr.setLocationRelativeTo(frame); dSignCsr.setVisible(true); X509CertificateVersion version = dSignCsr.getVersion(); SignatureType signatureType = dSignCsr.getSignatureType(); Date validityStart = dSignCsr.getValidityStart(); Date validityEnd = dSignCsr.getValidityEnd(); BigInteger serialNumber = dSignCsr.getSerialNumber(); caReplyFile = dSignCsr.getCaReplyFile(); X509ExtensionSet extensions = dSignCsr.getExtensions(); if (version == null) { return; } X500Name issuer = X500NameUtils.x500PrincipalToX500Name(signingCert.getSubjectX500Principal()); // CA Reply is a cert with subject from CSR and issuer from signing cert's subject X509CertificateGenerator generator = new X509CertificateGenerator(version); X509Certificate caReplyCert = generator.generate(subject, issuer, validityStart, validityEnd, publicKey, privateKey, signatureType, serialNumber, extensions, provider); X509Certificate[] caReplyChain = new X509Certificate[signingChain.length + 1]; caReplyChain[0] = caReplyCert; // Add all of the signing chain to the reply System.arraycopy(signingChain, 0, caReplyChain, 1, signingChain.length); byte[] caCertEncoded = X509CertUtil.getCertsEncodedPkcs7(caReplyChain); fos = new FileOutputStream(caReplyFile); fos.write(caCertEncoded); } catch (FileNotFoundException ex) { JOptionPane.showMessageDialog(frame, MessageFormat.format(res.getString("SignJarAction.NoWriteFile.message"), caReplyFile), res.getString("SignCsrAction.SignCsr.Title"), JOptionPane.WARNING_MESSAGE); return; } catch (Exception ex) { DError.displayError(frame, ex); return; } finally { IOUtils.closeQuietly(fos); } JOptionPane.showMessageDialog(frame, res.getString("SignCsrAction.SignCsrSuccessful.message"), res.getString("SignCsrAction.SignCsr.Title"), JOptionPane.INFORMATION_MESSAGE); }
From source file:org.cesecore.keys.util.KeyTools.java
/** * Retrieves the certificate chain from a keystore. * //from w w w . j av a 2 s. c o m * @param keyStore * the keystore, which has been loaded and opened. * @param privateKeyAlias * the alias of the privatekey for which the certchain belongs. * * @return array of Certificate, or null if no certificates are found. */ public static Certificate[] getCertChain(final KeyStore keyStore, final String privateKeyAlias) throws KeyStoreException { if (log.isTraceEnabled()) { log.trace(">getCertChain: alias='" + privateKeyAlias + "'"); } final Certificate[] certchain = keyStore.getCertificateChain(privateKeyAlias); if (certchain == null) { return null; } log.debug("Certchain retrieved from alias '" + privateKeyAlias + "' has length " + certchain.length); if (certchain.length < 1) { log.error("Cannot load certificate chain with alias '" + privateKeyAlias + "' from keystore."); if (log.isTraceEnabled()) { log.trace("<getCertChain: alias='" + privateKeyAlias + "', retlength=" + certchain.length); } return certchain; } else if (certchain.length > 0) { if (CertTools.isSelfSigned(certchain[certchain.length - 1])) { if (log.isDebugEnabled()) { log.debug("Issuer='" + CertTools.getIssuerDN(certchain[certchain.length - 1]) + "'."); log.debug("Subject='" + CertTools.getSubjectDN(certchain[certchain.length - 1]) + "'."); } if (log.isTraceEnabled()) { log.trace("<getCertChain: alias='" + privateKeyAlias + "', retlength=" + certchain.length); } return certchain; } } // If we came here, we have a cert which is not root cert in 'cert' final ArrayList<Certificate> array = new ArrayList<Certificate>(); for (int i = 0; i < certchain.length; i++) { array.add(certchain[i]); } boolean stop = false; while (!stop) { final X509Certificate cert = (X509Certificate) array.get(array.size() - 1); final String ialias = CertTools.getPartFromDN(CertTools.getIssuerDN(cert), "CN"); final Certificate[] chain1 = keyStore.getCertificateChain(ialias); if (chain1 == null) { stop = true; } else { if (log.isDebugEnabled()) { log.debug("Loaded certificate chain with length " + chain1.length + " with alias '" + ialias + "'."); } if (chain1.length == 0) { log.error("No RootCA certificate found!"); stop = true; } for (int j = 0; j < chain1.length; j++) { array.add(chain1[j]); // If one cert is slefsigned, we have found a root certificate, we don't need to go on anymore if (CertTools.isSelfSigned(chain1[j])) { stop = true; } } } } final Certificate[] ret = new Certificate[array.size()]; for (int i = 0; i < ret.length; i++) { ret[i] = array.get(i); if (log.isDebugEnabled()) { log.debug("Issuer='" + CertTools.getIssuerDN(ret[i]) + "'."); log.debug("Subject='" + CertTools.getSubjectDN(ret[i]) + "'."); } } if (log.isTraceEnabled()) { log.trace("<getCertChain: alias='" + privateKeyAlias + "', retlength=" + ret.length); } return ret; }
From source file:AuthSSLProtocolSocketFactory.java
private SSLContext createSSLContext() { try {/* w w w . ja v a 2s . c om*/ KeyManager[] keymanagers = null; TrustManager[] trustmanagers = null; if (this.keystoreUrl != null) { KeyStore keystore = createKeyStore(this.keystoreUrl, this.keystorePassword); Enumeration aliases = keystore.aliases(); while (aliases.hasMoreElements()) { String alias = (String) aliases.nextElement(); Certificate[] certs = keystore.getCertificateChain(alias); if (certs != null) { System.out.println("Certificate chain '" + alias + "':"); for (int c = 0; c < certs.length; c++) { if (certs[c] instanceof X509Certificate) { X509Certificate cert = (X509Certificate) certs[c]; System.out.println(" Certificate " + (c + 1) + ":"); System.out.println(" Subject DN: " + cert.getSubjectDN()); System.out.println(" Signature Algorithm: " + cert.getSigAlgName()); System.out.println(" Valid from: " + cert.getNotBefore()); System.out.println(" Valid until: " + cert.getNotAfter()); System.out.println(" Issuer: " + cert.getIssuerDN()); } } } } keymanagers = createKeyManagers(keystore, this.keystorePassword); } if (this.truststoreUrl != null) { KeyStore keystore = createKeyStore(this.truststoreUrl, this.truststorePassword); Enumeration aliases = keystore.aliases(); while (aliases.hasMoreElements()) { String alias = (String) aliases.nextElement(); System.out.println("Trusted certificate '" + alias + "':"); Certificate trustedcert = keystore.getCertificate(alias); if (trustedcert != null && trustedcert instanceof X509Certificate) { X509Certificate cert = (X509Certificate) trustedcert; System.out.println(" Subject DN: " + cert.getSubjectDN()); System.out.println(" Signature Algorithm: " + cert.getSigAlgName()); System.out.println(" Valid from: " + cert.getNotBefore()); System.out.println(" Valid until: " + cert.getNotAfter()); System.out.println(" Issuer: " + cert.getIssuerDN()); } } trustmanagers = createTrustManagers(keystore); } SSLContext sslcontext = SSLContext.getInstance("SSL"); sslcontext.init(keymanagers, trustmanagers, null); return sslcontext; } catch (NoSuchAlgorithmException e) { e.printStackTrace(); throw new AuthSSLInitializationError("Unsupported algorithm exception: " + e.getMessage()); } catch (KeyStoreException e) { e.printStackTrace(); throw new AuthSSLInitializationError("Keystore exception: " + e.getMessage()); } catch (GeneralSecurityException e) { e.printStackTrace(); throw new AuthSSLInitializationError("Key management exception: " + e.getMessage()); } catch (IOException e) { e.printStackTrace(); throw new AuthSSLInitializationError("I/O error reading keystore/truststore file: " + e.getMessage()); } }
From source file:org.alfresco.extension.countersign.action.executer.PDFSignatureProviderActionExecuter.java
/** * @see org.alfresco.repo.action.executer.ActionExecuterAbstractBase#executeImpl(org.alfresco.service.cmr.repository.NodeRef, * org.alfresco.service.cmr.repository.NodeRef) */// w w w .j a v a 2 s . co m protected void executeImpl(Action ruleAction, NodeRef actionedUponNodeRef) { if (serviceRegistry.getNodeService().exists(actionedUponNodeRef) == false) { // node doesn't exist - can't do anything return; } String location = (String) ruleAction.getParameterValue(PARAM_LOCATION); String geolocation = (String) ruleAction.getParameterValue(PARAM_GEOLOCATION); String reason = (String) ruleAction.getParameterValue(PARAM_REASON); String position = (String) ruleAction.getParameterValue(PARAM_POSITION); String keyPassword = (String) ruleAction.getParameterValue(PARAM_KEY_PASSWORD); String signatureJson = (String) ruleAction.getParameterValue(PARAM_SIGNATURE_JSON); Boolean visible = (Boolean) ruleAction.getParameterValue(PARAM_VISIBLE); Boolean graphic = (Boolean) ruleAction.getParameterValue(PARAM_GRAPHIC); boolean useSignatureField = false; String user = AuthenticationUtil.getRunAsUser(); String positionType = "predefined"; String positionLoc = "center"; JSONObject box; int page = -1; // parse out the position JSON JSONObject positionObj = null; try { positionObj = (JSONObject) parser.parse(position); } catch (ParseException e) { logger.error("Could not parse position JSON from Share"); throw new AlfrescoRuntimeException("Could not parse position JSON from Share"); } // get the page page = Integer.parseInt(String.valueOf(positionObj.get("page"))); // get the positioning type positionType = String.valueOf(positionObj.get("type")); // get the position (field or predefined) positionLoc = String.valueOf(positionObj.get("position")); // get the box (if required) box = (JSONObject) positionObj.get("box"); int width = 350; int height = 75; File tempDir = null; // current date, used for both signing the PDF and creating the // associated signature object Calendar now = Calendar.getInstance(); try { // get the keystore, pk and cert chain SignatureProvider signatureProvider = signatureProviderFactory.getSignatureProvider(user); KeyStore keystore = signatureProvider.getUserKeyStore(keyPassword); PrivateKey key = (PrivateKey) keystore.getKey(alias, keyPassword.toCharArray()); Certificate[] chain = keystore.getCertificateChain(alias); // open original pdf ContentReader pdfReader = getReader(actionedUponNodeRef); PdfReader reader = new PdfReader(pdfReader.getContentInputStream()); // create temp dir to store file File alfTempDir = TempFileProvider.getTempDir(); tempDir = new File(alfTempDir.getPath() + File.separatorChar + actionedUponNodeRef.getId()); tempDir.mkdir(); File file = new File(tempDir, serviceRegistry.getFileFolderService().getFileInfo(actionedUponNodeRef).getName()); OutputStream cos = serviceRegistry.getContentService() .getWriter(actionedUponNodeRef, ContentModel.PROP_CONTENT, true).getContentOutputStream(); PdfStamper stamp = PdfStamper.createSignature(reader, cos, '\0', file, true); PdfSignatureAppearance sap = stamp.getSignatureAppearance(); sap.setCrypto(key, chain, null, PdfSignatureAppearance.SELF_SIGNED); // set reason for signature, location of signer, and date sap.setReason(reason); sap.setLocation(location); sap.setSignDate(now); // get the image for the signature BufferedImage sigImage = SignatureToImage.convertJsonToImage(signatureJson, width, height); // save the signature image back to the signatureProvider signatureProvider.saveSignatureImage(sigImage, signatureJson); if (visible) { //if this is a graphic sig, set the graphic here if (graphic) { sap.setRenderingMode(PdfSignatureAppearance.RenderingMode.GRAPHIC); sap.setSignatureGraphic(Image.getInstance(sigImage, Color.WHITE)); } else { sap.setRenderingMode(PdfSignatureAppearance.RenderingMode.NAME_AND_DESCRIPTION); } // either insert the sig at a defined field or at a defined position / drawn loc if (positionType.equalsIgnoreCase(POSITION_TYPE_PREDEFINED)) { Rectangle pageRect = reader.getPageSizeWithRotation(page); sap.setVisibleSignature(positionBlock(positionLoc, pageRect, width, height), page, null); } else if (positionType.equalsIgnoreCase(POSITION_TYPE_DRAWN)) { Rectangle pageRect = reader.getPageSizeWithRotation(page); sap.setVisibleSignature(positionBlock(pageRect, box), page, null); } else { sap.setVisibleSignature(positionLoc); useSignatureField = true; } } // close the stamp, applying the changes to the PDF stamp.close(); reader.close(); cos.close(); //delete the temp file file.delete(); // apply the "signed" aspect serviceRegistry.getNodeService().addAspect(actionedUponNodeRef, CounterSignSignatureModel.ASPECT_SIGNED, new HashMap<QName, Serializable>()); // create a "signature" node and associate it with the signed doc addSignatureNodeAssociation(actionedUponNodeRef, location, reason, useSignatureField ? positionLoc : "none", now.getTime(), geolocation, page, positionLoc); } catch (IOException e) { throw new AlfrescoRuntimeException(e.getMessage(), e); } catch (ContentIOException e) { throw new AlfrescoRuntimeException(e.getMessage(), e); } catch (DocumentException e) { throw new AlfrescoRuntimeException(e.getMessage(), e); } catch (KeyStoreException e) { throw new AlfrescoRuntimeException(e.getMessage(), e); } catch (UnrecoverableKeyException e) { throw new AlfrescoRuntimeException(e.getMessage(), e); } catch (NoSuchAlgorithmException e) { throw new AlfrescoRuntimeException(e.getMessage(), e); } finally { if (tempDir != null) { try { tempDir.delete(); } catch (Exception ex) { throw new AlfrescoRuntimeException(ex.getMessage(), ex); } } } }
From source file:test.integ.be.e_contract.mycarenet.certra.CertRAClientTest.java
@Before public void setUp() throws Exception { KeyStore keyStore = KeyStore.getInstance("BeID"); BeIDKeyStoreParameter beIDKeyStoreParameter = new BeIDKeyStoreParameter(); beIDKeyStoreParameter.addPPDUName("digipass 870"); beIDKeyStoreParameter.addPPDUName("digipass 875"); beIDKeyStoreParameter.addPPDUName("digipass 920"); keyStore.load(beIDKeyStoreParameter); this.signPrivateKey = (PrivateKey) keyStore.getKey("Signature", null); Certificate[] signCertificates = keyStore.getCertificateChain("Signature"); this.signCertificateChain = new LinkedList<>(); for (Certificate signCertificate : signCertificates) { this.signCertificateChain.add((X509Certificate) signCertificate); }//from w ww . j a v a2 s .c o m this.client = new CertRAClient("https://services-acpt.ehealth.fgov.be/CertRa/v1"); }
From source file:ch.cyberduck.core.ssl.CertificateStoreX509KeyManager.java
@Override public X509Certificate[] getCertificateChain(final String alias) { try {//from w w w .j a v a 2 s.c om final KeyStore store; try { store = this.getKeystore(); } catch (IOException e) { return null; } final List<X509Certificate> result = new ArrayList<X509Certificate>(); final Certificate[] chain = store.getCertificateChain(alias); if (null == chain) { log.warn(String.format("No certificate chain for alias %s", alias)); // Return null if the alias can't be found return null; } else { for (Certificate cert : chain) { if (cert instanceof X509Certificate) { result.add((X509Certificate) cert); } } } if (result.isEmpty()) { log.warn(String.format("No certificate chain for alias %s", alias)); final Certificate cert = store.getCertificate(alias); if (null == cert) { // Return null if the alias can't be found return null; } if (cert instanceof X509Certificate) { final X509Certificate x509 = (X509Certificate) cert; result.add(x509); } } return result.toArray(new X509Certificate[result.size()]); } catch (KeyStoreException e) { log.error(String.format("Keystore not loaded %s", e.getMessage())); } return null; }
From source file:edu.vt.middleware.crypt.KeyStoreCli.java
/** * Exports a certificate or key pair from the keystore. * * @param line Parsed command line arguments container. * * @throws Exception On errors.//from www. ja va 2s.c om */ protected void doExport(final CommandLine line) throws Exception { validateOptions(line); final KeyStore store = readKeyStore(line); final String alias = line.getOptionValue(OPT_ALIAS); boolean wroteData = false; if (line.hasOption(OPT_CERT)) { final File certFile = new File(line.getOptionValue(OPT_CERT)); final Certificate[] certs = store.getCertificateChain(alias); if (certs != null) { if (certFile.getName().endsWith(PEM_SUFFIX)) { CryptWriter.writePemCertificates(certs, certFile); } else { CryptWriter.writeEncodedCertificates(certs, certFile); } } else { // Null cert chain indicates trusted cert entry // with single cert final Certificate cert = store.getCertificate(alias); if (certFile.getName().endsWith(PEM_SUFFIX)) { CryptWriter.writePemCertificate(cert, certFile); } else { CryptWriter.writeEncodedCertificate(cert, certFile); } } System.err.println("Wrote certificate to " + certFile); wroteData = true; } if (line.hasOption(OPT_KEY)) { final File keyFile = new File(line.getOptionValue(OPT_KEY)); final PrivateKey key = (PrivateKey) store.getKey(alias, line.getOptionValue(OPT_PASS).toCharArray()); if (keyFile.getName().endsWith(PEM_SUFFIX)) { CryptWriter.writePemKey(key, null, null, keyFile); } else { CryptWriter.writeEncodedKey(key, keyFile); } System.err.println("Wrote key to " + keyFile); wroteData = true; } if (!wroteData) { System.err.println("No data was written because neither -cert nor -key was specified."); } }
From source file:com.mgmtp.perfload.core.client.web.ssl.LtSSLSocketFactory.java
private SSLContext createSSLContext() { try {//from w w w .j a v a2 s .c om KeyManager[] keymanagers = null; TrustManager[] trustmanagers = null; if (this.keyStoreUrl != null) { KeyStore keystore = createStore(this.keyStoreUrl, this.keyStorePassword, this.keyStoreType); if (log.isDebugEnabled()) { for (Enumeration<String> aliases = keystore.aliases(); aliases.hasMoreElements();) { String alias = aliases.nextElement(); Certificate[] certs = keystore.getCertificateChain(alias); if (certs != null) { log.debug("Certificate chain '{}':", alias); for (int i = 0; i < certs.length; ++i) { if (certs[i] instanceof X509Certificate) { log.debug(" Certificate {}:", i + 1); logCertificate((X509Certificate) certs[i]); } } } } } keymanagers = createKeyManagers(keystore, this.keyStorePassword); } if (this.trustStoreUrl != null) { KeyStore keystore = createStore(this.trustStoreUrl, this.trustStorePassword, this.trustStoreType); if (log.isDebugEnabled()) { for (Enumeration<String> aliases = keystore.aliases(); aliases.hasMoreElements();) { String alias = aliases.nextElement(); log.debug("Trusted certificate '{}':", alias); Certificate trustedcert = keystore.getCertificate(alias); if (trustedcert instanceof X509Certificate) { logCertificate((X509Certificate) trustedcert); } } } trustmanagers = createTrustManagers(keystore); } SSLContext context = SSLContext.getInstance("SSL"); context.init(keymanagers, trustmanagers, null); return context; } catch (NoSuchAlgorithmException e) { throw new LtSSLInitializationException("Unsupported algorithm exception: " + e.getMessage(), e); } catch (KeyStoreException e) { throw new LtSSLInitializationException("Keystore exception: " + e.getMessage(), e); } catch (GeneralSecurityException e) { throw new LtSSLInitializationException("Key management exception: " + e.getMessage(), e); } catch (IOException e) { throw new LtSSLInitializationException( "I/O error reading key store/trust store file: " + e.getMessage(), e); } }
From source file:com.mgmtp.jfunk.web.ssl.JFunkSSLSocketFactory.java
private SSLContext createSSLContext() { try {/*from ww w . ja v a 2 s . co m*/ KeyManager[] keymanagers = null; TrustManager[] trustmanagers = null; if (this.keyStoreUrl != null) { KeyStore keystore = createStore(this.keyStoreUrl, this.keyStorePassword, this.keyStoreType); if (log.isDebugEnabled()) { for (Enumeration<String> aliases = keystore.aliases(); aliases.hasMoreElements();) { String alias = aliases.nextElement(); Certificate[] certs = keystore.getCertificateChain(alias); if (certs != null) { log.debug("Certificate chain '{}':", alias); for (int i = 0; i < certs.length; ++i) { if (certs[i] instanceof X509Certificate) { log.debug(" Certificate {}:", i + 1); logCertificate((X509Certificate) certs[i]); } } } } } keymanagers = createKeyManagers(keystore, this.keyStorePassword); } if (this.trustStoreUrl != null) { KeyStore keystore = createStore(this.trustStoreUrl, this.trustStorePassword, this.trustStoreType); if (log.isDebugEnabled()) { for (Enumeration<String> aliases = keystore.aliases(); aliases.hasMoreElements();) { String alias = aliases.nextElement(); log.debug("Trusted certificate '{}':", alias); Certificate trustedcert = keystore.getCertificate(alias); if (trustedcert instanceof X509Certificate) { logCertificate((X509Certificate) trustedcert); } } } trustmanagers = createTrustManagers(keystore); } SSLContext context = SSLContext.getInstance("SSL"); context.init(keymanagers, trustmanagers, null); return context; } catch (NoSuchAlgorithmException e) { throw new JFunkException("Unsupported algorithm exception: " + e.getMessage(), e); } catch (KeyStoreException e) { throw new JFunkException("Keystore exception: " + e.getMessage(), e); } catch (GeneralSecurityException e) { throw new JFunkException("Key management exception: " + e.getMessage(), e); } catch (IOException e) { throw new JFunkException("I/O error reading key store/trust store file: " + e.getMessage(), e); } }