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:org.jboss.as.test.integration.security.common.CoreUtils.java
private static void createKeyStoreTrustStore(KeyStore keyStore, KeyStore trustStore, String DN, String alias) throws Exception { X500Principal principal = new X500Principal(DN); SelfSignedX509CertificateAndSigningKey selfSignedX509CertificateAndSigningKey = SelfSignedX509CertificateAndSigningKey .builder().setKeyAlgorithmName("RSA").setSignatureAlgorithmName("SHA256withRSA").setDn(principal) .setKeySize(1024).build();/*ww w .j a va 2s . c o m*/ X509Certificate certificate = selfSignedX509CertificateAndSigningKey.getSelfSignedCertificate(); keyStore.setKeyEntry(alias, selfSignedX509CertificateAndSigningKey.getSigningKey(), KEYSTORE_CREATION_PASSWORD, new X509Certificate[] { certificate }); if (trustStore != null) trustStore.setCertificateEntry(alias, certificate); }
From source file:org.kse.gui.actions.ExportKeyPairAction.java
private void exportAsPkcs12(File exportFile, String alias, PrivateKey privateKey, Certificate[] certificates, Password exportPassword) throws CryptoException, IOException, KeyStoreException { KeyStore pkcs12 = KeyStoreUtil.create(KeyStoreType.PKCS12); certificates = X509CertUtil.orderX509CertChain(X509CertUtil.convertCertificates(certificates)); pkcs12.setKeyEntry(alias, privateKey, exportPassword.toCharArray(), certificates); KeyStoreUtil.save(pkcs12, exportFile, exportPassword); }
From source file:mitm.common.tools.CreateCA.java
public void generateCA(String password, File p12File) throws Exception { KeyStore keyStore = securityFactory.createKeyStore("PKCS12"); keyStore.load(null);// ww w .ja va 2 s . com generateRoot(); generateIntermediate(); keyStore.setKeyEntry("root", rootKeyPair.getPrivate(), null, new Certificate[] { rootCertificate }); keyStore.setKeyEntry("intermediate", intermediateKeyPair.getPrivate(), null, new Certificate[] { intermediateCertificate, rootCertificate }); FileOutputStream output = new FileOutputStream(p12File); keyStore.store(output, password.toCharArray()); output.close(); }
From source file:dk.itst.oiosaml.sp.IntegrationTests.java
@Before public final void setUpServer() throws Exception { tmpdir = new File(System.getProperty("java.io.tmpdir") + "/oiosaml-" + Math.random()); tmpdir.mkdir();//from w w w .j a v a2 s. c o m FileUtils.forceMkdir(new File(tmpdir, "metadata/IdP")); FileUtils.forceMkdir(new File(tmpdir, "metadata/SP")); credential = TestHelper.getCredential(); EntityDescriptor idpDescriptor = TestHelper.buildEntityDescriptor(credential); FileOutputStream fos = new FileOutputStream(new File(tmpdir, "metadata/IdP/gen.xml")); IOUtils.write(XMLHelper.nodeToString(SAMLUtil.marshallObject(idpDescriptor)).getBytes(), fos); fos.close(); EntityDescriptor spDescriptor = (EntityDescriptor) SAMLUtil .unmarshallElement(getClass().getResourceAsStream("/dk/itst/oiosaml/sp/SPMetadata.xml")); fos = new FileOutputStream(new File(tmpdir, "metadata/SP/SPMetadata.xml")); IOUtils.write(XMLHelper.nodeToString(SAMLUtil.marshallObject(spDescriptor)).getBytes(), fos); fos.close(); spMetadata = new SPMetadata(spDescriptor, SAMLConstants.SAML20P_NS); idpMetadata = new IdpMetadata(SAMLConstants.SAML20P_NS, idpDescriptor); fos = new FileOutputStream(new File(tmpdir, "oiosaml-sp.log4j.xml")); IOUtils.write( "<!DOCTYPE log4j:configuration SYSTEM \"http://logging.apache.org/log4j/docs/api/org/apache/log4j/xml/log4j.dtd\"><log4j:configuration xmlns:log4j=\"http://jakarta.apache.org/log4j/\" debug=\"false\"></log4j:configuration>", fos); fos.close(); Properties props = new Properties(); props.setProperty(Constants.PROP_CERTIFICATE_LOCATION, "keystore"); props.setProperty(Constants.PROP_CERTIFICATE_PASSWORD, "password"); props.setProperty(Constants.PROP_LOG_FILE_NAME, "oiosaml-sp.log4j.xml"); props.setProperty(SAMLUtil.OIOSAML_HOME, tmpdir.getAbsolutePath()); props.setProperty(Constants.PROP_SESSION_HANDLER_FACTORY, SingleVMSessionHandlerFactory.class.getName()); KeyStore ks = KeyStore.getInstance("JKS"); ks.load(null, null); ks.setKeyEntry("oiosaml", credential.getPrivateKey(), "password".toCharArray(), new Certificate[] { TestHelper.getCertificate(credential) }); OutputStream bos = new FileOutputStream(new File(tmpdir, "keystore")); ks.store(bos, "password".toCharArray()); bos.close(); props.setProperty(Constants.PROP_ASSURANCE_LEVEL, "2"); props.setProperty(Constants.PROP_IGNORE_CERTPATH, "true"); fos = new FileOutputStream(new File(tmpdir, "oiosaml-sp.properties")); props.store(fos, "Generated"); fos.close(); SAMLConfiguration.setSystemConfiguration(null); IdpMetadata.setMetadata(null); SPMetadata.setMetadata(null); System.setProperty(SAMLUtil.OIOSAML_HOME, tmpdir.getAbsolutePath()); server = new Server(8808); WebAppContext wac = new WebAppContext(); wac.setClassLoader(Thread.currentThread().getContextClassLoader()); wac.setContextPath("/saml"); wac.setWar("webapp/"); server.setHandler(wac); server.start(); client = new WebClient(); client.setRedirectEnabled(false); client.setThrowExceptionOnFailingStatusCode(false); handler = new RedirectRefreshHandler(); client.setRefreshHandler(handler); }
From source file:com.spotify.sshagenttls.CertHttpsHandler.java
public void handle(final HttpsURLConnection conn) { final CertKey certKey; try {/* w ww . j a va 2 s .c om*/ certKey = createCertKey(); } catch (IOException | GeneralSecurityException e) { if (failOnCertError) { throw new RuntimeException(e); } else { LOG.warn("Error when setting up client certificates fromPaths {}. Error was '{}'. " + "No cert will be sent with request.", getCertSource(), e.toString()); LOG.debug("full exception fromPaths setting up ClientCertificate follows", e); return; } } final Certificate cert = certKey.cert(); final PrivateKey key = certKey.key(); // Generate a keystore password. // Do all this locally to not make copies of the password in memory. final SecureRandom random = new SecureRandom(); final int numBytes = 60; final char[] keyStorePassword = new char[numBytes]; for (int i = 0; i < numBytes; i++) { // Only use ASCII characters for the password. The corresponding integer range is [32, 126]. keyStorePassword[i] = (char) (random.nextInt(95) + 32); } try { // We're creating a keystore in memory and putting the cert & key into it. // The keystore needs a password when we put the key into it, even though it's only going to // exist for the lifetime of the process. So we just have some random password that we use. final KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); keyStore.load(null, null); keyStore.setCertificateEntry("client", cert); keyStore.setKeyEntry("key", key, keyStorePassword, new Certificate[] { cert }); // build an SSLContext based on our keystore, and then get an SSLSocketFactory fromPaths that final SSLContext sslContext = SSLContexts.custom().useProtocol("TLS") .loadKeyMaterial(keyStore, keyStorePassword).build(); // Clear out arrays that had password Arrays.fill(keyStorePassword, '\0'); conn.setSSLSocketFactory(sslContext.getSocketFactory()); } catch (CertificateException | IOException | NoSuchAlgorithmException | KeyStoreException | UnrecoverableKeyException | KeyManagementException e) { // so many dumb ways to die. see https://www.youtube.com/watch?v=IJNR2EpS0jw for more. throw new RuntimeException(e); } }
From source file:com.spotify.docker.client.DockerCertificates.java
private DockerCertificates(final Builder builder) throws DockerCertificateException { try {/* w w w.j a v a2 s . co m*/ 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, null); 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.streamsets.pipeline.lib.remote.FTPAndSSHDUnitTest.java
protected File generateCertificateKeystore(KeyStoreType keystoreType) throws Exception { KeyPair keyPair = generateKeyPair(); X509Certificate cert = generateCertificate(keyPair); KeyStore keyStore = KeyStore.getInstance(keystoreType.getJavaValue()); keyStore.load(null, KEYSTORE_PASSWORD.toCharArray()); keyStore.setKeyEntry("foo", keyPair.getPrivate(), KEYSTORE_PASSWORD.toCharArray(), new Certificate[] { cert }); File keystoreFile = keystoreFolder.newFile("keystore " + System.currentTimeMillis() + ".jks"); try (FileOutputStream fos = new FileOutputStream(keystoreFile)) { keyStore.store(fos, KEYSTORE_PASSWORD.toCharArray()); }//from w w w. j av a2 s. co m return keystoreFile; }
From source file:org.nuxeo.ecm.core.blob.binary.TestAESBinaryManager.java
protected void createKeyStore(File file) throws GeneralSecurityException, IOException { AESBinaryManager.setUnlimitedJCEPolicy(); KeyGenerator kgen = KeyGenerator.getInstance("AES"); kgen.init(256);/*ww w . j a v a 2s .c o m*/ Key skey = kgen.generateKey(); KeyStore keyStore = KeyStore.getInstance(KEY_STORE_TYPE); // keyStore.load(null, KEY_STORE_PASSWORD.toCharArray()); keyStore.load(null, null); keyStore.setKeyEntry(KEY_ALIAS, skey, KEY_PASSWORD.toCharArray(), null); OutputStream out = new FileOutputStream(file); keyStore.store(out, KEY_STORE_PASSWORD.toCharArray()); out.close(); }
From source file:org.thingsboard.rule.engine.mqtt.credentials.CertPemClientCredentials.java
private KeyManagerFactory createAndInitKeyManagerFactory() throws Exception { X509Certificate certHolder = readCertFile(cert); Object keyObject = readPrivateKeyFile(privateKey); char[] passwordCharArray = "".toCharArray(); if (!StringUtils.isEmpty(password)) { passwordCharArray = password.toCharArray(); }/*w w w . ja v a2 s . c o m*/ JcaPEMKeyConverter keyConverter = new JcaPEMKeyConverter().setProvider("BC"); PrivateKey privateKey; if (keyObject instanceof PEMEncryptedKeyPair) { PEMDecryptorProvider provider = new JcePEMDecryptorProviderBuilder().build(passwordCharArray); KeyPair key = keyConverter.getKeyPair(((PEMEncryptedKeyPair) keyObject).decryptKeyPair(provider)); privateKey = key.getPrivate(); } else if (keyObject instanceof PEMKeyPair) { KeyPair key = keyConverter.getKeyPair((PEMKeyPair) keyObject); privateKey = key.getPrivate(); } else if (keyObject instanceof PrivateKey) { privateKey = (PrivateKey) keyObject; } else { throw new RuntimeException("Unable to get private key from object: " + keyObject.getClass()); } KeyStore clientKeyStore = KeyStore.getInstance(KeyStore.getDefaultType()); clientKeyStore.load(null, null); clientKeyStore.setCertificateEntry("cert", certHolder); clientKeyStore.setKeyEntry("private-key", privateKey, passwordCharArray, new Certificate[] { certHolder }); KeyManagerFactory keyManagerFactory = KeyManagerFactory .getInstance(KeyManagerFactory.getDefaultAlgorithm()); keyManagerFactory.init(clientKeyStore, passwordCharArray); return keyManagerFactory; }
From source file:com.thoughtworks.go.server.util.HttpTestUtil.java
private void prepareCertStore(File serverKeyStore) { KeyPair keyPair = generateKeyPair(); X509Certificate cert = generateCert(keyPair); FileOutputStream os = null;/* ww w. j a v a 2 s. c o m*/ try { KeyStore store = KeyStore.getInstance("JKS"); store.load(null, null); store.setKeyEntry("test", keyPair.getPrivate(), STORE_PASSWORD.toCharArray(), new Certificate[] { cert }); os = new FileOutputStream(serverKeyStore); store.store(os, STORE_PASSWORD.toCharArray()); } catch (Exception e) { throw new RuntimeException(e); } finally { if (os != null) { IOUtils.closeQuietly(os); } } }