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.bankinterface.util.KeyStoreUtil.java
public static void importPKCS8CertChain(KeyStore ks, String alias, byte[] keyBytes, String keyPass, byte[] certChain) throws InvalidKeySpecException, NoSuchAlgorithmException, CertificateException, KeyStoreException { // load the private key KeyFactory kf = KeyFactory.getInstance("RSA"); PKCS8EncodedKeySpec keysp = new PKCS8EncodedKeySpec(keyBytes); PrivateKey pk = kf.generatePrivate(keysp); // load the cert chain CertificateFactory cf = CertificateFactory.getInstance("X.509"); ByteArrayInputStream bais = new ByteArrayInputStream(certChain); Collection<? extends Certificate> certCol = cf.generateCertificates(bais); Certificate[] certs = new Certificate[certCol.toArray().length]; if (certCol.size() == 1) { logger.info("Single certificate; no chain"); bais = new ByteArrayInputStream(certChain); Certificate cert = cf.generateCertificate(bais); certs[0] = cert;//from www . j a va2 s. c o m } else { logger.info("Certificate chain length : " + certCol.size()); certs = certCol.toArray(new Certificate[certCol.size()]); } ks.setKeyEntry(alias, pk, keyPass.toCharArray(), certs); }
From source file:com.tremolosecurity.openunison.util.OpenUnisonUtils.java
private static void importSecreyKey(Options options, CommandLine cmd, TremoloType tt, KeyStore ks, String ksPath) throws KeyStoreException, Base64DecodingException, NoSuchAlgorithmException, CertificateException, FileNotFoundException, IOException { String alias = loadOption(cmd, "alias", options); logger.info("importing to " + alias); String base64Key = loadOption(cmd, "secretkey", options); SecretKey sc = new SecretKeySpec(Base64.decode(base64Key), "AES"); ks.setKeyEntry(alias, sc, tt.getKeyStorePassword().toCharArray(), null); ks.store(new FileOutputStream(ksPath), tt.getKeyStorePassword().toCharArray()); logger.info("import complete"); }
From source file:com.zacwolf.commons.crypto.Crypter_AES.java
@Override public final void addToKeystore(final KeyStore keystore, final char[] keystorepass, final String alias) throws KeyStoreException, CertificateException { keystore.setKeyEntry(alias == null ? super.type : alias, this.secretkey, keystorepass, null); }
From source file:org.apache.accumulo.test.util.CertUtils.java
public void createSelfSignedCert(File targetKeystoreFile, String keyName, String keystorePassword) throws KeyStoreException, CertificateException, NoSuchAlgorithmException, IOException, OperatorCreationException, AccumuloSecurityException, NoSuchProviderException { if (targetKeystoreFile.exists()) { throw new FileExistsException(targetKeystoreFile); }//from ww w.j ava 2s .co m KeyPair kp = generateKeyPair(); X509CertificateObject cert = generateCert(keyName, kp, true, kp.getPublic(), kp.getPrivate()); char[] password = keystorePassword.toCharArray(); KeyStore keystore = KeyStore.getInstance(keystoreType); keystore.load(null, null); keystore.setCertificateEntry(keyName + "Cert", cert); keystore.setKeyEntry(keyName + "Key", kp.getPrivate(), password, new Certificate[] { cert }); try (FileOutputStream fos = new FileOutputStream(targetKeystoreFile)) { keystore.store(fos, password); } }
From source file:org.apache.drill.exec.server.rest.WebServer.java
/** * Create an HTTPS connector for given jetty server instance. If the admin has specified keystore/truststore settings * they will be used else a self-signed certificate is generated and used. * * @return Initialized {@link ServerConnector} for HTTPS connectios. * @throws Exception/*from w ww. j av a 2 s . com*/ */ private ServerConnector createHttpsConnector() throws Exception { logger.info("Setting up HTTPS connector for web server"); final SslContextFactory sslContextFactory = new SslContextFactory(); if (config.hasPath(ExecConstants.HTTP_KEYSTORE_PATH) && !Strings.isNullOrEmpty(config.getString(ExecConstants.HTTP_KEYSTORE_PATH))) { logger.info("Using configured SSL settings for web server"); sslContextFactory.setKeyStorePath(config.getString(ExecConstants.HTTP_KEYSTORE_PATH)); sslContextFactory.setKeyStorePassword(config.getString(ExecConstants.HTTP_KEYSTORE_PASSWORD)); // TrustStore and TrustStore password are optional if (config.hasPath(ExecConstants.HTTP_TRUSTSTORE_PATH)) { sslContextFactory.setTrustStorePath(config.getString(ExecConstants.HTTP_TRUSTSTORE_PATH)); if (config.hasPath(ExecConstants.HTTP_TRUSTSTORE_PASSWORD)) { sslContextFactory .setTrustStorePassword(config.getString(ExecConstants.HTTP_TRUSTSTORE_PASSWORD)); } } } else { logger.info("Using generated self-signed SSL settings for web server"); final SecureRandom random = new SecureRandom(); // Generate a private-public key pair final KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); keyPairGenerator.initialize(1024, random); final KeyPair keyPair = keyPairGenerator.generateKeyPair(); final DateTime now = DateTime.now(); // Create builder for certificate attributes final X500NameBuilder nameBuilder = new X500NameBuilder(BCStyle.INSTANCE) .addRDN(BCStyle.OU, "Apache Drill (auth-generated)") .addRDN(BCStyle.O, "Apache Software Foundation (auto-generated)") .addRDN(BCStyle.CN, workManager.getContext().getEndpoint().getAddress()); final Date notBefore = now.minusMinutes(1).toDate(); final Date notAfter = now.plusYears(5).toDate(); final BigInteger serialNumber = new BigInteger(128, random); // Create a certificate valid for 5years from now. final X509v3CertificateBuilder certificateBuilder = new JcaX509v3CertificateBuilder(nameBuilder.build(), // attributes serialNumber, notBefore, notAfter, nameBuilder.build(), keyPair.getPublic()); // Sign the certificate using the private key final ContentSigner contentSigner = new JcaContentSignerBuilder("SHA256WithRSAEncryption") .build(keyPair.getPrivate()); final X509Certificate certificate = new JcaX509CertificateConverter() .getCertificate(certificateBuilder.build(contentSigner)); // Check the validity certificate.checkValidity(now.toDate()); // Make sure the certificate is self-signed. certificate.verify(certificate.getPublicKey()); // Generate a random password for keystore protection final String keyStorePasswd = RandomStringUtils.random(20); final KeyStore keyStore = KeyStore.getInstance("JKS"); keyStore.load(null, null); keyStore.setKeyEntry("DrillAutoGeneratedCert", keyPair.getPrivate(), keyStorePasswd.toCharArray(), new java.security.cert.Certificate[] { certificate }); sslContextFactory.setKeyStore(keyStore); sslContextFactory.setKeyStorePassword(keyStorePasswd); } final HttpConfiguration httpsConfig = new HttpConfiguration(); httpsConfig.addCustomizer(new SecureRequestCustomizer()); // SSL Connector final ServerConnector sslConnector = new ServerConnector(embeddedJetty, new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()), new HttpConnectionFactory(httpsConfig)); sslConnector.setPort(config.getInt(ExecConstants.HTTP_PORT)); return sslConnector; }
From source file:org.apache.accumulo.test.util.CertUtils.java
public void createSignedCert(File targetKeystoreFile, String keyName, String keystorePassword, String signerKeystorePath, String signerKeystorePassword) throws KeyStoreException, CertificateException, NoSuchAlgorithmException, IOException, OperatorCreationException, AccumuloSecurityException, UnrecoverableKeyException, NoSuchProviderException { KeyStore signerKeystore = KeyStore.getInstance(keystoreType); char[] signerPasswordArray = signerKeystorePassword.toCharArray(); try (FileInputStream fis = new FileInputStream(signerKeystorePath)) { signerKeystore.load(fis, signerPasswordArray); }/*from w w w .j a v a 2 s.c o m*/ Certificate signerCert = findCert(signerKeystore); PrivateKey signerKey = findPrivateKey(signerKeystore, signerPasswordArray); KeyPair kp = generateKeyPair(); X509CertificateObject cert = generateCert(keyName, kp, false, signerCert.getPublicKey(), signerKey); char[] password = keystorePassword.toCharArray(); KeyStore keystore = KeyStore.getInstance(keystoreType); keystore.load(null, null); keystore.setCertificateEntry(keyName + "Cert", cert); keystore.setKeyEntry(keyName + "Key", kp.getPrivate(), password, new Certificate[] { cert, signerCert }); try (FileOutputStream fos = new FileOutputStream(targetKeystoreFile)) { keystore.store(fos, password); } }
From source file:com.trsst.Command.java
public static final void writeKeyPairToFile(KeyPair keyPair, X509Certificate cert, String alias, File file, char[] pwd) { FileInputStream input = null; FileOutputStream output = null; try {//ww w .ja v a2 s . c om KeyStore keyStore = KeyStore.getInstance("PKCS12"); if (file.exists()) { input = new FileInputStream(file); keyStore.load(new FileInputStream(file), pwd); input.close(); } else { keyStore.load(null); // weird but required } // save my private key keyStore.setKeyEntry(alias, keyPair.getPrivate(), pwd, new X509Certificate[] { cert }); // store away the keystore output = new java.io.FileOutputStream(file); keyStore.store(output, pwd); output.flush(); } catch (Exception e) { log.error("Error while storing key: " + e.getMessage(), e); } finally { if (input != null) { try { input.close(); } catch (IOException e) { // ignore while closing log.trace("Error while closing: " + e.getMessage(), e); } } if (output != null) { try { output.close(); } catch (IOException e) { // ignore while closing log.trace("Error while closing: " + e.getMessage(), e); } } } }
From source file:org.apache.drill.cv.exec.server.rest.CvDrillWebServer.java
/** * Create an HTTPS connector for given jetty server instance. If the admin has specified * keystore/truststore settings they will be used else a self-signed certificate is generated and * used./*from w w w.j av a 2s . c o m*/ * * @return Initialized {@link ServerConnector} for HTTPS connectios. * @throws Exception */ private ServerConnector createHttpsConnector() throws Exception { CvDrillWebServer.logger.info("Setting up HTTPS connector for web server"); final SslContextFactory sslContextFactory = new SslContextFactory(); if (config.hasPath(ExecConstants.HTTP_KEYSTORE_PATH) && !Strings.isNullOrEmpty(config.getString(ExecConstants.HTTP_KEYSTORE_PATH))) { CvDrillWebServer.logger.info("Using configured SSL settings for web server"); sslContextFactory.setKeyStorePath(config.getString(ExecConstants.HTTP_KEYSTORE_PATH)); sslContextFactory.setKeyStorePassword(config.getString(ExecConstants.HTTP_KEYSTORE_PASSWORD)); // TrustStore and TrustStore password are optional if (config.hasPath(ExecConstants.HTTP_TRUSTSTORE_PATH)) { sslContextFactory.setTrustStorePath(config.getString(ExecConstants.HTTP_TRUSTSTORE_PATH)); if (config.hasPath(ExecConstants.HTTP_TRUSTSTORE_PASSWORD)) { sslContextFactory .setTrustStorePassword(config.getString(ExecConstants.HTTP_TRUSTSTORE_PASSWORD)); } } } else { CvDrillWebServer.logger.info("Using generated self-signed SSL settings for web server"); final SecureRandom random = new SecureRandom(); // Generate a private-public key pair final KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); keyPairGenerator.initialize(1024, random); final KeyPair keyPair = keyPairGenerator.generateKeyPair(); final DateTime now = DateTime.now(); // Create builder for certificate attributes final X500NameBuilder nameBuilder = new X500NameBuilder(BCStyle.INSTANCE) .addRDN(BCStyle.OU, "Apache Drill (auth-generated)") .addRDN(BCStyle.O, "Apache Software Foundation (auto-generated)") .addRDN(BCStyle.CN, workManager.getContext().getEndpoint().getAddress()); final Date notBefore = now.minusMinutes(1).toDate(); final Date notAfter = now.plusYears(5).toDate(); final BigInteger serialNumber = new BigInteger(128, random); // Create a certificate valid for 5years from now. final X509v3CertificateBuilder certificateBuilder = new JcaX509v3CertificateBuilder(nameBuilder.build(), // attributes serialNumber, notBefore, notAfter, nameBuilder.build(), keyPair.getPublic()); // Sign the certificate using the private key final ContentSigner contentSigner = new JcaContentSignerBuilder("SHA256WithRSAEncryption") .build(keyPair.getPrivate()); final X509Certificate certificate = new JcaX509CertificateConverter() .getCertificate(certificateBuilder.build(contentSigner)); // Check the validity certificate.checkValidity(now.toDate()); // Make sure the certificate is self-signed. certificate.verify(certificate.getPublicKey()); // Generate a random password for keystore protection final String keyStorePasswd = RandomStringUtils.random(20); final KeyStore keyStore = KeyStore.getInstance("JKS"); keyStore.load(null, null); keyStore.setKeyEntry("DrillAutoGeneratedCert", keyPair.getPrivate(), keyStorePasswd.toCharArray(), new java.security.cert.Certificate[] { certificate }); sslContextFactory.setKeyStore(keyStore); sslContextFactory.setKeyStorePassword(keyStorePasswd); } final HttpConfiguration httpsConfig = new HttpConfiguration(); httpsConfig.addCustomizer(new SecureRequestCustomizer()); // SSL Connector final ServerConnector sslConnector = new ServerConnector(embeddedJetty, new SslConnectionFactory(sslContextFactory, HttpVersion.HTTP_1_1.asString()), new HttpConnectionFactory(httpsConfig)); sslConnector.setPort(getWebserverPort()); return sslConnector; }
From source file:org.cesecore.keys.util.KeyTools.java
/** * Creates JKS-file that can be used with JDK. The alias for the private key is set to 'privateKey' and the private key password is null. * /*from w ww . j a v a2 s . c o m*/ * @param alias * the alias used for the key entry * @param privKey * RSA private key * @param password * user's password * @param cert * user certificate * @param cachain * CA-certificate chain or null if only one cert in chain, in that case use 'cert'. * * @return KeyStore containing JKS-keystore * * @exception Exception * if input parameters are not OK or certificate generation fails */ public static KeyStore createJKS(final String alias, final PrivateKey privKey, final String password, final X509Certificate cert, final Certificate[] cachain) throws Exception { if (log.isTraceEnabled()) { log.trace(">createJKS: alias=" + alias + ", privKey, cert=" + CertTools.getSubjectDN(cert) + ", cachain.length=" + ((cachain == null) ? 0 : cachain.length)); } final String caAlias = "cacert"; // Certificate chain if (cert == null) { throw new IllegalArgumentException("Parameter cert cannot be null."); } int len = 1; if (cachain != null) { len += cachain.length; } final Certificate[] chain = new Certificate[len]; chain[0] = cert; if (cachain != null) { System.arraycopy(cachain, 0, chain, 1, cachain.length); } // store the key and the certificate chain final KeyStore store = KeyStore.getInstance("JKS"); store.load(null, null); // First load the key entry final X509Certificate[] usercert = new X509Certificate[1]; usercert[0] = cert; store.setKeyEntry(alias, privKey, password.toCharArray(), usercert); // Add the root cert as trusted if (cachain != null) { if (!CertTools.isSelfSigned(cachain[cachain.length - 1])) { throw new IllegalArgumentException("Root cert is not self-signed."); } store.setCertificateEntry(caAlias, cachain[cachain.length - 1]); } // Set the complete chain log.debug("Storing cert chain of length " + chain.length); store.setKeyEntry(alias, privKey, password.toCharArray(), chain); if (log.isTraceEnabled()) { log.trace("<createJKS: alias=" + alias + ", privKey, cert=" + CertTools.getSubjectDN(cert) + ", cachain.length=" + ((cachain == null) ? 0 : cachain.length)); } return store; }