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:com.shekhargulati.reactivex.docker.client.ssl.DockerCertificates.java
private DockerCertificates(final Builder builder) throws DockerCertificateException { if ((builder.caCertPath == null) || (builder.clientCertPath == null) || (builder.clientKeyPath == null)) { throw new DockerCertificateException( "caCertPath, clientCertPath, and clientKeyPath must all be specified"); }// w ww. j a v a 2 s .com try { final CertificateFactory cf = CertificateFactory.getInstance("X.509"); final Certificate caCert = cf.generateCertificate(Files.newInputStream(builder.caCertPath)); final Certificate clientCert = cf.generateCertificate(Files.newInputStream(builder.clientCertPath)); final PEMKeyPair clientKeyPair = (PEMKeyPair) new PEMParser( Files.newBufferedReader(builder.clientKeyPath, Charset.defaultCharset())).readObject(); final PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec( clientKeyPair.getPrivateKeyInfo().getEncoded()); final KeyFactory kf = KeyFactory.getInstance("RSA"); final PrivateKey clientKey = kf.generatePrivate(spec); final KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(null, null); trustStore.setEntry("ca", new KeyStore.TrustedCertificateEntry(caCert), null); final KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); keyStore.load(null, KEY_STORE_PASSWORD); keyStore.setCertificateEntry("client", clientCert); keyStore.setKeyEntry("key", clientKey, KEY_STORE_PASSWORD, new Certificate[] { clientCert }); this.sslContext = SSLContexts.custom().loadTrustMaterial(trustStore) .loadKeyMaterial(keyStore, KEY_STORE_PASSWORD).useTLS().build(); } catch (CertificateException | IOException | NoSuchAlgorithmException | InvalidKeySpecException | KeyStoreException | UnrecoverableKeyException | KeyManagementException e) { throw new DockerCertificateException(e); } }
From source file:com.github.jmkgreen.keystore.mongo.KeyStoreRest.java
@GET @Path("create-new-key") public void createNewKey(@QueryParam("keystoreName") String keystoreName, @QueryParam("keystorePassword") String password, @QueryParam("keyName") String keyName, @QueryParam("keyPassword") String keyPassword) throws CertificateException, IOException, KeyStoreException, NoSuchAlgorithmException { KeyStore store = keyStoreRepository.load(keystoreName, "JCEKS", password); LOG.info("Creating a new key within a store currently holding " + store.size() + " keys."); AesCipherService cipherService = new AesCipherService(); Key key = cipherService.generateNewKey(256); store.setKeyEntry(keyName, key, keyPassword.toCharArray(), null); keyStoreRepository.createOrUpdate(keystoreName, password.toCharArray(), store); LOG.info("Stored Key within a KeyStore currently holding " + store.size() + " keys."); }
From source file:com.shekhargulati.reactivex.rxokhttp.SslCertificates.java
private SslCertificates(final Builder builder) throws SslCertificateException { if ((builder.caCertPath == null) || (builder.clientCertPath == null) || (builder.clientKeyPath == null)) { throw new SslCertificateException( "caCertPath, clientCertPath, and clientKeyPath must all be specified"); }//from ww w. j ava2s . c om try { final CertificateFactory cf = CertificateFactory.getInstance("X.509"); final Certificate caCert = cf.generateCertificate(Files.newInputStream(builder.caCertPath)); final Certificate clientCert = cf.generateCertificate(Files.newInputStream(builder.clientCertPath)); final PEMKeyPair clientKeyPair = (PEMKeyPair) new PEMParser( Files.newBufferedReader(builder.clientKeyPath, Charset.defaultCharset())).readObject(); final PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec( clientKeyPair.getPrivateKeyInfo().getEncoded()); final KeyFactory kf = KeyFactory.getInstance("RSA"); final PrivateKey clientKey = kf.generatePrivate(spec); final KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(null, null); trustStore.setEntry("ca", new KeyStore.TrustedCertificateEntry(caCert), null); final KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); keyStore.load(null, KEY_STORE_PASSWORD); keyStore.setCertificateEntry("client", clientCert); keyStore.setKeyEntry("key", clientKey, KEY_STORE_PASSWORD, new Certificate[] { clientCert }); this.sslContext = SSLContexts.custom().loadTrustMaterial(trustStore) .loadKeyMaterial(keyStore, KEY_STORE_PASSWORD).useTLS().build(); } catch (java.security.cert.CertificateException | IOException | NoSuchAlgorithmException | InvalidKeySpecException | KeyStoreException | UnrecoverableKeyException | KeyManagementException e) { throw new SslCertificateException(e); } }
From source file:com.adito.keystore.actions.ShowKeyStoreDispatchAction.java
/** * @param mapping/*from w w w .j a v a 2s .c o m*/ * @param form * @param request * @param response * @return ActionForward * @throws Exception */ public ActionForward exportPrivate(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { String sel = ((ShowKeyStoreForm) form).getSelectedItem(); KeyStore systemClientStore = ((ShowKeyStoreForm) form).getSelectedKeyStore().getKeyStore(); FileDownloadPageInterceptListener l = (FileDownloadPageInterceptListener) CoreUtil .getPageInterceptListenerById(request.getSession(), "fileDownload"); if (l == null) { l = new FileDownloadPageInterceptListener(); CoreUtil.addPageInterceptListener(request.getSession(), l); } File clientCertFile = new File(CoreUtil.getTempDownloadDirectory(getSessionInfo(request)), sel + ".p12"); FileOutputStream out = new FileOutputStream(clientCertFile); char[] password = ((ShowKeyStoreForm) form).getSelectedKeyStore().getKeyStorePassword().toCharArray(); if (systemClientStore.isKeyEntry(sel)) { PrivateKey keypair = ((ShowKeyStoreForm) form).getSelectedKeyStore().getPrivateKey(sel, password); KeyStore userStore = KeyStore.getInstance("PKCS12", "BC"); userStore.load(null, null); userStore.setKeyEntry(sel, keypair, ((ShowKeyStoreForm) form).getPassword().toCharArray(), ((ShowKeyStoreForm) form).getSelectedKeyStore().getCertificateChain(sel)); userStore.store(out, ((ShowKeyStoreForm) form).getPassword().toCharArray()); out.close(); } l.addDownload(new CSRDownload(clientCertFile, clientCertFile.getName(), "application/octet-stream", mapping.findForward("success"), "exportPrivateKey.message", "keystore", sel)); return mapping.findForward("success"); }
From source file:org.ejbca.util.keystore.KeyTools.java
/** * Creates JKS-file that can be used with JDK. The alias for the private key is set to * 'privateKey' and the private key password is null. * * @param alias the alias used for the key entry * @param privKey RSA private key/*w w w .ja v a 2s . c om*/ * @param password user's password * @param cert user certificate * @param cachain CA-certificate chain or null if only one cert in chain, in that case use * 'cert'. * * @return KeyStore containing JKS-keystore * * @exception Exception if input parameters are not OK or certificate generation fails */ public static KeyStore createJKS(final String alias, final PrivateKey privKey, final String password, final X509Certificate cert, final Certificate[] cachain) throws Exception { if (log.isTraceEnabled()) { log.trace(">createJKS: alias=" + alias + ", privKey, cert=" + CertTools.getSubjectDN(cert) + ", cachain.length=" + ((cachain == null) ? 0 : cachain.length)); } final String caAlias = "cacert"; // Certificate chain if (cert == null) { throw new IllegalArgumentException("Parameter cert cannot be null."); } int len = 1; if (cachain != null) { len += cachain.length; } final Certificate[] chain = new Certificate[len]; chain[0] = cert; if (cachain != null) { for (int i = 0; i < cachain.length; i++) { chain[i + 1] = cachain[i]; } } // store the key and the certificate chain final KeyStore store = KeyStore.getInstance("JKS"); store.load(null, null); // First load the key entry final X509Certificate[] usercert = new X509Certificate[1]; usercert[0] = cert; store.setKeyEntry(alias, privKey, password.toCharArray(), usercert); // Add the root cert as trusted if (cachain != null) { if (!CertTools.isSelfSigned((X509Certificate) cachain[cachain.length - 1])) { throw new IllegalArgumentException("Root cert is not self-signed."); } store.setCertificateEntry(caAlias, cachain[cachain.length - 1]); } // Set the complete chain log.debug("Storing cert chain of length " + chain.length); store.setKeyEntry(alias, privKey, password.toCharArray(), chain); if (log.isTraceEnabled()) { log.trace("<createJKS: alias=" + alias + ", privKey, cert=" + CertTools.getSubjectDN(cert) + ", cachain.length=" + ((cachain == null) ? 0 : cachain.length)); } return store; }
From source file:org.objectweb.proactive.extensions.ssl.KeyStoreCreator.java
/** * Create a keystore with a certificate/*from w ww . j av a 2 s .co m*/ */ private boolean create(String keyStore) { try { // Create a certificate CertificateGenerator gen = new CertificateGenerator(); KeyPair pair = gen.generateRSAKeyPair(); X509Certificate cert = gen.generateCertificate(SslHelpers.DEFAULT_SUBJET_DN, pair); // Create the keystore KeyStore ks = KeyStore.getInstance("PKCS12", SslHelpers.BC_NAME); ks.load(null, null); ks.setKeyEntry(SslHelpers.DEFAULT_SUBJET_DN, pair.getPrivate(), SslHelpers.DEFAULT_KS_PASSWD.toCharArray(), new X509Certificate[] { cert }); // Write the keystore FileOutputStream fos = new FileOutputStream(new File(keyStore)); ks.store(fos, SslHelpers.DEFAULT_KS_PASSWD.toCharArray()); fos.close(); return true; } catch (Exception e) { System.err.println("Failed to create the keystore " + keyStore + ": " + e); return false; } }
From source file:edu.vt.alerts.android.library.tasks.RegistrationTask.java
private KeyStore createKeyStore(KeyPair keyPair, HttpResponse response) throws Exception { Log.i("registration", "Got status from registration server: " + response.getStatusLine()); HttpEntity entity = response.getEntity(); byte[] contents = getBytes(entity.getContent()); Collection<?> certs = extractCerts(contents); Certificate[] certificates = new Certificate[certs.size()]; Log.i("registration", "Extracted out " + certs.size() + " certs"); CertificateFactory certFactory = CertificateFactory.getInstance("X.509"); Iterator<?> it = certs.iterator(); int i = 0;/*www . j a v a2 s . com*/ while (it.hasNext()) { byte[] encoded = ((X509CertificateHolder) it.next()).getEncoded(); certificates[i++] = (X509Certificate) certFactory .generateCertificate(new ByteArrayInputStream(encoded)); } Log.d("registration", "Creating local keystore"); KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); keyStore.load(null, null); keyStore.setKeyEntry("Cert", keyPair.getPrivate(), "changeit".toCharArray(), certificates); return keyStore; }
From source file:org.opendaylight.aaa.cert.impl.ODLKeyTool.java
public boolean createKeyStoreWithSelfSignCert(final String keyStoreName, final String keyStorePwd, final String dName, final String keyAlias, final int validity) { try {//from www .j a va 2 s . c o m final KeyPairGenerator keyPairGenerator = KeyPairGenerator .getInstance(KeyStoreConstant.DEFAULT_KEY_ALG); keyPairGenerator.initialize(KeyStoreConstant.DEFAULT_KEY_SIZE); final KeyPair keyPair = keyPairGenerator.generateKeyPair(); final X509V3CertificateGenerator x509V3CertGen = new X509V3CertificateGenerator(); x509V3CertGen.setSerialNumber(getSecureRandomeInt()); x509V3CertGen.setIssuerDN(new X509Principal(dName)); x509V3CertGen.setNotBefore(new Date(System.currentTimeMillis())); x509V3CertGen .setNotAfter(new Date(System.currentTimeMillis() + (KeyStoreConstant.DAY_TIME * validity))); x509V3CertGen.setSubjectDN(new X509Principal(dName)); x509V3CertGen.setPublicKey(keyPair.getPublic()); x509V3CertGen.setSignatureAlgorithm(KeyStoreConstant.DEFAULT_SIGN_ALG); final X509Certificate x509Cert = x509V3CertGen.generateX509Certificate(keyPair.getPrivate()); final KeyStore ctlKeyStore = KeyStore.getInstance("JKS"); ctlKeyStore.load(null, keyStorePwd.toCharArray()); ctlKeyStore.setKeyEntry(keyAlias, keyPair.getPrivate(), keyStorePwd.toCharArray(), new java.security.cert.Certificate[] { x509Cert }); final FileOutputStream fOutputStream = new FileOutputStream(workingDir + keyStoreName); ctlKeyStore.store(fOutputStream, keyStorePwd.toCharArray()); LOG.info("{} is created", keyStoreName); return true; } catch (NoSuchAlgorithmException | InvalidKeyException | SecurityException | SignatureException | KeyStoreException | CertificateException | IOException e) { LOG.error("Fatal error creating key", e); return false; } }
From source file:com.aaasec.sigserv.cssigapp.KeyStoreFactory.java
/** * Add the private key and the certificate chain to the key store. *///w w w.jav a 2 s .c o m public void addToKeyStore(KeyPair keyPair, X509Certificate[] chain, String alias, KeyStore key_store, char[] KS_PASSWORD) throws KeyStoreException { key_store.setKeyEntry(alias, keyPair.getPrivate(), KS_PASSWORD, chain); }
From source file:org.opendaylight.aaa.cert.impl.ODLMdsalKeyTool.java
public KeyStore createKeyStoreWithSelfSignCert(final String keyStoreName, final String keyStorePwd, final String dName, final String keyAlias, final int validity, final String keyAlg, final int keySize, final String signAlg) { try {//from w ww .j av a 2s .c o m final KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(keyAlg); keyPairGenerator.initialize(keySize); final KeyPair keyPair = keyPairGenerator.generateKeyPair(); final X509V3CertificateGenerator x509V3CertGen = new X509V3CertificateGenerator(); x509V3CertGen.setSerialNumber(getSecureRandomeInt()); x509V3CertGen.setIssuerDN(new X509Principal(dName)); x509V3CertGen.setNotBefore(new Date(System.currentTimeMillis())); x509V3CertGen .setNotAfter(new Date(System.currentTimeMillis() + (KeyStoreConstant.DAY_TIME * validity))); x509V3CertGen.setSubjectDN(new X509Principal(dName)); x509V3CertGen.setPublicKey(keyPair.getPublic()); x509V3CertGen.setSignatureAlgorithm(signAlg); final X509Certificate x509Cert = x509V3CertGen.generateX509Certificate(keyPair.getPrivate()); final KeyStore ctlKeyStore = KeyStore.getInstance("JKS"); ctlKeyStore.load(null, keyStorePwd.toCharArray()); ctlKeyStore.setKeyEntry(keyAlias, keyPair.getPrivate(), keyStorePwd.toCharArray(), new java.security.cert.Certificate[] { x509Cert }); LOG.info("{} is created", keyStoreName); return ctlKeyStore; } catch (final NoSuchAlgorithmException | InvalidKeyException | SecurityException | SignatureException | KeyStoreException | CertificateException | IOException e) { LOG.error("Fatal error creating keystore", e); return null; } }