List of usage examples for java.security KeyStore setCertificateEntry
public final void setCertificateEntry(String alias, Certificate cert) throws KeyStoreException
From source file:org.wso2.carbon.utils.security.KeyImporter.java
/** * sourcekeystore sourceStorepass keyalias targetstore targetStorePass * * @param args/* w ww. java 2 s. c om*/ */ public static void main(String[] args) throws Exception { if (log.isDebugEnabled()) { log.debug("Importing certificate ..."); } if (args.length != 5) { throw new Exception("Incorrect number of parameters"); } FileOutputStream fileOutputStream = null; try { String sourceStorePath = args[0]; String sourceStorePass = args[1]; String keyAlias = args[2]; String targetStorePath = args[3]; String targetStorePass = args[4]; KeyStore sourceStore = KeyStore.getInstance("JKS"); FileInputStream fis = new FileInputStream(new File(sourceStorePath).getAbsolutePath()); sourceStore.load(fis, sourceStorePass.toCharArray()); Certificate cert = sourceStore.getCertificateChain(keyAlias)[0]; KeyStore targetStore = KeyStore.getInstance("JKS"); File targetStoreFile = new File(targetStorePath); if (targetStoreFile.exists()) { targetStore.load(new FileInputStream(targetStoreFile.getAbsolutePath()), targetStorePass.toCharArray()); } else { targetStore.load(null, null); } targetStore.setCertificateEntry(keyAlias, cert); fileOutputStream = new FileOutputStream(new File(targetStorePath).getAbsolutePath()); targetStore.store(fileOutputStream, targetStorePass.toCharArray()); fis.close(); fileOutputStream.flush(); if (log.isDebugEnabled()) { log.debug("Importing certificate ... DONE !"); } } catch (Exception e) { log.error("Importing of key failed"); throw e; } finally { if (fileOutputStream != null) { fileOutputStream.close(); } } }
From source file:com.peterphi.std.crypto.keygen.CaHelper.java
public static void main(String[] args) throws Exception { String casubject = "C=UK, O=SOMEORG, OU=Org Unit, CN=Example Certificate Authority"; X509Certificate cacert = null; PrivateKey caPrivateKey = null; if (true) {/*from www .j a va2s . c om*/ KeyStore ks = KeyStore.getInstance("PKCS12", "BC"); ks.load(new FileInputStream(new File("/tmp/someorg-ca.p12")), new char[] {}); caPrivateKey = (PrivateKey) ks.getKey("ca", new char[] {}); cacert = (X509Certificate) ks.getCertificate("ca"); } else { KeyPair cakeys = generateKeyPair(2048); caPrivateKey = cakeys.getPrivate(); cacert = generateCaCertificate(casubject, cakeys, (BigInteger) null, new X509Name(casubject)); } { // CA .p12 { KeyStore ks = KeyStore.getInstance("PKCS12", "BC"); ks.load(null); //ks.setCertificateEntry("ca", cacert); ks.setKeyEntry("ca", caPrivateKey, new char[] {}, new java.security.cert.Certificate[] { cacert }); ks.store(new FileOutputStream("/tmp/someorg-ca.p12"), new char[] {}); } // CA .jks (public key only) { KeyStore ks = KeyStore.getInstance("JKS"); ks.load(null); ks.setCertificateEntry("ca", cacert); ks.store(new FileOutputStream("/tmp/ca-public.jks"), new char[] {}); } // CA .pem (public key only) { PEMWriter pem = new PEMWriter(new FileWriter(new File("/tmp/d3ca.crt"))); pem.writeObject(cacert); pem.close(); } } /* // User { String user = "C=UK, O=SOMEORG, OU=Org Unit, L=SomeCompany, CN=Some User (test)"; KeyPair keys = generateKeyPair(1024); X509Certificate cert = generateClientCertificate(keys.getPublic(), caPrivateKey, new X509Name(subject), new X509Name(user)); { KeyStore ks = KeyStore.getInstance("PKCS12", "BC"); ks.load(null); ks.setCertificateEntry("issuer", cacert); ks.setCertificateEntry("me", cert); ks.setKeyEntry("me", keys.getPrivate(), new char[] {}, new java.security.cert.Certificate[] { cert, cacert }); ks.store(new FileOutputStream("/tmp/someorg-someuser.p12"), "SomeCompanysecurity".toCharArray()); } { KeyStore ks = KeyStore.getInstance("JKS"); ks.load(null); ks.setKeyEntry("me", keys.getPrivate(), new char[] {}, new java.security.cert.Certificate[] { cert, cacert }); // ks.setCertificateEntry("issuer", cacert); // ks.setCertificateEntry("me", cert); ks.store(new FileOutputStream("/tmp/someorg-someuser.jks"), new char[] {}); } }//*/ // examplehost hostkey: { String user = "C=UK, O=SOMEORG, OU=Org Unit, L=SomeCompany, CN=examplehost.example.com"; KeyPair keys = generateKeyPair(1024); X509Certificate cert = generateServerCertificate(keys.getPublic(), caPrivateKey, new X509Name(casubject), new X509Name(user)); { KeyStore ks = KeyStore.getInstance("JKS"); ks.load(null); ks.setKeyEntry("me", keys.getPrivate(), new char[] {}, new java.security.cert.Certificate[] { cert, cacert }); // ks.setCertificateEntry("issuer", cacert); // ks.setCertificateEntry("me", cert); ks.store(new FileOutputStream("/tmp/host.jks"), new char[] {}); } { KeyStore ks = KeyStore.getInstance("PKCS12", "BC"); ks.load(null); ks.setCertificateEntry("issuer", cacert); ks.setCertificateEntry("me", cert); ks.setKeyEntry("me", keys.getPrivate(), new char[] {}, new java.security.cert.Certificate[] { cert, cacert }); ks.store(new FileOutputStream("/tmp/host.p12"), new char[] {}); } } }
From source file:net.sf.jsignpdf.InstallCert.java
/** * The main - whole logic of Install Cert Tool. * // w w w. j a v a2 s . c o m * @param args * @throws Exception */ public static void main(String[] args) { String host; int port; char[] passphrase; System.out.println("InstallCert - Install CA certificate to Java Keystore"); System.out.println("====================================================="); final BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); try { if ((args.length == 1) || (args.length == 2)) { String[] c = args[0].split(":"); host = c[0]; port = (c.length == 1) ? 443 : Integer.parseInt(c[1]); String p = (args.length == 1) ? "changeit" : args[1]; passphrase = p.toCharArray(); } else { String tmpStr; do { System.out.print("Enter hostname or IP address: "); tmpStr = StringUtils.defaultIfEmpty(reader.readLine(), null); } while (tmpStr == null); host = tmpStr; System.out.print("Enter port number [443]: "); tmpStr = StringUtils.defaultIfEmpty(reader.readLine(), null); port = tmpStr == null ? 443 : Integer.parseInt(tmpStr); System.out.print("Enter keystore password [changeit]: "); tmpStr = reader.readLine(); String p = "".equals(tmpStr) ? "changeit" : tmpStr; passphrase = p.toCharArray(); } char SEP = File.separatorChar; final File dir = new File(System.getProperty("java.home") + SEP + "lib" + SEP + "security"); final File file = new File(dir, "cacerts"); System.out.println("Loading KeyStore " + file + "..."); InputStream in = new FileInputStream(file); KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); ks.load(in, passphrase); in.close(); SSLContext context = SSLContext.getInstance("TLS"); TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(ks); X509TrustManager defaultTrustManager = (X509TrustManager) tmf.getTrustManagers()[0]; SavingTrustManager tm = new SavingTrustManager(defaultTrustManager); context.init(null, new TrustManager[] { tm }, null); SSLSocketFactory factory = context.getSocketFactory(); System.out.println("Opening connection to " + host + ":" + port + "..."); SSLSocket socket = (SSLSocket) factory.createSocket(host, port); socket.setSoTimeout(10000); try { System.out.println("Starting SSL handshake..."); socket.startHandshake(); socket.close(); System.out.println(); System.out.println("No errors, certificate is already trusted"); } catch (SSLException e) { System.out.println(); System.out.println("Certificate is not yet trusted."); // e.printStackTrace(System.out); } X509Certificate[] chain = tm.chain; if (chain == null) { System.out.println("Could not obtain server certificate chain"); return; } System.out.println(); System.out.println("Server sent " + chain.length + " certificate(s):"); System.out.println(); MessageDigest sha1 = MessageDigest.getInstance("SHA1"); MessageDigest md5 = MessageDigest.getInstance("MD5"); for (int i = 0; i < chain.length; i++) { X509Certificate cert = chain[i]; System.out.println(" " + (i + 1) + " Subject " + cert.getSubjectDN()); System.out.println(" Issuer " + cert.getIssuerDN()); sha1.update(cert.getEncoded()); System.out.println(" sha1 " + toHexString(sha1.digest())); md5.update(cert.getEncoded()); System.out.println(" md5 " + toHexString(md5.digest())); System.out.println(); } System.out.print("Enter certificate to add to trusted keystore or 'q' to quit [1]: "); String line = reader.readLine().trim(); int k = -1; try { k = (line.length() == 0) ? 0 : Integer.parseInt(line) - 1; } catch (NumberFormatException e) { } if (k < 0 || k >= chain.length) { System.out.println("KeyStore not changed"); } else { try { System.out.println("Creating keystore backup"); final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss"); final File backupFile = new File(dir, CACERTS_KEYSTORE + "." + dateFormat.format(new java.util.Date())); final FileInputStream fis = new FileInputStream(file); final FileOutputStream fos = new FileOutputStream(backupFile); IOUtils.copy(fis, fos); fis.close(); fos.close(); } catch (Exception e) { e.printStackTrace(); } System.out.println("Installing certificate..."); X509Certificate cert = chain[k]; String alias = host + "-" + (k + 1); ks.setCertificateEntry(alias, cert); OutputStream out = new FileOutputStream(file); ks.store(out, passphrase); out.close(); System.out.println(); System.out.println(cert); System.out.println(); System.out.println("Added certificate to keystore '" + file + "' using alias '" + alias + "'"); } } catch (Exception e) { System.out.println(); System.out.println("----------------------------------------------"); System.out.println("Problem occured during installing certificate:"); e.printStackTrace(); System.out.println("----------------------------------------------"); } System.out.println("Press Enter to finish..."); try { reader.readLine(); } catch (IOException e) { e.printStackTrace(); } }
From source file:Main.java
public static void addCertToKnownServersStore(Certificate cert, Context context) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException { KeyStore knownServers = getKnownServersStore(context); knownServers.setCertificateEntry(Integer.toString(cert.hashCode()), cert); FileOutputStream fos = null;/*from ww w . j av a2s . com*/ try { fos = context.openFileOutput(LOCAL_TRUSTSTORE_FILENAME, Context.MODE_PRIVATE); knownServers.store(fos, LOCAL_TRUSTSTORE_PASSWORD.toCharArray()); } finally { fos.close(); } }
From source file:Main.java
public static SocketFactory getSocketFactoryWithCustomCA(InputStream stream) throws CertificateException, KeyStoreException, IOException, NoSuchAlgorithmException, KeyManagementException { // Load CAs from an InputStream // (could be from a resource or ByteArrayInputStream or ...) CertificateFactory cf = CertificateFactory.getInstance("X.509"); InputStream caInput = new BufferedInputStream(stream); Certificate ca;/*w w w. java 2s. c om*/ try { ca = cf.generateCertificate(caInput); System.out.println("ca=" + ((X509Certificate) ca).getSubjectDN()); } finally { try { caInput.close(); } catch (IOException e) { e.printStackTrace(); } } // Create a KeyStore containing our trusted CAs String keyStoreType = KeyStore.getDefaultType(); KeyStore keyStore = KeyStore.getInstance(keyStoreType); keyStore.load(null, null); keyStore.setCertificateEntry("ca", ca); // Create a TrustManager that trusts the CAs in our KeyStore String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); tmf.init(keyStore); // Create an SSLContext that uses our TrustManager SSLContext context = SSLContext.getInstance("TLS"); context.init(null, tmf.getTrustManagers(), null); return context.getSocketFactory(); }
From source file:Main.java
/** * Generate a SSLSocketFactory wich checks the certificate given * @param context Context to use/* w w w. j a v a2s .c o m*/ * @param rResource int with url of the resource to read the certificate * @parma password String to use with certificate * @return SSLSocketFactory generated to validate this certificate */ public static SSLSocketFactory newSslSocketFactory(Context context, int rResource, String password) throws CertificateException, NoSuchProviderException, KeyStoreException, NoSuchAlgorithmException, IOException, UnrecoverableKeyException, KeyManagementException { // Get an instance of the Bouncy Castle KeyStore format KeyStore trusted = KeyStore.getInstance("BKS"); // Get the raw resource, which contains the keystore with // your trusted certificates (root and any intermediate certs) InputStream is = context.getApplicationContext().getResources().openRawResource(rResource); CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509", "BC"); X509Certificate cert = (X509Certificate) certificateFactory.generateCertificate(is); String alias = "alias";//cert.getSubjectX500Principal().getName(); KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(null); trustStore.setCertificateEntry(alias, cert); KeyManagerFactory kmf = KeyManagerFactory.getInstance("X509"); kmf.init(trustStore, null); KeyManager[] keyManagers = kmf.getKeyManagers(); TrustManagerFactory tmf = TrustManagerFactory.getInstance("X509"); tmf.init(trustStore); TrustManager[] trustManagers = tmf.getTrustManagers(); SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(keyManagers, trustManagers, null); return sslContext.getSocketFactory(); }
From source file:com.cloudbees.tftwoway.Client.java
public static TrustManager[] getTrustManager() throws Exception { TrustManagerFactory trustManagerFactory = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); KeyStore store = KeyStore.getInstance("JKS"); store.load(null);//from ww w .j a v a2s. c om X509Certificate cacerts = loadX509Key(CACERT); store.setCertificateEntry("cert", cacerts); trustManagerFactory.init(store); return trustManagerFactory.getTrustManagers(); }
From source file:com.cerema.cloud2.lib.common.network.NetworkUtils.java
public static void addCertToKnownServersStore(Certificate cert, Context context) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException { KeyStore knownServers = getKnownServersStore(context); knownServers.setCertificateEntry(Integer.toString(cert.hashCode()), cert); FileOutputStream fos = null;/*from w ww .j av a 2s. c om*/ try { fos = context.openFileOutput(LOCAL_TRUSTSTORE_FILENAME, Context.MODE_PRIVATE); knownServers.store(fos, LOCAL_TRUSTSTORE_PASSWORD.toCharArray()); } finally { fos.close(); } }
From source file:org.comixwall.pffw.Utils.java
/** * Create an SSL context which trusts the PFFW server certificate. * PFFW server certificate is self signed, hence is not verified by the default SSL context. * * @param owner Fragment which initiated the call to this method. * @return SSL context./*w ww .j a v a2 s . com*/ */ static SSLContext getSslContext(final Fragment owner) { SSLContext sslContext = null; try { // Load our crt from an InputStream CertificateFactory cf = CertificateFactory.getInstance("X.509"); InputStream crtInput = owner.getResources().openRawResource( owner.getResources().getIdentifier("server", "raw", owner.getActivity().getPackageName())); Certificate crt; try { crt = cf.generateCertificate(crtInput); logger.finest("server.crt=" + ((X509Certificate) crt).getSubjectDN()); } finally { crtInput.close(); } // Create a KeyStore containing our trusted crt String keyStoreType = KeyStore.getDefaultType(); KeyStore keyStore = KeyStore.getInstance(keyStoreType); keyStore.load(null, null); keyStore.setCertificateEntry("server.crt", crt); // Create a TrustManager that trusts the crt in our KeyStore String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); tmf.init(keyStore); // Create an SSLContext that uses our TrustManager sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, tmf.getTrustManagers(), null); } catch (Exception e) { e.printStackTrace(); logger.severe("getSslContext exception: " + e.toString()); } return sslContext; }
From source file:org.rhq.enterprise.server.plugins.rhnhosted.RHNSSLSocketFactory.java
/** * * @param sslCerts these certs will be used to validate the ssl connection * @return//from ww w . j a va 2 s . co m * @throws IOException * @throws GeneralSecurityException */ static public SSLSocketFactory getSSLSocketFactory(List<X509Certificate> sslCerts) throws IOException, GeneralSecurityException { SSLContext sc = null; KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); ks.load(null); //Important, this intializes the keystore int counter = 0; for (X509Certificate cert : sslCerts) { ks.setCertificateEntry("rhn-key-" + counter, cert); counter++; } sc = SSLContext.getInstance("SSL"); TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(ks); sc.init(null, tmf.getTrustManagers(), new java.security.SecureRandom()); return sc.getSocketFactory(); }