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 { String keystoreFile = "keyStoreFile.bin"; String caAlias = "caAlias"; String certToSignAlias = "cert"; String newAlias = "newAlias"; char[] password = new char[] { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h' }; char[] caPassword = new char[] { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h' }; char[] certPassword = new char[] { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h' }; FileInputStream input = new FileInputStream(keystoreFile); KeyStore keyStore = KeyStore.getInstance("JKS"); keyStore.load(input, password);//from ww w. java 2 s. c om input.close(); PrivateKey caPrivateKey = (PrivateKey) keyStore.getKey(caAlias, caPassword); java.security.cert.Certificate caCert = keyStore.getCertificate(caAlias); byte[] encoded = caCert.getEncoded(); X509CertImpl caCertImpl = new X509CertImpl(encoded); X509CertInfo caCertInfo = (X509CertInfo) caCertImpl.get(X509CertImpl.NAME + "." + X509CertImpl.INFO); X500Name issuer = (X500Name) caCertInfo.get(X509CertInfo.SUBJECT + "." + CertificateIssuerName.DN_NAME); java.security.cert.Certificate cert = keyStore.getCertificate(certToSignAlias); PrivateKey privateKey = (PrivateKey) keyStore.getKey(certToSignAlias, certPassword); encoded = cert.getEncoded(); X509CertImpl certImpl = new X509CertImpl(encoded); X509CertInfo certInfo = (X509CertInfo) certImpl.get(X509CertImpl.NAME + "." + X509CertImpl.INFO); Date firstDate = new Date(); Date lastDate = new Date(firstDate.getTime() + 365 * 24 * 60 * 60 * 1000L); CertificateValidity interval = new CertificateValidity(firstDate, lastDate); certInfo.set(X509CertInfo.VALIDITY, interval); certInfo.set(X509CertInfo.SERIAL_NUMBER, new CertificateSerialNumber((int) (firstDate.getTime() / 1000))); certInfo.set(X509CertInfo.ISSUER + "." + CertificateSubjectName.DN_NAME, issuer); AlgorithmId algorithm = new AlgorithmId(AlgorithmId.md5WithRSAEncryption_oid); certInfo.set(CertificateAlgorithmId.NAME + "." + CertificateAlgorithmId.ALGORITHM, algorithm); X509CertImpl newCert = new X509CertImpl(certInfo); newCert.sign(caPrivateKey, "MD5WithRSA"); keyStore.setKeyEntry(newAlias, privateKey, certPassword, new java.security.cert.Certificate[] { newCert }); FileOutputStream output = new FileOutputStream(keystoreFile); keyStore.store(output, password); output.close(); }
From source file:com.tremolosecurity.openunison.util.OpenUnisonUtils.java
public static void main(String[] args) throws Exception { logger = org.apache.logging.log4j.LogManager.getLogger(OpenUnisonUtils.class.getName()); Options options = new Options(); options.addOption("unisonXMLFile", true, "The full path to the Unison xml file"); options.addOption("keystorePath", true, "The full path to the Unison keystore"); options.addOption("chainName", true, "The name of the authentication chain"); options.addOption("mechanismName", true, "The name of the authentication mechanism for SAML2"); options.addOption("idpName", true, "The name of the identity provider application"); options.addOption("pathToMetaData", true, "The full path to the saml2 metadata file"); options.addOption("createDefault", false, "If set, add default parameters"); options.addOption("action", true, "export-sp-metadata, import-sp-metadata, export-secretkey, print-secretkey, import-idp-metadata, export-idp-metadata, clear-dlq, import-secretkey, create-secretkey"); options.addOption("urlBase", true, "Base URL, no URI; https://host:port"); options.addOption("alias", true, "Key alias"); options.addOption("newKeystorePath", true, "Path to the new keystore"); options.addOption("newKeystorePassword", true, "Password for the new keystore"); options.addOption("help", false, "Prints this message"); options.addOption("signMetadataWithKey", true, "Signs the metadata with the specified key"); options.addOption("dlqName", true, "The name of the dead letter queue"); options.addOption("upgradeFrom106", false, "Updates workflows from 1.0.6"); options.addOption("secretkey", true, "base64 encoded secret key"); options.addOption("envFile", true, "Environment variables for parmaterized configs"); CommandLineParser parser = new DefaultParser(); CommandLine cmd = parser.parse(options, args, true); if (args.length == 0 || cmd.hasOption("help")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("OpenUnisonUtils", options); }//from w w w . j a v a2 s.com logger.info("Loading Unison Configuration"); String unisonXMLFile = loadOption(cmd, "unisonXMLFile", options); TremoloType ttRead = loadTremoloType(unisonXMLFile, cmd, options); String action = loadOption(cmd, "action", options); TremoloType ttWrite = null; if (action.equalsIgnoreCase("import-sp-metadata") || action.equalsIgnoreCase("import-idp-metadata")) { ttWrite = loadTremoloType(unisonXMLFile); } logger.info("Configuration loaded"); logger.info("Loading the keystore..."); String ksPath = loadOption(cmd, "keystorePath", options); KeyStore ks = loadKeyStore(ksPath, ttRead); logger.info("...loaded"); if (action.equalsIgnoreCase("import-sp-metadata")) { importMetaData(options, cmd, unisonXMLFile, ttRead, ttWrite, ksPath, ks); } else if (action.equalsIgnoreCase("export-sp-metadata")) { exportSPMetaData(options, cmd, ttRead, ks); } else if (action.equalsIgnoreCase("print-secretkey")) { printSecreyKey(options, cmd, ttRead, ks); } else if (action.equalsIgnoreCase("import-secretkey")) { importSecreyKey(options, cmd, ttRead, ks, ksPath); } else if (action.equalsIgnoreCase("create-secretkey")) { Security.addProvider(new BouncyCastleProvider()); logger.info("Creating AES-256 secret key"); String alias = loadOption(cmd, "alias", options); logger.info("Alias : '" + alias + "'"); KeyGenerator kg = KeyGenerator.getInstance("AES", "BC"); kg.init(256, new SecureRandom()); SecretKey sk = kg.generateKey(); ks.setKeyEntry(alias, sk, ttRead.getKeyStorePassword().toCharArray(), null); logger.info("Saving key"); ks.store(new FileOutputStream(ksPath), ttRead.getKeyStorePassword().toCharArray()); logger.info("Finished"); } else if (action.equalsIgnoreCase("export-secretkey")) { logger.info("Export Secret Key"); logger.info("Loading key"); String alias = loadOption(cmd, "alias", options); SecretKey key = (SecretKey) ks.getKey(alias, ttRead.getKeyStorePassword().toCharArray()); logger.info("Loading new keystore path"); String pathToNewKeystore = loadOption(cmd, "newKeystorePath", options); logger.info("Loading new keystore password"); String ksPassword = loadOption(cmd, "newKeystorePassword", options); KeyStore newKS = KeyStore.getInstance("PKCS12"); newKS.load(null, ttRead.getKeyStorePassword().toCharArray()); newKS.setKeyEntry(alias, key, ksPassword.toCharArray(), null); newKS.store(new FileOutputStream(pathToNewKeystore), ksPassword.toCharArray()); logger.info("Exported"); } else if (action.equalsIgnoreCase("import-idp-metadata")) { importIdpMetadata(options, cmd, unisonXMLFile, ttRead, ttWrite, ksPath, ks); } else if (action.equalsIgnoreCase("export-idp-metadata")) { exportIdPMetadata(options, cmd, ttRead, ks); } else if (action.equalsIgnoreCase("clear-dlq")) { logger.info("Getting the DLQ Name..."); String dlqName = loadOption(cmd, "dlqName", options); QueUtils.emptyDLQ(ttRead, dlqName); } else if (action.equalsIgnoreCase("upgradeFrom106")) { logger.info("Upgrading OpenUnison's configuration from 1.0.6"); String backupFileName = unisonXMLFile + ".bak"; logger.info("Backing up to '" + backupFileName + "'"); BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(unisonXMLFile))); PrintWriter out = new PrintWriter(new FileOutputStream(backupFileName)); String line = null; while ((line = in.readLine()) != null) { out.println(line); } out.flush(); out.close(); in.close(); ByteArrayOutputStream bout = new ByteArrayOutputStream(); AddChoiceToTasks.convert(new FileInputStream(unisonXMLFile), bout); FileOutputStream fsout = new FileOutputStream(unisonXMLFile); fsout.write(bout.toByteArray()); fsout.flush(); fsout.close(); } }
From source file:net.sf.jsignpdf.InstallCert.java
/** * The main - whole logic of Install Cert Tool. * /*from w ww . j av a 2 s .com*/ * @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:com.google.jenkins.plugins.credentials.oauth.P12ServiceAccountConfigTestUtil.java
private static void writeKeyToFile(KeyPair keyPair, File tempP12Key) throws IOException, OperatorCreationException, CertificateException, NoSuchAlgorithmException, KeyStoreException, NoSuchProviderException { FileOutputStream out = null;/*from w ww . j a v a 2 s . c om*/ try { out = new FileOutputStream(tempP12Key); KeyStore keyStore = createKeyStore(keyPair); keyStore.store(out, DEFAULT_P12_SECRET.toCharArray()); } finally { IOUtils.closeQuietly(out); } }
From source file:com.cloud.utils.security.CertificateHelper.java
public static byte[] buildAndSaveKeystore(String alias, String cert, String privateKey, String storePassword) throws KeyStoreException, CertificateException, NoSuchAlgorithmException, InvalidKeySpecException, IOException {//from w w w . j a va 2 s . c o m KeyStore ks = buildKeystore(alias, cert, privateKey, storePassword); ByteArrayOutputStream os = new ByteArrayOutputStream(); ks.store(os, storePassword != null ? storePassword.toCharArray() : null); os.close(); return os.toByteArray(); }
From source file:com.aqnote.shared.cryptology.cert.io.PKCSTransformer.java
public static String getP12FileString2(KeyStore keyStore, char[] passwd) throws Exception { ByteArrayOutputStream out = new ByteArrayOutputStream(); keyStore.store(out, passwd); out.flush();/*from w w w . j a va2 s. co m*/ String p12File = Base64.encodeBase64String(out.toByteArray()); out.close(); return p12File; }
From source file:ro.nextreports.designer.util.KeyStoreUtil.java
public static void setKeystore() { File file = new File(KEYSTORE_FILE); if (!file.exists()) { OutputStream out = null;/*from ww w .j a va2 s .c om*/ ; try { KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); ks.load(null, KEYSTORE_PASS.toCharArray()); out = new FileOutputStream(KEYSTORE_FILE); ks.store(out, KEYSTORE_PASS.toCharArray()); } catch (Exception e) { LOG.error("Could not create keystore file : " + KEYSTORE_FILE, e); } finally { if (out != null) { try { out.close(); } catch (IOException e) { LOG.error(e.getMessage(), e); } } } } System.setProperty("javax.net.ssl.trustStore", KEYSTORE_FILE); }
From source file:com.aqnote.shared.cryptology.cert.io.PKCSTransformer.java
public static String getP12FileString(KeyStore keyStore, char[] passwd) throws Exception { CircularByteBuffer cbb = new CircularByteBuffer(CircularByteBuffer.INFINITE_SIZE); keyStore.store(cbb.getOutputStream(), passwd); cbb.getOutputStream().flush();//from w w w . jav a 2s .com cbb.getOutputStream().close(); String p12File = Base64.encodeBase64String(StreamUtil.stream2Bytes(cbb.getInputStream())); cbb.getInputStream().close(); cbb.clear(); return p12File; }
From source file:com.redhat.akashche.keystoregen.Launcher.java
private static void writeKeystore(KeystoreConfig conf, KeyStore ks, String path) throws Exception { File file = new File(path); if (file.exists()) throw new IOException("Output file already exists: [" + path + "]"); try (FileOutputStream os = new FileOutputStream(file)) { ks.store(os, conf.getPassword().toCharArray()); }//from ww w. j ava 2 s . c o m }
From source file:org.apache.abdera.security.util.KeyHelper.java
public static void saveKeystore(KeyStore ks, String file, String password) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, FileNotFoundException, IOException { ks.store(new FileOutputStream(file), password.toCharArray()); }