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.aqnote.shared.cryptology.cert.util.KeyStoreUtil.java
public static KeyStore readPKCS12KeyStore(String alias, Certificate[] chain, KeyPair keyPair, char[] pwd) throws Exception { PKCS12SafeBagBuilder BagBuilder = new JcaPKCS12SafeBagBuilder((X509Certificate) chain[0]); BagBuilder.addBagAttribute(PKCS12SafeBag.friendlyNameAttribute, new DERBMPString(alias)); SubjectKeyIdentifier pubKeyId = new JcaX509ExtensionUtils().createSubjectKeyIdentifier(keyPair.getPublic()); BagBuilder.addBagAttribute(PKCS12SafeBag.localKeyIdAttribute, pubKeyId); KeyStore store = KeyStore.getInstance(KEY_STORE_TYPE, JCE_PROVIDER); store.load(null, null);//from w ww . ja v a2 s. co m store.setKeyEntry(alias, keyPair.getPrivate(), pwd, chain); return store; }
From source file:co.cask.cdap.security.tools.KeyStores.java
/** * Create a Java key store with a stored self-signed certificate. * @return Java keystore which has a self signed X.509 certificate *//*from www . j a va 2s .com*/ public static KeyStore generatedCertKeyStore(SConfiguration sConf, String password) { try { KeyPairGenerator keyGen = KeyPairGenerator.getInstance(KEY_PAIR_ALGORITHM); SecureRandom random = SecureRandom.getInstance(SECURE_RANDOM_ALGORITHM, SECURE_RANDOM_PROVIDER); keyGen.initialize(KEY_SIZE, random); // generate a key pair KeyPair pair = keyGen.generateKeyPair(); int validity = sConf.getInt(Constants.Security.SSL.CERT_VALIDITY, VALIDITY); X509Certificate cert = getCertificate(DISTINGUISHED_NAME, pair, validity, SIGNATURE_ALGORITHM); KeyStore keyStore = KeyStore.getInstance(SSL_KEYSTORE_TYPE); keyStore.load(null, password.toCharArray()); keyStore.setKeyEntry(CERT_ALIAS, pair.getPrivate(), password.toCharArray(), new java.security.cert.Certificate[] { cert }); return keyStore; } catch (Exception e) { throw new RuntimeException( "SSL is enabled but a key store file could not be created. A keystore is required " + "for SSL to be used.", e); } }
From source file:com.cloudbees.tftwoway.Client.java
public static KeyManager[] getKeyManager() throws Exception { KeyManagerFactory keyManagerFactory = KeyManagerFactory .getInstance(KeyManagerFactory.getDefaultAlgorithm()); KeyStore store = KeyStore.getInstance("JKS"); PrivateKey clientKey = loadRSAKey(PRIVATE_KEY); X509Certificate clientCert = loadX509Key(CERTIFICATE); store.load(null);// w w w . j av a 2 s. com store.setKeyEntry("key", clientKey, "123123".toCharArray(), new Certificate[] { clientCert }); keyManagerFactory.init(store, "123123".toCharArray()); return keyManagerFactory.getKeyManagers(); }
From source file:io.vertx.config.vault.utils.Certificates.java
/** * Constructs a Java truststore in JKS format, containing the Vault server certificate generated by * {@link #createVaultCertAndKey()}, so that Vault clients configured with this JKS will trust that * certificate.// www . jav a 2 s. c om */ public static void createClientCertAndKey() throws Exception { if (SSL_DIRECTORY.isDirectory() && CLIENT_CERT_PEMFILE.isFile()) { return; } // Store the Vault's server certificate as a trusted cert in the truststore final KeyStore trustStore = KeyStore.getInstance("jks"); trustStore.load(null); trustStore.setCertificateEntry("cert", vaultCertificate); try (final FileOutputStream keystoreOutputStream = new FileOutputStream(CLIENT_TRUSTSTORE)) { trustStore.store(keystoreOutputStream, "password".toCharArray()); } // Generate a client certificate, and store it in a Java keystore final KeyPair keyPair = generateKeyPair(); final X509Certificate clientCertificate = generateCert(keyPair, "C=AU, O=The Legion of the Bouncy Castle, OU=Client Certificate, CN=localhost"); final KeyStore keyStore = KeyStore.getInstance("jks"); keyStore.load(null); keyStore.setKeyEntry("privatekey", keyPair.getPrivate(), "password".toCharArray(), new java.security.cert.Certificate[] { clientCertificate }); keyStore.setCertificateEntry("cert", clientCertificate); try (final FileOutputStream keystoreOutputStream = new FileOutputStream(CLIENT_KEYSTORE)) { keyStore.store(keystoreOutputStream, "password".toCharArray()); } // Also write the client certificate to a PEM file, so it can be registered with Vault writeCertToPem(clientCertificate, CLIENT_CERT_PEMFILE); writePrivateKeyToPem(keyPair.getPrivate(), CLIENT_PRIVATE_KEY_PEMFILE); }
From source file:com.oneis.common.utils.SSLCertificates.java
public static SSLContext load(String keysDirectory, String certsName, String clientCAName, boolean quiet) throws Exception { // For some indiciation of what's going on early in the boot process if (!quiet) { System.out.println("Loading " + certsName + " SSL certificates from " + keysDirectory); }/*from w ww .ja va 2 s . c o m*/ // Get filenames String keyPathname = keysDirectory + "/" + certsName + ".key"; String certPathname = keysDirectory + "/" + certsName + ".crt"; final String intermediateCertPathnameBase = keysDirectory + "/" + certsName + "-intermediate"; String clientCAPathname = null; if (clientCAName != null) { clientCAPathname = keysDirectory + "/" + clientCAName + ".crt"; } if (!new File(keyPathname).exists()) { System.out.println("Doesn't exist: " + keyPathname); return null; } if (!new File(certPathname).exists()) { System.out.println("Doesn't exist: " + certPathname); return null; } if (clientCAPathname != null) { if (!new File(clientCAPathname).exists()) { System.out.println("Doesn't exist: " + clientCAPathname); return null; } } char[] nullPassword = {}; PrivateKey privateKey = readPEMPrivateKey(keyPathname); CertificateFactory cf = CertificateFactory.getInstance("X.509"); // Server certificate ArrayList<java.security.cert.Certificate> certList = new ArrayList<java.security.cert.Certificate>(4); java.security.cert.Certificate cert = cf.generateCertificate(readPEM(certPathname)); certList.add(cert); // Optional intermediate certificates int intermediateCounter = 1; while (true) { String intermediateCertPathname = intermediateCertPathnameBase; if (intermediateCounter != 1) { intermediateCertPathname += "-" + intermediateCounter; } intermediateCounter++; intermediateCertPathname += ".crt"; if (new File(intermediateCertPathname).exists()) { certList.add(cf.generateCertificate(readPEM(intermediateCertPathname))); } else { // End of cert list break; } } // Optional client CA certificate java.security.cert.Certificate clientCACert = null; if (clientCAPathname != null) { clientCACert = cf.generateCertificate(readPEM(clientCAPathname)); } if (clientCAName != null && clientCACert == null) { throw new RuntimeException("Logic error, failed to load client CA cert when required"); } KeyStore ks = KeyStore.getInstance("JKS", "SUN"); ks.load(null, nullPassword); ks.setKeyEntry("ONEIS", (Key) privateKey, "".toCharArray(), certList.toArray(new java.security.cert.Certificate[certList.size()])); if (clientCACert != null) { KeyStore.TrustedCertificateEntry tce = new KeyStore.TrustedCertificateEntry(clientCACert); ks.setEntry("CLIENTCA", tce, null); } // Generate some random Java API stuff, just for entertainment KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); kmf.init(ks, nullPassword); TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509"); tmf.init(ks); SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); if (!quiet) { System.out.println(" - server cert chain length " + certList.size() + (clientCACert != null ? ", requires client cert" : ", public server")); } return sslContext; }
From source file:com.cloud.utils.security.CertificateHelper.java
public static KeyStore buildKeystore(String alias, String cert, String privateKey, String storePassword) throws KeyStoreException, CertificateException, NoSuchAlgorithmException, InvalidKeySpecException, IOException {/*from www . j av a 2s . com*/ KeyStore ks = KeyStore.getInstance("JKS"); ks.load(null, storePassword != null ? storePassword.toCharArray() : null); Certificate[] certs = new Certificate[1]; certs[0] = buildCertificate(cert); ks.setKeyEntry(alias, buildPrivateKey(privateKey), storePassword != null ? storePassword.toCharArray() : null, certs); return ks; }
From source file:io.fabric8.utils.cxf.WebClients.java
public static KeyStore createKeyStore(String clientCertData, File clientCertFile, String clientKeyData, File clientKeyFile, String clientKeyAlgo, char[] clientKeyPassword) throws Exception { 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);// w w w . j av a 2s . c o m String alias = cert.getSubjectX500Principal().getName(); keyStore.setKeyEntry(alias, privKey, clientKeyPassword, new Certificate[] { cert }); return keyStore; } }
From source file:org.zaproxy.zap.extension.dynssl.SslCertificateUtils.java
/** * Code c/o http://stackoverflow.com/questions/12501117/programmatically-obtain-keystore-from-pem * @param pemFile/*from w w w .jav a 2s . c om*/ * @return * @throws IOException * @throws CertificateException * @throws InvalidKeySpecException * @throws NoSuchAlgorithmException * @throws KeyStoreException */ public static KeyStore pem2Keystore(File pemFile) throws IOException, CertificateException, InvalidKeySpecException, NoSuchAlgorithmException, KeyStoreException { byte[] certAndKey = FileUtils.readFileToByteArray(pemFile); byte[] certBytes = parseDERFromPEM(certAndKey, "-----BEGIN CERTIFICATE-----", "-----END CERTIFICATE-----"); byte[] keyBytes = parseDERFromPEM(certAndKey, "-----BEGIN PRIVATE KEY-----", "-----END PRIVATE KEY-----"); X509Certificate cert = generateCertificateFromDER(certBytes); RSAPrivateKey key = generatePrivateKeyFromDER(keyBytes); KeyStore keystore = KeyStore.getInstance("JKS"); keystore.load(null); keystore.setCertificateEntry("cert-alias", cert); keystore.setKeyEntry(SslCertificateService.ZAPROXY_JKS_ALIAS, key, SslCertificateService.PASSPHRASE, new Certificate[] { cert }); return keystore; }
From source file:test.SAMLAttributeQueryExample.java
/** * Build the HTTP client./* w ww .ja v a 2s .c o m*/ * * @param idpCertificateFile path to idp certificate file * @param clientPrivateKeyFile path to client private key file * @param clientCertificateFile path to client certificate file * @return the HTTP client * @throws Exception if an error occurs */ @Nonnull public static HttpClient buildHttpClient(@Nonnull final String idpCertificateFile, @Nonnull final String clientPrivateKeyFile, @Nonnull final String clientCertificateFile) throws Exception { X509Certificate idpCert = CertUtil.readCertificate(idpCertificateFile); KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(null, null); trustStore.setCertificateEntry("idp", idpCert); PrivateKey clientPrivateKey = KeyPairUtil.readPrivateKey(clientPrivateKeyFile); X509Certificate clientCert = CertUtil.readCertificate(clientCertificateFile); KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); keyStore.load(null, null); keyStore.setKeyEntry("me", clientPrivateKey, "secret".toCharArray(), new Certificate[] { clientCert }); SSLContextBuilder sslContextBuilder = SSLContexts.custom(); sslContextBuilder.loadTrustMaterial(trustStore); sslContextBuilder.loadKeyMaterial(keyStore, "secret".toCharArray()); SSLContext sslcontext = sslContextBuilder.build(); CloseableHttpClient httpClient = HttpClients.custom().setSslcontext(sslcontext).build(); return httpClient; }
From source file:net.link.util.test.pkix.PkiTestUtils.java
/** * Persist the given private key and corresponding certificate to a keystore file. * * @param pkcs12keyStore The file of the keystore to write the key material to. * @param keyStoreType The type of the key store format to use. * @param privateKey The private key to persist. * @param certificate The X509 certificate corresponding with the private key. * @param keyStorePassword The keystore password. * @param keyEntryPassword The keyentry password. *///w ww . j a v a 2s . c o m public static KeyStore persistInKeyStore(File pkcs12keyStore, String keyStoreType, PrivateKey privateKey, Certificate certificate, String keyStorePassword, String keyEntryPassword) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException { KeyStore keyStore = KeyStore.getInstance(keyStoreType); keyStore.load(null, keyStorePassword.toCharArray()); keyStore.setKeyEntry(DEFAULT_ALIAS, privateKey, keyEntryPassword.toCharArray(), new Certificate[] { certificate }); FileOutputStream keyStoreOut = new FileOutputStream(pkcs12keyStore); try { keyStore.store(keyStoreOut, keyStorePassword.toCharArray()); } finally { keyStoreOut.close(); } return keyStore; }