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:it.cnr.icar.eric.common.security.KeyToolStripped.java
/** * Generate a public/private key pair.// w ww . j a v a 2s. c o m * * @throws Exception */ public static void generateKeyPair(KeyStore keyStore, char[] storePass, String alias, char[] keyPass, String dname, String keyAlg, int validity) throws Exception { int keySize = 1024; if (keyStore.containsAlias(alias)) { MessageFormat messageformat = new MessageFormat("Key pair not generated, alias <alias> already exists"); Object[] aobj = { alias }; throw new Exception(messageformat.format(((Object) (aobj)))); } String sigAlg = null; if (keyAlg.equalsIgnoreCase("DSA")) { sigAlg = "SHA1WithDSA"; } else if (keyAlg.equalsIgnoreCase("RSA")) { sigAlg = "MD5WithRSA"; } else { throw new Exception("Cannot derive signature algorithm"); } //Must specify provider "SunRsaSign" otherwise it gets some weird NSS specific provider //when running in AppServer EE. CertAndKeyGen certandkeygen = new CertAndKeyGen(keyAlg, sigAlg); X500Name x500name; if (dname == null) { throw new Exception("Key pair not generated, dname is null."); } else { x500name = new X500Name(dname); } certandkeygen.generate(keySize); PrivateKey privatekey = certandkeygen.getPrivateKey(); X509Certificate[] ax509certificate = new X509Certificate[1]; ax509certificate[0] = certandkeygen.getSelfCertificate(x500name, validity * 24 * 60 * 60); keyStore.setKeyEntry(alias, privatekey, keyPass, ax509certificate); }
From source file:org.apache.drill.yarn.appMaster.http.WebServer.java
/** * Create an HTTPS connector for given jetty server instance. If the admin has * specified keystore/truststore settings they will be used else a self-signed * certificate is generated and used.//from w w w . j a v a 2 s . c o m * <p> * This is a shameless copy of * {@link org.apache.drill.exec.server.rest.Webserver#createHttpsConnector( )}. * The two should be merged at some point. The primary issue is that the Drill * version is tightly coupled to Drillbit configuration. * * @return Initialized {@link ServerConnector} for HTTPS connections. * @throws Exception */ private ServerConnector createHttpsConnector(Config config) throws Exception { LOG.info("Setting up HTTPS connector for web server"); final SslContextFactory sslContextFactory = new SslContextFactory(); // if (config.hasPath(ExecConstants.HTTP_KEYSTORE_PATH) && // !Strings.isNullOrEmpty(config.getString(ExecConstants.HTTP_KEYSTORE_PATH))) // { // LOG.info("Using configured SSL settings for web server"); // sslContextFactory.setKeyStorePath(config.getString(ExecConstants.HTTP_KEYSTORE_PATH)); // sslContextFactory.setKeyStorePassword(config.getString(ExecConstants.HTTP_KEYSTORE_PASSWORD)); // // // TrustStore and TrustStore password are optional // if (config.hasPath(ExecConstants.HTTP_TRUSTSTORE_PATH)) { // sslContextFactory.setTrustStorePath(config.getString(ExecConstants.HTTP_TRUSTSTORE_PATH)); // if (config.hasPath(ExecConstants.HTTP_TRUSTSTORE_PASSWORD)) { // sslContextFactory.setTrustStorePassword(config.getString(ExecConstants.HTTP_TRUSTSTORE_PASSWORD)); // } // } // } else { LOG.info("Using generated self-signed SSL settings for web server"); final SecureRandom random = new SecureRandom(); // Generate a private-public key pair final KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); keyPairGenerator.initialize(1024, random); final KeyPair keyPair = keyPairGenerator.generateKeyPair(); final DateTime now = DateTime.now(); // Create builder for certificate attributes final X500NameBuilder nameBuilder = new X500NameBuilder(BCStyle.INSTANCE) .addRDN(BCStyle.OU, "Apache Drill (auth-generated)") .addRDN(BCStyle.O, "Apache Software Foundation (auto-generated)").addRDN(BCStyle.CN, "Drill AM"); final Date notBefore = now.minusMinutes(1).toDate(); final Date notAfter = now.plusYears(5).toDate(); final BigInteger serialNumber = new BigInteger(128, random); // Create a certificate valid for 5years from now. final X509v3CertificateBuilder certificateBuilder = new JcaX509v3CertificateBuilder(nameBuilder.build(), // attributes serialNumber, notBefore, notAfter, nameBuilder.build(), keyPair.getPublic()); // Sign the certificate using the private key final ContentSigner contentSigner = new JcaContentSignerBuilder("SHA256WithRSAEncryption") .build(keyPair.getPrivate()); final X509Certificate certificate = new JcaX509CertificateConverter() .getCertificate(certificateBuilder.build(contentSigner)); // Check the validity certificate.checkValidity(now.toDate()); // Make sure the certificate is self-signed. certificate.verify(certificate.getPublicKey()); // Generate a random password for keystore protection final String keyStorePasswd = RandomStringUtils.random(20); final KeyStore keyStore = KeyStore.getInstance("JKS"); keyStore.load(null, null); keyStore.setKeyEntry("DrillAutoGeneratedCert", keyPair.getPrivate(), keyStorePasswd.toCharArray(), new java.security.cert.Certificate[] { certificate }); sslContextFactory.setKeyStore(keyStore); sslContextFactory.setKeyStorePassword(keyStorePasswd); // } final HttpConfiguration httpsConfig = new HttpConfiguration(); httpsConfig.addCustomizer(new SecureRequestCustomizer()); // SSL Connector final ServerConnector sslConnector = new ServerConnector(jettyServer, new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()), new HttpConnectionFactory(httpsConfig)); sslConnector.setPort(config.getInt(DrillOnYarnConfig.HTTP_PORT)); return sslConnector; }
From source file:com.liferay.sync.engine.lan.session.LanSession.java
private static SSLConnectionSocketFactory _getSSLSocketFactory() throws Exception { KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); keyStore.load(null, null);/*from w w w . j ava2 s.co m*/ for (SyncAccount syncAccount : SyncAccountService.findAll()) { if (!syncAccount.isActive() || !syncAccount.isLanEnabled()) { continue; } try { PrivateKey privateKey = LanPEMParserUtil.parsePrivateKey(syncAccount.getLanKey()); if (privateKey == null) { _logger.error("SyncAccount {} missing valid private key", syncAccount.getSyncAccountId()); continue; } X509Certificate x509Certificate = LanPEMParserUtil .parseX509Certificate(syncAccount.getLanCertificate()); if (x509Certificate == null) { _logger.error("SyncAccount {} missing valid certificate", syncAccount.getSyncAccountId()); continue; } keyStore.setCertificateEntry(syncAccount.getLanServerUuid(), x509Certificate); keyStore.setKeyEntry(syncAccount.getLanServerUuid(), privateKey, "".toCharArray(), new Certificate[] { x509Certificate }); } catch (Exception e) { _logger.error(e.getMessage(), e); } } KeyManagerFactory keyManagerFactory = KeyManagerFactory .getInstance(KeyManagerFactory.getDefaultAlgorithm()); keyManagerFactory.init(keyStore, "".toCharArray()); TrustManagerFactory trustManagerFactory = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(keyStore); SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null); return new SNISSLConnectionSocketFactory(sslContext, new NoopHostnameVerifier()); }
From source file:test.unit.be.fedict.eid.applet.service.AppletServiceServletTest.java
private void persistKey(File pkcs12keyStore, PrivateKey privateKey, X509Certificate certificate, char[] keyStorePassword, char[] keyEntryPassword) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException, NoSuchProviderException { KeyStore keyStore = KeyStore.getInstance("pkcs12", BouncyCastleProvider.PROVIDER_NAME); keyStore.load(null, keyStorePassword); LOG.debug("keystore security provider: " + keyStore.getProvider().getName()); keyStore.setKeyEntry("default", privateKey, keyEntryPassword, new Certificate[] { certificate }); FileOutputStream keyStoreOut = new FileOutputStream(pkcs12keyStore); keyStore.store(keyStoreOut, keyStorePassword); keyStoreOut.close();//from w w w .j a v a 2 s .com }
From source file:com.piusvelte.taplock.server.TapLockServer.java
protected static String encryptString(String decStr) { String encStr = null;/* w ww .j av a2 s . c o m*/ KeyStore ks = getKeyStore(); if (ks != null) { SecretKey sk = getSecretKey(ks); if (sk == null) { // create key KeyGenerator kgen = null; try { kgen = KeyGenerator.getInstance("AES"); } catch (NoSuchAlgorithmException e) { writeLog("encryptString: " + e.getMessage()); } if (kgen != null) { int keyLength; try { keyLength = Cipher.getMaxAllowedKeyLength("AES"); } catch (NoSuchAlgorithmException e) { keyLength = 128; writeLog("encryptString: " + e.getMessage()); } kgen.init(keyLength); sk = kgen.generateKey(); // create a keystore try { ks.load(null, sPassphrase.toCharArray()); ks.setKeyEntry(TAP_LOCK, sk, sPassphrase.toCharArray(), null); ks.store(new FileOutputStream(sKeystore), sPassphrase.toCharArray()); } catch (NoSuchAlgorithmException e) { writeLog("encryptString: " + e.getMessage()); } catch (CertificateException e) { writeLog("encryptString: " + e.getMessage()); } catch (IOException e) { writeLog("encryptString: " + e.getMessage()); } catch (KeyStoreException e) { writeLog("encryptString: " + e.getMessage()); } } } if ((sk != null) && (decStr != null)) { Cipher cipher; try { cipher = Cipher.getInstance("AES"); cipher.init(Cipher.ENCRYPT_MODE, sk); return new String(Base64.encodeBase64(cipher.doFinal(decStr.getBytes("UTF-8")))); } catch (NoSuchAlgorithmException e) { writeLog("encryptString: " + e.getMessage()); } catch (NoSuchPaddingException e) { writeLog("encryptString: " + e.getMessage()); } catch (InvalidKeyException e) { writeLog("encryptString: " + e.getMessage()); } catch (IllegalBlockSizeException e) { writeLog("encryptString: " + e.getMessage()); } catch (BadPaddingException e) { writeLog("encryptString: " + e.getMessage()); } catch (UnsupportedEncodingException e) { writeLog("encryptString: " + e.getMessage()); } } } return encStr; }
From source file:org.commonjava.maven.galley.transport.htcli.internal.SSLUtils.java
public static KeyStore readKeyAndCert(final String pemContent, final String keyPass) throws CertificateException, IOException, KeyStoreException, NoSuchAlgorithmException, InvalidKeySpecException { final KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); ks.load(null);//w w w. j a v a2s.c om final CertificateFactory certFactory = CertificateFactory.getInstance("X.509"); final KeyFactory keyFactory = KeyFactory.getInstance("RSA"); final List<String> lines = readLines(pemContent); String currentHeader = null; final StringBuilder current = new StringBuilder(); final Map<String, String> entries = new LinkedHashMap<String, String>(); for (final String line : lines) { if (line == null) { continue; } if (line.startsWith("-----BEGIN")) { currentHeader = line.trim(); current.setLength(0); } else if (line.startsWith("-----END")) { entries.put(currentHeader, current.toString()); } else { current.append(line.trim()); } } final List<Certificate> certs = new ArrayList<Certificate>(); for (int pass = 0; pass < 2; pass++) { for (final Map.Entry<String, String> entry : entries.entrySet()) { final String header = entry.getKey(); final byte[] data = decodeBase64(entry.getValue()); if (pass > 0 && header.contains("BEGIN PRIVATE KEY")) { final KeySpec spec = new PKCS8EncodedKeySpec(data); final PrivateKey key = keyFactory.generatePrivate(spec); ks.setKeyEntry("key", key, keyPass.toCharArray(), certs.toArray(new Certificate[] {})); } else if (pass < 1 && header.contains("BEGIN CERTIFICATE")) { final Certificate c = certFactory.generateCertificate(new ByteArrayInputStream(data)); ks.setCertificateEntry("certificate", c); certs.add(c); } } } return ks; }
From source file:org.guanxi.sp.engine.form.RegisterGuardFormController.java
/** * Creates a JKS keystore and imports the specified certificate chain * * @param ksFileName The full path/name of the keystore to create * @param alias The alias for the certificate entry to create * @param password The password for the keystore and also the private key * @param caBean CABean instance from a call to createSignedCertificateChain *//* w w w . j a v a 2 s .co m*/ private void createKeystoreWithChain(String ksFileName, String alias, String password, CABean caBean) { try { KeyStore ks = KeyStore.getInstance("JKS"); ks.load(null, null); ks.setKeyEntry(alias, caBean.getCSRPrivateKey(), password.toCharArray(), caBean.getChain()); ks.store(new FileOutputStream(ksFileName), password.toCharArray()); } catch (Exception e) { logger.error(e); } }
From source file:io.fabric8.kubernetes.api.KubernetesFactory.java
private void configureClientCert(WebClient webClient) { try (InputStream certInputStream = getInputStreamFromDataOrFile(clientCertData, clientCertFile)) { CertificateFactory certFactory = CertificateFactory.getInstance("X509"); X509Certificate cert = (X509Certificate) certFactory.generateCertificate(certInputStream); InputStream keyInputStream = getInputStreamFromDataOrFile(clientKeyData, clientKeyFile); PEMReader reader = new PEMReader(keyInputStream); RSAPrivateCrtKeySpec keySpec = new PKCS1EncodedKeySpec(reader.getDerBytes()).getKeySpec(); KeyFactory kf = KeyFactory.getInstance(clientKeyAlgo); RSAPrivateKey privKey = (RSAPrivateKey) kf.generatePrivate(keySpec); KeyStore keyStore = KeyStore.getInstance("JKS"); keyStore.load(null);//from w w w . j a v a 2 s . c o m String alias = cert.getSubjectX500Principal().getName(); keyStore.setKeyEntry(alias, privKey, clientKeyPassword, new Certificate[] { cert }); KeyManagerFactory keyManagerFactory = KeyManagerFactory .getInstance(KeyManagerFactory.getDefaultAlgorithm()); keyManagerFactory.init(keyStore, clientKeyPassword); HTTPConduit conduit = WebClient.getConfig(webClient).getHttpConduit(); TLSClientParameters params = conduit.getTlsClientParameters(); if (params == null) { params = new TLSClientParameters(); conduit.setTlsClientParameters(params); } KeyManager[] existingKeyManagers = params.getKeyManagers(); KeyManager[] keyManagers; if (existingKeyManagers == null || ArrayUtils.isEmpty(existingKeyManagers)) { keyManagers = keyManagerFactory.getKeyManagers(); } else { keyManagers = (KeyManager[]) ArrayUtils.addAll(existingKeyManagers, keyManagerFactory.getKeyManagers()); } params.setKeyManagers(keyManagers); } catch (Exception e) { log.error("Could not create key manager for " + clientCertFile + " (" + clientKeyFile + ")", e); } }
From source file:test.integ.be.agiv.security.IPSTSTest.java
private void persistKey(File pkcs12keyStore, PrivateKey privateKey, X509Certificate certificate, char[] keyStorePassword, char[] keyEntryPassword) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException { KeyStore keyStore = KeyStore.getInstance("pkcs12"); keyStore.load(null, keyStorePassword); keyStore.setKeyEntry("default", privateKey, keyEntryPassword, new Certificate[] { certificate }); FileOutputStream keyStoreOut = new FileOutputStream(pkcs12keyStore); keyStore.store(keyStoreOut, keyStorePassword); keyStoreOut.close();//from w w w . ja v a2s .c o m }
From source file:org.kuali.kra.s2s.service.impl.GrantsGovConnectorServiceImpl.java
/** * This method is to confgiure KeyStore and Truststore for Grants.Gov webservice client * @param tlsConfig//from w w w. jav a 2s. co m * @param alias * @param mulitCampusEnabled * @throws S2SException */ protected void configureKeyStoreAndTrustStore(TLSClientParameters tlsConfig, String alias, boolean mulitCampusEnabled) throws S2SException { KeyStore keyStore = S2SCertificateReader.getKeyStore(); KeyManagerFactory keyManagerFactory; try { keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); if (alias != null && mulitCampusEnabled) { KeyStore keyStoreAlias; keyStoreAlias = KeyStore.getInstance(JKS_TYPE); Certificate[] certificates = keyStore.getCertificateChain(alias); Key key = keyStore.getKey(alias, s2SUtilService.getProperty(KEYSTORE_PASSWORD).toCharArray()); keyStoreAlias.load(null, null); keyStoreAlias.setKeyEntry(alias, key, s2SUtilService.getProperty(KEYSTORE_PASSWORD).toCharArray(), certificates); keyManagerFactory.init(keyStoreAlias, s2SUtilService.getProperty(KEYSTORE_PASSWORD).toCharArray()); } else { keyManagerFactory.init(keyStore, s2SUtilService.getProperty(KEYSTORE_PASSWORD).toCharArray()); } KeyManager[] km = keyManagerFactory.getKeyManagers(); tlsConfig.setKeyManagers(km); KeyStore trustStore = S2SCertificateReader.getTrustStore(); TrustManagerFactory trustManagerFactory = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(trustStore); TrustManager[] tm = trustManagerFactory.getTrustManagers(); tlsConfig.setTrustManagers(tm); } catch (NoSuchAlgorithmException e) { LOG.error(e); throw new S2SException(KeyConstants.ERROR_KEYSTORE_CONFIG, e.getMessage()); } catch (KeyStoreException e) { LOG.error(e); throw new S2SException(KeyConstants.ERROR_KEYSTORE_CONFIG, e.getMessage()); } catch (UnrecoverableKeyException e) { LOG.error(e); throw new S2SException(KeyConstants.ERROR_KEYSTORE_CONFIG, e.getMessage()); } catch (CertificateException e) { LOG.error(e); throw new S2SException(KeyConstants.ERROR_KEYSTORE_CONFIG, e.getMessage()); } catch (IOException e) { LOG.error(e); throw new S2SException(KeyConstants.ERROR_KEYSTORE_CONFIG, e.getMessage()); } }