List of usage examples for java.security KeyStore store
public final void store(OutputStream stream, char[] password) throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException
From source file:MainClass.java
public static void main(String args[]) throws Exception { char[] oldpass = args[0].toCharArray(); char[] newpass = args[1].toCharArray(); String name = "mykeystore"; FileInputStream in = new FileInputStream(name); KeyStore ks = KeyStore.getInstance("JKS"); ks.load(in, oldpass);//from w w w. j a v a 2s. c o m in.close(); FileOutputStream output = new FileOutputStream(name); ks.store(output, newpass); output.close(); }
From source file:MainClass.java
public static void main(String args[]) throws Exception { String cacert = "mytest.cer"; String lfcert = "lf_signed.cer"; String lfstore = "lfkeystore"; char[] lfstorepass = "wshr.ut".toCharArray(); char[] lfkeypass = "wshr.ut".toCharArray(); CertificateFactory cf = CertificateFactory.getInstance("X.509"); FileInputStream in1 = new FileInputStream(cacert); java.security.cert.Certificate cac = cf.generateCertificate(in1); in1.close();/*from w w w. jav a 2 s . c o m*/ FileInputStream in2 = new FileInputStream(lfcert); java.security.cert.Certificate lfc = cf.generateCertificate(in2); in2.close(); java.security.cert.Certificate[] cchain = { lfc, cac }; FileInputStream in3 = new FileInputStream(lfstore); KeyStore ks = KeyStore.getInstance("JKS"); ks.load(in3, lfstorepass); PrivateKey prk = (PrivateKey) ks.getKey("lf", lfkeypass); ks.setKeyEntry("lf_signed", prk, lfstorepass, cchain); FileOutputStream out4 = new FileOutputStream("lfnewstore"); ks.store(out4, "newpass".toCharArray()); out4.close(); }
From source file:ImportKey.java
/** * <p>/*from ww w. java 2 s . c om*/ * Takes two file names for a key and the certificate for the key, and * imports those into a keystore. Optionally it takes an alias for the key. * <p> * The first argument is the filename for the key. The key should be in * PKCS8-format. * <p> * The second argument is the filename for the certificate for the key. * <p> * If a third argument is given it is used as the alias. If missing, the key * is imported with the alias importkey * <p> * The name of the keystore file can be controlled by setting the keystore * property (java -Dkeystore=mykeystore). If no name is given, the file is * named <code>keystore.ImportKey</code> and placed in your home directory. * * @param args * [0] Name of the key file, [1] Name of the certificate file [2] * Alias for the key. **/ public static void main(String args[]) { // change this if you want another password by default String keypass = "password"; // change this if you want another alias by default String defaultalias = "tomcat"; // change this if you want another keystorefile by default String keystorename = null; // parsing command line input String keyfile = ""; String certfile = ""; if (args.length < 3 || args.length > 4) { System.out.println("Usage: java comu.ImportKey keystore keyfile certfile [alias]"); System.exit(0); } else { keystorename = args[0]; keyfile = args[1]; certfile = args[2]; if (args.length > 3) defaultalias = args[3]; } try { // initializing and clearing keystore KeyStore ks = KeyStore.getInstance("JKS", "SUN"); ks.load(null, keypass.toCharArray()); System.out.println("Using keystore-file : " + keystorename); ks.store(new FileOutputStream(keystorename), keypass.toCharArray()); ks.load(new FileInputStream(keystorename), keypass.toCharArray()); // loading Key InputStream fl = fullStream(keyfile); byte[] key = new byte[fl.available()]; KeyFactory kf = KeyFactory.getInstance("RSA"); fl.read(key, 0, fl.available()); fl.close(); PKCS8EncodedKeySpec keysp = new PKCS8EncodedKeySpec(key); PrivateKey ff = kf.generatePrivate(keysp); // loading CertificateChain CertificateFactory cf = CertificateFactory.getInstance("X.509"); InputStream certstream = fullStream(certfile); Collection c = cf.generateCertificates(certstream); Certificate[] certs = new Certificate[c.toArray().length]; if (c.size() == 1) { certstream = fullStream(certfile); System.out.println("One certificate, no chain."); Certificate cert = cf.generateCertificate(certstream); certs[0] = cert; } else { System.out.println("Certificate chain length: " + c.size()); certs = (Certificate[]) c.toArray(new Certificate[c.size()]); } // storing keystore ks.setKeyEntry(defaultalias, ff, keypass.toCharArray(), certs); System.out.println("Key and certificate stored."); System.out.println("Alias:" + defaultalias + " Password:" + keypass); ks.store(new FileOutputStream(keystorename), keypass.toCharArray()); } catch (Exception ex) { ex.printStackTrace(); } }
From source file:org.openanzo.security.keystore.TestSecretKeyEncoder.java
/** * Main method used to generate a keystore. Useful for bootstrapping the first time. * /*from w w w . j a v a 2 s .c o m*/ * @param args * @throws Exception */ public static void main(String[] args) throws Exception { File file = new File("testKeystore"); System.out.println("Generating new keystore to:" + file.getAbsolutePath()); KeyStore keyStore = KeyStore.getInstance("JCEKS"); keyStore.load(null, TEST_KEYSTORE_PASSWORD); KeyGenerator kgen = KeyGenerator.getInstance(ALGORITHM); Key key = kgen.generateKey(); keyStore.setKeyEntry(KEY_NAME, key, TEST_KEYSTORE_PASSWORD, new Certificate[0]); keyStore.store(FileUtils.openOutputStream(file), TEST_KEYSTORE_PASSWORD); System.out.println("Done generating keystore."); }
From source file:org.sipfoundry.commons.sipkeystorebuilder.sipkeystorebuilder.java
public static void main(String[] args) throws Exception { if (args.length != 1) { System.out.println(//from w w w . j a va 2 s . com "sipkeystorebuilder: creates '[sip or sip-web].keystore' (Java Key Store) and java truststore '[authority].jks"); System.out.println("[alias] will be set to the first CN value of the X509 certificate."); System.out.println("-------------------------------------------------------------------"); System.out.println("Usage: [sipX ssl directory]"); System.out.println("-------------------------------------------------------------------"); System.exit(1); } char[] password = "changeit".toCharArray(); final String auth = "authorities"; final String keySuffix = ".key"; final String certSuffix = ".crt"; final String keystoreSuffix = ".keystore"; final String truststoreSuffix = ".jks"; File ssldir = new File(args[0]); File authdir = new File(args[0] + "/" + auth); FilenameFilter keyFilter = new FilenameFilter() { public boolean accept(File dir, String name) { return name.endsWith(keySuffix); } }; if (ssldir.isDirectory()) { // Valid directory specified. Now scan for key and cert files to build the KeyStore. File[] keyfiles = ssldir.listFiles(keyFilter); for (int i = 0; i < keyfiles.length; i++) { // get the matching certificate file. String certPath = keyfiles[i].toString().replaceAll(keySuffix, certSuffix); File certFile = new File(certPath); if (certFile.exists()) { FileInputStream fin1 = new FileInputStream(keyfiles[i].toString()); byte[] bytes1 = Util.streamToBytes(fin1); FileInputStream fin2 = new FileInputStream(certFile.toString()); byte[] bytes2 = Util.streamToBytes(fin2); KeyStore SipXKeyStore = KeyStoreBuilder.build(bytes1, bytes2, password); File outks = new File(keyfiles[i].toString().replaceAll(keySuffix, keystoreSuffix)); FileOutputStream fout = new FileOutputStream(outks); SipXKeyStore.store(fout, password); fout.flush(); fout.close(); } } } if (authdir.isDirectory()) { // Valid authority directory specified. Now scan for cert files to build the TrustStore. File[] certFiles = authdir.listFiles(); TrustChain trustChain = new TrustChain(); for (int i = 0; i < certFiles.length; i++) { try { TrustMaterial trustCerts = new TrustMaterial(certFiles[i].toString()); trustChain.addTrustMaterial(trustCerts); } catch (IOException ex) { // skip adding CA. } catch (KeyStoreException ex) { // skip adding CA. } catch (GeneralSecurityException ex) { // skip adding CA. } } File outts = new File(args[0] + "/" + auth + truststoreSuffix); FileOutputStream fout = new FileOutputStream(outts); KeyStore trustKeyStore = trustChain.getUnifiedKeyStore(); trustKeyStore.store(fout, password); fout.flush(); fout.close(); } System.exit(0); }
From source file:com.streamreduce.util.CAGenerator.java
public static void main(String[] args) throws Exception { KeyStore store = KeyStore.getInstance("JKS"); // store.load(CAGenerator.class.getResourceAsStream("/mmc-keystore.jks"), "ion-mmc".toCharArray()); store.load(null);//w ww . ja v a 2 s. com KeyPair keypair = generateKeyPair(); X509Certificate cert = generateCACert(keypair); char[] password = "nodeable-agent".toCharArray(); store.setKeyEntry("nodeable", keypair.getPrivate(), password, new Certificate[] { cert }); store.store(new FileOutputStream("nodeable-keystore.jks"), password); byte[] certBytes = getCertificateAsBytes(cert); FileOutputStream output = new FileOutputStream("nodeable.crt"); IOUtils.copy(new ByteArrayInputStream(certBytes), output); output.close(); }
From source file:org.wso2.carbon.utils.security.KeyImporter.java
/** * sourcekeystore sourceStorepass keyalias targetstore targetStorePass * * @param args//from w ww . j a v a 2 s . c o m */ 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:org.apache.metron.dataservices.auth.AuthToken.java
public static void main(String[] args) throws Exception { Options options = new Options(); options.addOption("keystoreFile", true, "Keystore File"); options.addOption("keystorePassword", true, "Keystore Password"); options.addOption("authTokenAlias", true, ""); CommandLineParser parser = new GnuParser(); CommandLine cmd = parser.parse(options, args); try {/*w ww .j a va 2 s.c om*/ KeyStore ks = KeyStore.getInstance("JCEKS"); String keystorePassword = cmd.getOptionValue("keystorePassword"); String keystoreFile = cmd.getOptionValue("keystoreFile"); String authTokenAlias = cmd.getOptionValue("authTokenAlias"); ks.load(null, keystorePassword.toCharArray()); // generate a key and store it in the keystore... KeyGenerator keyGen = KeyGenerator.getInstance("AES"); SecretKey key = keyGen.generateKey(); KeyStore.ProtectionParameter protParam = new KeyStore.PasswordProtection( keystorePassword.toCharArray()); KeyStore.SecretKeyEntry skEntry = new KeyStore.SecretKeyEntry(key); ks.setEntry(authTokenAlias, skEntry, protParam); java.io.FileOutputStream fos = null; try { fos = new java.io.FileOutputStream(keystoreFile); ks.store(fos, keystorePassword.toCharArray()); } finally { if (fos != null) { fos.close(); } } System.out.println("done"); } catch (Exception e) { e.printStackTrace(); } }
From source file:PKCS12Import.java
public static void main(String[] args) throws Exception { if (args.length < 1) { System.err.println("usage: java PKCS12Import {pkcs12file} [newjksfile]"); System.exit(1);/*from ww w . java 2s .c o m*/ } File fileIn = new File(args[0]); File fileOut; if (args.length > 1) { fileOut = new File(args[1]); } else { fileOut = new File("newstore.jks"); } if (!fileIn.canRead()) { System.err.println("Unable to access input keystore: " + fileIn.getPath()); System.exit(2); } if (fileOut.exists() && !fileOut.canWrite()) { System.err.println("Output file is not writable: " + fileOut.getPath()); System.exit(2); } KeyStore kspkcs12 = KeyStore.getInstance("pkcs12"); KeyStore ksjks = KeyStore.getInstance("jks"); System.out.print("Enter input keystore passphrase: "); char[] inphrase = readPassphrase(); System.out.print("Enter output keystore passphrase: "); char[] outphrase = readPassphrase(); kspkcs12.load(new FileInputStream(fileIn), inphrase); ksjks.load((fileOut.exists()) ? new FileInputStream(fileOut) : null, outphrase); Enumeration eAliases = kspkcs12.aliases(); int n = 0; while (eAliases.hasMoreElements()) { String strAlias = (String) eAliases.nextElement(); System.err.println("Alias " + n++ + ": " + strAlias); if (kspkcs12.isKeyEntry(strAlias)) { System.err.println("Adding key for alias " + strAlias); Key key = kspkcs12.getKey(strAlias, inphrase); Certificate[] chain = kspkcs12.getCertificateChain(strAlias); ksjks.setKeyEntry(strAlias, key, outphrase, chain); } } OutputStream out = new FileOutputStream(fileOut); ksjks.store(out, outphrase); out.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) {/* ww w.ja va 2 s . com*/ 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[] {}); } } }