private KeyManager[] getKeyManagers(InputStream certificate, String passphrase) throws IOException { if (key_managers == null) { KeyStore ks; try { ks = KeyStore.getInstance("PKCS12"); } catch (KeyStoreException e) { throw new RuntimeException("Unable to create key store."); } char certphrase[] = passphrase.toCharArray(); try { ks.load(certificate, certphrase); } catch (GeneralSecurityException e) { throw new RuntimeException("Bad certificate or unknown type."); } finally { closeQuietly(certificate); } KeyManagerFactory kmf; try { kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmf.init(ks, certphrase); } catch (GeneralSecurityException e) { throw new RuntimeException(e.getMessage()); } key_managers = kmf.getKeyManagers(); } return key_managers; }
private static KeyStore readKeyStore(String name) throws Exception { File file = new File(PATH, name); InputStream in = new FileInputStream(file); KeyStore ks = KeyStore.getInstance("JKS"); ks.load(in, passwd); in.close(); return ks; }
/** * Creates an empty keystore * * @throws Exception */ private void createKeystore() throws Exception { if (keystore == null) { Security.addProvider(bouncyCastleProvider); keystore = KeyStore.getInstance(Configuration.getSSLClientKeyStoreType(), bouncyCastleProvider); keystore.load(null, KEYSTORE_PASSWORD.toCharArray()); } }
public void testDefaults() throws Exception { Properties p = initProps(); KeyStore ks = KeyStoreUtil.createKeyStore(p); List aliases = ListUtil.fromIterator(new EnumerationIterator(ks.aliases())); assertIsomorphic(SetUtil.set("mykey", "mycert"), SetUtil.theSet(aliases)); assertNotNull(ks.getCertificate("mycert")); assertNull(ks.getCertificate("foocert")); assertEquals("JCEKS", ks.getType()); }
void assertPubKs(File file, String pass, List<String> hosts) throws Exception { KeyStore ks = loadKeyStore("jceks", file, pass); List aliases = ListUtil.fromIterator(new EnumerationIterator(ks.aliases())); assertEquals(hosts.size(), aliases.size()); for (String host : hosts) { String alias = host + ".crt"; Certificate cert = ks.getCertificate(alias); assertNotNull(cert); assertEquals("X.509", cert.getType()); } }
/* * Define the client side of the test. * * If the server prematurely exits, serverReady will be set to true * to avoid infinite hangs. */ void doClientSide() throws Exception { /* * Wait for server to get started. */ while (!serverReady) { Thread.sleep(50); } /* * See if an unknown keystore actually gets checked ok. */ System.out.println("=============="); System.out.println("Starting test0"); KeyStore uks = KeyStore.getInstance("JKS"); SSLContext ctx = SSLContext.getInstance("TLS"); KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); uks.load(new FileInputStream(unknownFilename), cpasswd); kmf.init(uks, cpasswd); TrustManager[] tms = new TrustManager[] {new MyJavaxX509TrustManager()}; ctx.init(kmf.getKeyManagers(), tms, null); SSLSocketFactory sslsf = (SSLSocketFactory) ctx.getSocketFactory(); System.out.println("Trying first socket " + serverPort); SSLSocket sslSocket = (SSLSocket) sslsf.createSocket("localhost", serverPort); doTest(sslSocket); /* * Now try the other way. */ com.sun.net.ssl.SSLContext ctx1 = com.sun.net.ssl.SSLContext.getInstance("TLS"); com.sun.net.ssl.KeyManagerFactory kmf1 = com.sun.net.ssl.KeyManagerFactory.getInstance("SunX509"); kmf1.init(uks, cpasswd); com.sun.net.ssl.TrustManager[] tms1 = new com.sun.net.ssl.TrustManager[] {new MyComX509TrustManager()}; ctx1.init(kmf1.getKeyManagers(), tms1, null); sslsf = (SSLSocketFactory) ctx1.getSocketFactory(); System.out.println("Trying second socket " + serverPort1); sslSocket = (SSLSocket) sslsf.createSocket("localhost", serverPort1); doTest(sslSocket); System.out.println("Completed test1"); }
public static void main(String args[]) { int port = 6502; SSLServerSocket server; try { // get the keystore into memory KeyStore ks = KeyStore.getInstance("JKS"); ks.load(new FileInputStream(keyStore), keyStorePass); // initialize the key manager factory with the keystore data KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); kmf.init(ks, keyStorePass); // initialize the SSLContext engine // may throw NoSuchProvider or NoSuchAlgorithm exception // TLS - Transport Layer Security most generic SSLContext sslContext = SSLContext.getInstance("TLS"); // Inititialize context with given KeyManagers, TrustManagers, // SecureRandom defaults taken if null sslContext.init(kmf.getKeyManagers(), null, null); // Get ServerSocketFactory from the context object ServerSocketFactory ssf = sslContext.getServerSocketFactory(); // Now like programming with normal server sockets ServerSocket serverSocket = ssf.createServerSocket(port); System.out.println("Accepting secure connections"); Socket client = serverSocket.accept(); System.out.println("Got connection"); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(client.getOutputStream())); BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream())); String username = in.readLine(); String password = in.readLine(); if (username.equals("Josh") && password.equals("GoBucs")) { out.write("Greeting Client"); } else { out.write("Sorry, you are not authorized"); } out.flush(); in.close(); out.close(); } catch (Exception e) { System.out.println("Exception thrown " + e); } }
private static TrustManager[] createTrustManagers() throws GeneralSecurityException, IOException { InputStream keyStoreStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("ssltest-keystore.jks"); char[] keyStorePassword = "******".toCharArray(); KeyStore ks = KeyStore.getInstance("JKS"); ks.load(keyStoreStream, keyStorePassword); assert (ks.size() > 0); TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(ks); return tmf.getTrustManagers(); }
private void createClientKeyStore() throws Exception { clientCertKeystore = KeyStore.getInstance(Configuration.getSSLClientKeyStoreType()); String clientCertPath = Configuration.getSSLClientCertPath(); FileInputStream fileInputStream = null; if (clientCertPath != null) { try { fileInputStream = new FileInputStream(clientCertPath); } catch (IOException ioe) { logger.error("\n----\nCertificate not found: " + clientCertPath + "\n----"); } } String password = Configuration.getSSLClientCertPassword(); char[] passphrase = password == null ? null : password.toCharArray(); clientCertKeystore.load(fileInputStream, passphrase); }
public static KeyStore readKeyStore(String keystorePath, String password) throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException, UnrecoverableKeyException, KeyManagementException { KeyStore keyStore = KeyStore.getInstance("JKS"); FileInputStream fis = null; try { fis = new FileInputStream(keystorePath); keyStore.load(fis, password.toCharArray()); } finally { if (fis != null) { fis.close(); } } return keyStore; }
/* * If this is a secure server, we now setup the SSLContext we'll * use for creating the SSLEngines throughout the lifetime of * this process. */ private void createSSLContext() throws Exception { char[] passphrase = "passphrase".toCharArray(); KeyStore ks = KeyStore.getInstance("JKS"); ks.load(new FileInputStream("testkeys"), passphrase); KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); kmf.init(ks, passphrase); TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509"); tmf.init(ks); sslContext = SSLContext.getInstance("TLS"); sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); }
private static KeyManager[] createKeyManagers() throws GeneralSecurityException, IOException { InputStream keyStoreStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("ssltest-cacerts.jks"); char[] keyStorePassword = "******".toCharArray(); KeyStore ks = KeyStore.getInstance("JKS"); ks.load(keyStoreStream, keyStorePassword); assert (ks.size() > 0); // Set up key manager factory to use our key store char[] certificatePassword = "******".toCharArray(); KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); kmf.init(ks, certificatePassword); // Initialize the SSLContext to work with our key managers. return kmf.getKeyManagers(); }
private void addCertToKeystore(X509Certificate _cert, Key _privateKey, String alias) throws KeyStoreException { X509Certificate[] chain = new X509Certificate[2]; chain[0] = _cert; chain[1] = rootCA; keystore.setKeyEntry(alias, _privateKey, KEYSTORE_PASSWORD.toCharArray(), chain); }
private X509Certificate buildSignedCert(String domain, KeyPair _keyPair) throws Exception { PrivateKey privateRootKey = (PrivateKey) keystore.getKey(Configuration.getRootCaName(), KEYSTORE_PASSWORD.toCharArray()); X509v3CertificateBuilder certificateBuilder = createX509v3CertificateBuilder(domain, _keyPair); return createX509Certificate(certificateBuilder, privateRootKey); }
private static void loadKeyStore(File keyStoreFile) { try { FileInputStream fileInputStream = null; try { fileInputStream = new FileInputStream(KEY_STORE_FILENAME); logger.trace("Loading key store from file [" + keyStoreFile + "]"); keystore = KeyStore.getInstance(KeyStore.getDefaultType()); keystore.load(fileInputStream, KEY_STORE_PASSWORD.toCharArray()); } finally { if (fileInputStream != null) { fileInputStream.close(); } } } catch (Exception e) { throw new RuntimeException( "Exception while loading KeyStore from " + keyStoreFile.getAbsolutePath(), e); } }
public void testCreateSharedPLNKeyStores() throws Exception { List<String> hosts = ListUtil.list("host1", "host2.foo.bar", "host3"); List<String> hosts2 = ListUtil.list("host3", "host4"); File dir = getTempDir(); File pub = new File(dir, "pub.ks"); KeyStoreUtil.createSharedPLNKeyStores( dir, hosts, pub, "pubpass", MiscTestUtil.getSecureRandom()); assertPubKs(pub, "pubpass", hosts); for (String host : hosts) { assertPrivateKs( new File(dir, host + ".jceks"), StringUtil.fromFile(new File(dir, host + ".pass")), host); } KeyStore pubks1 = loadKeyStore("jceks", new File(dir, "pub.ks"), "pubpass"); Certificate host1cert1 = pubks1.getCertificate("host1.crt"); Certificate host3cert1 = pubks1.getCertificate("host3.crt"); String host1priv1 = StringUtil.fromFile(new File(dir, "host1.jceks")); String host3priv1 = StringUtil.fromFile(new File(dir, "host3.jceks")); // Now add host4 and generate a new key for host3 KeyStoreUtil.createSharedPLNKeyStores( dir, hosts2, pub, "pubpass", MiscTestUtil.getSecureRandom()); List<String> both = ListUtils.sum(hosts, hosts2); assertPubKs(pub, "pubpass", both); for (String host : both) { assertPrivateKs( new File(dir, host + ".jceks"), StringUtil.fromFile(new File(dir, host + ".pass")), host); } KeyStore pubks2 = loadKeyStore("jceks", new File(dir, "pub.ks"), "pubpass"); // host1 should have the same cert, host3 not Certificate host1cert2 = pubks2.getCertificate("host1.crt"); Certificate host3cert2 = pubks2.getCertificate("host3.crt"); assertEquals(host1cert1, host1cert2); assertNotEquals(host3cert1, host3cert2); // host1's private key file should be the same, host3's not String host1priv2 = StringUtil.fromFile(new File(dir, "host1.jceks")); String host3priv2 = StringUtil.fromFile(new File(dir, "host3.jceks")); assertEquals(host1priv1, host1priv2); assertNotEquals(host3priv1, host3priv2); }
/** * We need a root CA as a file to add to the browser under which all certificates will be trusted. * * @throws Exception */ private void createRootCA() throws Exception { KeyPair _keyPair = newKeyPair(); rootCA = buildRootCert(Configuration.getRootCaName(), _keyPair); writePEMObject(rootCAPath, rootCA); writePEMObject(Configuration.getRootKeyPath(), _keyPair.getPrivate()); keystore.setKeyEntry( Configuration.getRootCaName(), _keyPair.getPrivate(), KEYSTORE_PASSWORD.toCharArray(), new X509Certificate[] {rootCA}); }
private void loadKeyStoreFromFile(KeyStore pKeyStore, String pFile, char[] pPassword) throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException { FileInputStream fis = null; try { fis = new FileInputStream(getAndValidateFile(pFile, "keystore")); pKeyStore.load(fis, pPassword); } finally { if (fis != null) { fis.close(); } } }
/** * Read certificate and adds it to the keystore. * * @throws IOException * @throws CertificateException * @throws KeyStoreException */ private void readRootCA() throws IOException, CertificateException, KeyStoreException { Key _privateKey = readPrivateKey(Configuration.getRootKeyPath()); X509CertificateHolder holder = (X509CertificateHolder) readWithPemParser(Configuration.getRootCaPath()); rootCA = new JcaX509CertificateConverter() .setProvider(BouncyCastleProvider.PROVIDER_NAME) .getCertificate(holder); keystore.setKeyEntry( Configuration.getRootCaName(), _privateKey, KEYSTORE_PASSWORD.toCharArray(), new X509Certificate[] {rootCA}); }
private KeyStore getKeyStore(JolokiaServerConfig pConfig) throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException, InvalidKeySpecException, InvalidKeyException, NoSuchProviderException, SignatureException { char[] password = pConfig.getKeystorePassword(); String keystoreFile = pConfig.getKeystore(); KeyStore keystore = KeyStore.getInstance(pConfig.getKeyStoreType()); if (keystoreFile != null) { // Load everything from a keystore which must include CA (if useClientSslAuthenticatin is // used) and // server cert/key loadKeyStoreFromFile(keystore, keystoreFile, password); } else { // Load keys from PEM files keystore.load(null); updateKeyStoreFromPEM(keystore, pConfig); // If no server cert is configured, then use a self-signed server certificate if (pConfig.getServerCert() == null) { KeyStoreUtil.updateWithSelfSignedServerCertificate(keystore); } } return keystore; }
public void testStore() throws Exception { File dir = getTempDir(); File file = new File(dir, "test.ks"); Properties p = initProps(); p.put(KeyStoreUtil.PROP_KEYSTORE_FILE, file.toString()); assertFalse(file.exists()); KeyStore ks = KeyStoreUtil.createKeyStore(p); assertTrue(file.exists()); KeyStore ks2 = loadKeyStore(ks.getType(), file, PASSWD); List aliases = ListUtil.fromIterator(new EnumerationIterator(ks2.aliases())); assertIsomorphic(SetUtil.set("mykey", "mycert"), SetUtil.theSet(aliases)); assertNotNull(ks2.getCertificate("mycert")); assertNull(ks2.getCertificate("foocert")); assertEquals("JCEKS", ks2.getType()); }
void assertPrivateKs(File file, String pass, String alias) throws Exception { KeyStore ks = loadKeyStore("jceks", file, alias); List aliases = ListUtil.fromIterator(new EnumerationIterator(ks.aliases())); assertEquals(2, aliases.size()); Certificate cert = ks.getCertificate(alias + ".crt"); assertNotNull(cert); assertEquals("X.509", cert.getType()); assertTrue(ks.isKeyEntry(alias + ".key")); assertTrue(ks.isCertificateEntry(alias + ".crt")); Key key = ks.getKey(alias + ".key", pass.toCharArray()); assertNotNull(key); assertEquals("RSA", key.getAlgorithm()); }
private static void saveKeyStore() { try { ByteArrayOutputStream bout = new ByteArrayOutputStream(); keystore.store(bout, KEY_STORE_PASSWORD.toCharArray()); File keyStoreFile = new File(KEY_STORE_FILENAME); logger.trace("Saving key store to file [" + keyStoreFile + "]"); FileOutputStream fileOutputStream = null; try { fileOutputStream = new FileOutputStream(keyStoreFile); fileOutputStream.write(bout.toByteArray()); } finally { if (fileOutputStream != null) { fileOutputStream.close(); } } keyStoreFile.deleteOnExit(); } catch (Exception e) { throw new RuntimeException("Exception while saving KeyStore", e); } }
private void initialize() throws Exception { String trustFilename = System.getProperty("test.src", "./") + "/" + pathToStores + "/" + trustStoreFile; char[] passphrase = "passphrase".toCharArray(); KeyStore ks = KeyStore.getInstance("JKS"); ks.load(new FileInputStream(trustFilename), passphrase); for (Enumeration e = ks.aliases(); e.hasMoreElements(); ) { String alias = (String) e.nextElement(); if (ks.isCertificateEntry(alias)) { certChain[0] = (X509Certificate) ks.getCertificate(alias); break; } } TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509"); tmf.init(ks); trustManager = (X509TrustManager) (tmf.getTrustManagers())[0]; }
static { try { KeyStore ks = KeyStore.getInstance("JKS"); KeyStore ts = KeyStore.getInstance("JKS"); char[] passphrase = "passphrase".toCharArray(); ks.load(new FileInputStream(keyFilename), passphrase); ts.load(new FileInputStream(trustFilename), passphrase); KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); kmf.init(ks, passphrase); TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509"); tmf.init(ts); SSLContext sslCtx = SSLContext.getInstance("TLS"); sslCtx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null); sslc = sslCtx; } catch (Exception e) { loadException = e; } }
/* * Define the server side of the test. * * If the server prematurely exits, serverReady will be set to true * to avoid infinite hangs. */ void doServerSide() throws Exception { KeyStore ks = KeyStore.getInstance("JKS"); com.sun.net.ssl.SSLContext ctx = com.sun.net.ssl.SSLContext.getInstance("TLS"); com.sun.net.ssl.KeyManagerFactory kmf = com.sun.net.ssl.KeyManagerFactory.getInstance("SunX509"); ks.load(new FileInputStream(keyFilename), cpasswd); kmf.init(ks, cpasswd); com.sun.net.ssl.TrustManager[] tms = new com.sun.net.ssl.TrustManager[] {new MyComX509TrustManager()}; ctx.init(kmf.getKeyManagers(), tms, null); SSLServerSocketFactory sslssf = (SSLServerSocketFactory) ctx.getServerSocketFactory(); SSLServerSocket sslServerSocket = (SSLServerSocket) sslssf.createServerSocket(serverPort); serverPort = sslServerSocket.getLocalPort(); sslServerSocket.setNeedClientAuth(true); /* * Create using the other type. */ SSLContext ctx1 = SSLContext.getInstance("TLS"); KeyManagerFactory kmf1 = KeyManagerFactory.getInstance("SunX509"); TrustManager[] tms1 = new TrustManager[] {new MyJavaxX509TrustManager()}; kmf1.init(ks, cpasswd); ctx1.init(kmf1.getKeyManagers(), tms1, null); sslssf = (SSLServerSocketFactory) ctx1.getServerSocketFactory(); SSLServerSocket sslServerSocket1 = (SSLServerSocket) sslssf.createServerSocket(serverPort1); serverPort1 = sslServerSocket1.getLocalPort(); sslServerSocket1.setNeedClientAuth(true); /* * Signal Client, we're ready for his connect. */ serverReady = true; SSLSocket sslSocket = (SSLSocket) sslServerSocket.accept(); sslServerSocket.close(); serverReady = false; InputStream sslIS = sslSocket.getInputStream(); OutputStream sslOS = sslSocket.getOutputStream(); sslIS.read(); sslOS.write(85); sslOS.flush(); sslSocket.close(); sslSocket = (SSLSocket) sslServerSocket1.accept(); sslIS = sslSocket.getInputStream(); sslOS = sslSocket.getOutputStream(); sslIS.read(); sslOS.write(85); sslOS.flush(); sslSocket.close(); System.out.println("Server exiting!"); System.out.flush(); }
/** * Create KeyStore and add a self-signed X.509 Certificate * * @param dname the X.509 Distinguished Name, eg "CN=www.google.co.uk, O=\"Google Inc\", * L=\"Mountain View\", S=California, C=US" * @param keyAlgorithmName the key algorithm, eg "RSA" */ private static KeyStore generateCertificate( String alias, char[] keyStorePassword, KeyAlgorithmName keyAlgorithmName, String dname, String... sanDomains) throws GeneralSecurityException, IOException { CertAndKeyGen certAndKeyGen = new CertAndKeyGen( keyAlgorithmName.name(), keyAlgorithmName.signatureAlgorithmName, "SunCertificates"); certAndKeyGen.generate(keyAlgorithmName.keySize); PrivateKey privateKey = certAndKeyGen.getPrivateKey(); X509CertInfo info = new X509CertInfo(); Date from = new Date(); Date to = new Date(from.getTime() + TimeUnit.DAYS.toMillis(360)); CertificateValidity interval = new CertificateValidity(from, to); BigInteger sn = new BigInteger(64, new SecureRandom()); X500Name owner = new X500Name(dname); info.set(X509CertInfo.VALIDITY, interval); info.set(X509CertInfo.SERIAL_NUMBER, new CertificateSerialNumber(sn)); info.set(X509CertInfo.SUBJECT, new CertificateSubjectName(owner)); info.set(X509CertInfo.ISSUER, new CertificateIssuerName(owner)); info.set(X509CertInfo.KEY, new CertificateX509Key(certAndKeyGen.getPublicKey())); info.set(X509CertInfo.VERSION, new CertificateVersion(CertificateVersion.V3)); info.set( X509CertInfo.ALGORITHM_ID, new CertificateAlgorithmId(new AlgorithmId(AlgorithmId.md5WithRSAEncryption_oid))); // add subject alternative names GeneralNames generalNames = new GeneralNames(); for (String sanDomain : sanDomains) { generalNames.add(new GeneralName(new DNSName(sanDomain))); } if (generalNames.size() > 0) { CertificateExtensions certificateExtensions = (CertificateExtensions) info.get(X509CertInfo.EXTENSIONS); if (certificateExtensions == null) certificateExtensions = new CertificateExtensions(); certificateExtensions.set( SubjectAlternativeNameExtension.NAME, new SubjectAlternativeNameExtension(generalNames)); info.set(X509CertInfo.EXTENSIONS, certificateExtensions); } // Sign the certificate to identify the algorithm that's used. X509CertImpl x509Certificate = new X509CertImpl(info); x509Certificate.sign(privateKey, keyAlgorithmName.signatureAlgorithmName); // update the algorithm, and resign. info.set( CertificateAlgorithmId.NAME + "." + CertificateAlgorithmId.ALGORITHM, x509Certificate.get(X509CertImpl.SIG_ALG)); x509Certificate = new X509CertImpl(info); x509Certificate.sign(privateKey, keyAlgorithmName.signatureAlgorithmName); // add to new key store KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); keyStore.load(null, keyStorePassword); keyStore.setKeyEntry( alias, privateKey, keyStorePassword, new X509Certificate[] {x509Certificate}); return keyStore; }
KeyStore loadKeyStore(String type, File file, String passwd) throws Exception { KeyStore ks = KeyStore.getInstance(type); FileInputStream fis = new FileInputStream(file); ks.load(fis, passwd.toCharArray()); return ks; }