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:edu.washington.shibboleth.attribute.resolver.provider.dataConnector.RwsDataConnector.java
/** * This sets the key managers that will be used for all TLS and SSL connections to the ldap. * /* w w w. j a va 2 s . c o m*/ * @see #clearCache() * @see #initializeHttpPool() * @see #setSslSocketFactory(SSLSocketFactory) * * @param kc <code>X509Credential</code> to create KeyManagers with */ public void setSslKeyManagers(X509Credential kc) { if (kc != null) { try { KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType()); keystore.load(null, null); keystore.setKeyEntry("ldap_tls_client_auth", kc.getPrivateKey(), "changeit".toCharArray(), kc.getEntityCertificateChain().toArray(new X509Certificate[0])); kmf.init(keystore, "changeit".toCharArray()); sslKeyManagers = kmf.getKeyManagers(); } catch (GeneralSecurityException e) { log.error("Error initializing key managers", e); } catch (IOException e) { log.error("Error initializing key managers", e); } } }
From source file:org.texai.x509.X509Utils.java
/** Generates the X.509 security information. * * @param keyPair the key pair for the generated certificate * @param issuerPrivateKey the issuer's private key * @param issuerCertificate the issuer's certificate * @param uid the generated certificate's subject UID * @param keystorePassword the keystore password * @param isJCEUnlimitedStrengthPolicy the indicator whether the generated X.509 security information will be * hosted on a system with unlimited strength policy * @param domainComponent the domain component * @return the X509 security information *//* w ww . j a v a 2 s . co m*/ public static X509SecurityInfo generateX509SecurityInfo(final KeyPair keyPair, final PrivateKey issuerPrivateKey, final X509Certificate issuerCertificate, final UUID uid, final char[] keystorePassword, final boolean isJCEUnlimitedStrengthPolicy, final String domainComponent) { //Preconditions assert keyPair != null : "keyPair must not be null"; assert issuerPrivateKey != null : "issuerPrivateKey must not be null"; assert issuerCertificate != null : "issuerCertificate must not be null"; assert uid != null : "uid must not be null"; assert keystorePassword != null : "keystorePassword must not be null"; try { final X509Certificate x509Certificate = generateX509Certificate(keyPair.getPublic(), issuerPrivateKey, issuerCertificate, uid, domainComponent); assert X509Utils.isJCEUnlimitedStrengthPolicy(); final KeyStore keyStore; if (isJCEUnlimitedStrengthPolicy) { keyStore = KeyStore.getInstance("UBER", BOUNCY_CASTLE_PROVIDER); } else { keyStore = KeyStore.getInstance("JCEKS"); } keyStore.load(null, null); keyStore.setKeyEntry(X509Utils.ENTRY_ALIAS, keyPair.getPrivate(), keystorePassword, new Certificate[] { x509Certificate, X509Utils.getRootX509Certificate() }); return new X509SecurityInfo(X509Utils.getTruststore(), keyStore, keystorePassword, null); } catch (NoSuchProviderException | NoSuchAlgorithmException | SignatureException | InvalidKeyException | IOException | KeyStoreException | CertificateException ex) { throw new TexaiException(ex); } }
From source file:com.gamesalutes.utils.EncryptUtils.java
/** * Creates an <code>SSLContext</code> that uses the specified trusted certificates. * //from ww w . j ava 2 s. co m * @param protocol the {@link TransportSecurityProtocol} to use for the context * @param trustedCerts certificates to import into the <code>SSLContext</code> or <code>null</code> * to accept all issuers * @param privateKey the client key to authenticate the client with the server * @return the created <code>SSLContext</code> * @throws Exception if error occurs during the process of creating the context */ public static SSLContext createSSLContext(TransportSecurityProtocol protocol, PrivateKey privateKey, java.security.cert.X509Certificate... trustedCerts) throws Exception { if (trustedCerts != null && trustedCerts.length == 0) throw new IllegalArgumentException("trustedCerts is empty"); X509TrustManager defaultManager = null; KeyManager[] keyManagers = null; KeyStore keyStore = null; if (privateKey != null || trustedCerts != null) { // create a new key store instance that will install the certificates // and/or the private keys keyStore = KeyStore.getInstance(JKS_TYPE); keyStore.load(null, null); } // import the certs if (trustedCerts != null) { // set up the key manager for the certificates javax.net.ssl.TrustManagerFactory trustFact = javax.net.ssl.TrustManagerFactory .getInstance(KEY_MANAGEMENT_ALG_SUN_X509); // install the certificates in the key store and give them a unique alias int imported = 0; for (java.security.cert.X509Certificate cert : trustedCerts) { if (cert != null) keyStore.setCertificateEntry("cert" + ++imported, cert); } if (imported == 0) throw new IllegalArgumentException("no non-null certs in trustedCerts"); // add the certs to the trust factory trustFact.init(keyStore); // get a default trust manager TrustManager[] tms = trustFact.getTrustManagers(); if (tms != null && tms.length >= 1) defaultManager = (X509TrustManager) tms[0]; } // import the private key if (privateKey != null) { keyStore.setKeyEntry("client", privateKey, null, null); KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(privateKey.getAlgorithm()); kmfactory.init(keyStore, null); keyManagers = kmfactory.getKeyManagers(); } //create the SSL context based on these parameters SSLContext sslContext = SSLContext.getInstance(protocol.toString()); // use a CertX509TrustManager since default one will still fail validation for // self-signed certs sslContext.init(keyManagers, new TrustManager[] { trustedCerts != null ? new CertX509TrustManager(defaultManager, trustedCerts) : new CertX509TrustManager() }, null); return sslContext; }
From source file:org.signserver.server.cryptotokens.KeystoreCryptoToken.java
@Override public void importCertificateChain(final List<Certificate> certChain, final String alias, final char[] authCode, final Map<String, Object> params, final IServices services) throws CryptoTokenOfflineException, IllegalArgumentException { if (certChain.size() < 1) { throw new IllegalArgumentException("Certificate chain can not be empty"); }//from w w w .j a v a 2 s. c o m try { final KeyStore keyStore = getKeyStore(); final Key key = keyStore.getKey(alias, authCode != null ? authCode : authenticationCode); CryptoTokenHelper.ensureNewPublicKeyMatchesOld(keyStore, alias, certChain.get(0)); keyStore.setKeyEntry(alias, key, authCode != null ? authCode : authenticationCode, certChain.toArray(new Certificate[0])); // persist keystore OutputStream out = null; if (!TYPE_INTERNAL.equalsIgnoreCase(keystoretype)) { out = new FileOutputStream(new File(keystorepath)); } else { // use internal worker data out = new ByteArrayOutputStream(); } keyStore.store(out, authenticationCode); if (TYPE_INTERNAL.equalsIgnoreCase(keystoretype)) { final byte[] data = ((ByteArrayOutputStream) out).toByteArray(); getWorkerSession().setKeystoreData(new AdminInfo("Internal", null, null), this.workerId, data); } // update in-memory representation KeyEntry entry = getKeyEntry(alias); final Certificate signingCert = certChain.get(0); if (entry == null) { entry = new KeyEntry(); } entry.setCertificate(signingCert); entry.setCertificateChain(certChain); } catch (Exception e) { throw new CryptoTokenOfflineException(e); } }
From source file:edu.internet2.middleware.subject.provider.LdapPEMSocketFactory.java
protected void initManagers() { // trust managers try {/*from w ww . ja v a 2 s .c o m*/ X509Certificate cert = null; if (caFilename != null) cert = readCertificate(caFilename); KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); ks.load(null, null); ks.setCertificateEntry("CACERT", cert); TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(ks); trustManagers = tmf.getTrustManagers(); } catch (Exception e) { log.error("ldap source cacert error: " + e); } // key managers if (certFilename != null && keyFilename != null) { char[] pw = new char[] { 0 }; try { X509Certificate cert = readCertificate(certFilename); PKCS1 pkcs = new PKCS1(); PrivateKey key = pkcs.readKey(keyFilename); KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); ks.load(null, null); X509Certificate[] chain = new X509Certificate[1]; chain[0] = cert; ks.setKeyEntry("CERT", (Key) key, pw, chain); KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmf.init(ks, pw); keyManagers = kmf.getKeyManagers(); } catch (Exception e) { log.error("ldap source cert/key error: " + e); } } }
From source file:edu.vt.middleware.crypt.KeyStoreCli.java
/** * Imports a certificate or key pair into the keystore. * * @param line Parsed command line arguments container. * * @throws Exception On errors./* w ww. j a v a2s . c o m*/ */ protected void doImport(final CommandLine line) throws Exception { validateOptions(line); final KeyStore store = readKeyStore(line); final String alias = line.getOptionValue(OPT_ALIAS); final File certFile = new File(line.getOptionValue(OPT_CERT)); if (line.hasOption(OPT_KEY)) { final File keyFile = new File(line.getOptionValue(OPT_KEY)); final char[] passChars = line.getOptionValue(OPT_PASS).toCharArray(); final PrivateKey key = CryptReader.readPrivateKey(keyFile); final Certificate[] chain = CryptReader.readCertificateChain(certFile); System.err.println("Read certificate chain of length " + chain.length + ":"); for (int i = 0; i < chain.length; i++) { System.out.println("===== Certificate [" + i + "] ====="); printCertificate(chain[i]); } store.setKeyEntry(alias, key, passChars, chain); System.err.println("Imported key entry " + alias); } else { final Certificate cert = CryptReader.readCertificate(certFile); System.err.println("Read certificate:"); printCertificate(cert); store.setCertificateEntry(alias, cert); System.err.println("Imported trusted cert entry " + alias); } final OutputStream os = new FileOutputStream(new File(line.getOptionValue(OPT_STORE))); try { store.store(os, line.getOptionValue(OPT_PASS).toCharArray()); } finally { os.close(); } }
From source file:net.solarnetwork.node.setup.impl.DefaultKeystoreService.java
private X509Certificate createSelfSignedCertificate(KeyStore keyStore, String dn, String alias) { try {/*from ww w. j a va2s.c om*/ // create new key pair for the node KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); keyGen.initialize(keySize, new SecureRandom()); KeyPair keypair = keyGen.generateKeyPair(); PublicKey publicKey = keypair.getPublic(); PrivateKey privateKey = keypair.getPrivate(); Certificate cert = certificateService.generateCertificate(dn, publicKey, privateKey); keyStore.setKeyEntry(alias, privateKey, getKeyStorePassword().toCharArray(), new Certificate[] { cert }); saveKeyStore(keyStore); return (X509Certificate) cert; } catch (NoSuchAlgorithmException e) { throw new CertificateException("Error setting up node key pair", e); } catch (KeyStoreException e) { throw new CertificateException("Error setting up node key pair", e); } }
From source file:org.lockss.util.KeyStoreUtil.java
private static void initializeKeyStore(KeyStore keyStore, Configuration config) throws CertificateException, IOException, InvalidKeyException, KeyStoreException, NoSuchAlgorithmException, NoSuchProviderException, SignatureException, UnrecoverableKeyException { String keyAlias = config.get(PROP_KEY_ALIAS, DEFAULT_KEY_ALIAS); String certAlias = config.get(PROP_CERT_ALIAS, DEFAULT_CERT_ALIAS); String keyAlgName = config.get(PROP_KEY_ALGORITHM, DEFAULT_KEY_ALGORITHM); String sigAlgName = config.get(PROP_SIG_ALGORITHM, DEFAULT_SIG_ALGORITHM); String keyStorePassword = config.get(PROP_KEYSTORE_PASSWORD); String keyPassword = config.get(PROP_KEY_PASSWORD); int keyBits = config.getInt(PROP_KEY_BITS, DEFAULT_KEY_BITS); long expireIn = config.getTimeInterval(PROP_EXPIRE_IN, DEFAULT_EXPIRE_IN); String x500String = config.get(PROP_X500_NAME, DEFAULT_X500_NAME); CertAndKeyGen keypair = new CertAndKeyGen(keyAlgName, sigAlgName); keypair.generate(keyBits);//from w ww . ja v a2 s . com PrivateKey privKey = keypair.getPrivateKey(); log.debug3("PrivKey: " + privKey.getAlgorithm() + " " + privKey.getFormat()); X509Certificate[] chain = new X509Certificate[1]; X500Name x500Name = new X500Name(x500String); chain[0] = keypair.getSelfCertificate(x500Name, expireIn); log.debug3("Certificate: " + chain[0].toString()); keyStore.load(null, keyStorePassword.toCharArray()); keyStore.setCertificateEntry(certAlias, chain[0]); keyStore.setKeyEntry(keyAlias, privKey, keyPassword.toCharArray(), chain); Key myKey = keyStore.getKey(keyAlias, keyPassword.toCharArray()); log.debug("MyKey: " + myKey.getAlgorithm() + " " + myKey.getFormat()); }
From source file:com.wandrell.util.ksgen.BouncyCastleKeyStoreFactory.java
@Override protected final void addCertificate(final KeyStore kstore, final String password, final String alias, final String issuer) throws NoSuchAlgorithmException, NoSuchProviderException, InvalidKeyException, OperatorCreationException, CertificateException, IOException, KeyStoreException, SignatureException { final KeyPair keypair; // Key pair for the certificate final Certificate certificate; // Generated certificate final Certificate[] chain; // Certificate chain // Creates a key pair keypair = getKeyPair();/*from w w w.j a v a2 s . c o m*/ // Creates a certificate certificate = getCertificate(keypair, issuer); // Creates the certificates chain chain = new Certificate[] { certificate }; // Sets the key data into the key store kstore.setKeyEntry(alias, keypair.getPrivate(), password.toCharArray(), chain); LOGGER.debug("Added certificate with alias {} and password {} for issuer {}", alias, password, issuer); }
From source file:edu.washington.shibboleth.attribute.resolver.dc.rws.HttpDataSource.java
/** * Generate a socket factory using supplied key and trust stores *//*from www.j ava2 s . co m*/ protected SSLConnectionSocketFactory getSocketFactory() throws IOException { TrustManager[] trustManagers = null; KeyManager[] keyManagers = null; try { /* trust managers */ if (caCertificateFile != null) { KeyStore trustStore; int cn = 0; log.info("Setting x509 trust from " + caCertificateFile); TrustManagerFactory tmf = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); CertificateFactory cf = CertificateFactory.getInstance("X.509"); FileInputStream in = new FileInputStream(caCertificateFile); Collection certs = cf.generateCertificates(in); trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(null, null); Iterator cit = certs.iterator(); while (cit.hasNext()) { X509Certificate cert = (X509Certificate) cit.next(); log.info(" adding " + cert.getSubjectX500Principal().toString()); System.out.println(" adding " + cert.getSubjectX500Principal().toString()); trustStore.setCertificateEntry("CACERT" + cn, cert); cn += 1; } tmf.init(trustStore); trustManagers = tmf.getTrustManagers(); } else { // no verification trustManagers = new TrustManager[] { new X509TrustManager() { public X509Certificate[] getAcceptedIssuers() { return null; } public void checkClientTrusted(X509Certificate[] certs, String authType) { return; } public void checkServerTrusted(X509Certificate[] certs, String authType) { return; } } }; } /* key manager */ if (certificateFile != null && keyFile != null) { KeyStore keyStore; KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); keyStore.load(null, null); FileInputStream in = new FileInputStream(certificateFile); CertificateFactory cf = CertificateFactory.getInstance("X.509"); X509Certificate cert = (X509Certificate) cf.generateCertificate(in); PKCS1 pkcs = new PKCS1(); log.info("reading key file: " + keyFile); PrivateKey key = pkcs.readKey(keyFile); X509Certificate[] chain = new X509Certificate[1]; chain[0] = cert; keyStore.setKeyEntry("CERT", (Key) key, "pw".toCharArray(), chain); kmf.init(keyStore, "pw".toCharArray()); keyManagers = kmf.getKeyManagers(); } /* socket factory */ SSLContext ctx = SSLContext.getInstance("TLS"); ctx.init(keyManagers, trustManagers, null); return new SSLConnectionSocketFactory(ctx); } catch (IOException e) { log.error("error reading cert or key error: " + e); } catch (KeyStoreException e) { log.error("keystore error: " + e); } catch (NoSuchAlgorithmException e) { log.error("sf error: " + e); } catch (KeyManagementException e) { log.error("sf error: " + e); } catch (CertificateException e) { log.error("sf error: " + e); } catch (UnrecoverableKeyException e) { log.error("sf error: " + e); } return null; }