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.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.enrollment.EnrollmentManager.java
private void storeKeyToKeyStore(String alias, Key cryptoKey, Certificate certInCertChain) { KeyStore keyStore; try {//from w w w . j a v a 2s . c om keyStore = KeyStore.getInstance(AgentConstants.DEVICE_KEYSTORE_TYPE); Certificate[] certChain = new Certificate[1]; certChain[0] = certInCertChain; keyStore.setKeyEntry(alias, cryptoKey, AgentConstants.DEVICE_KEYSTORE_PASSWORD.toCharArray(), certChain); keyStore.store(new FileOutputStream(AgentConstants.DEVICE_KEYSTORE), AgentConstants.DEVICE_KEYSTORE_PASSWORD.toCharArray()); } catch (KeyStoreException | CertificateException | NoSuchAlgorithmException | IOException e) { log.error(AgentConstants.LOG_APPENDER + "An error occurred whilst trying to store the key with alias " + "[" + alias + "] in the device keystore."); log.error(AgentConstants.LOG_APPENDER + e); log.warn(AgentConstants.LOG_APPENDER + "Key [" + alias + "] was not stored in the keystore; " + "Hence the device will be re-enrolled during next restart."); } }
From source file:nl.nikhef.eduroam.WiFiEduroam.java
@TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) // Step 3 for android 4.0 - 4.2 private void installClientCertificate() { try {//from ww w . j ava2s. c o m updateStatus("Inputting client certificate."); // Parse the certificate that we got from the server CertificateFactory certFactory = CertificateFactory.getInstance("X.509"); InputStream in = new ByteArrayInputStream( Base64.decode(certificate.replaceAll("-----(BEGIN|END) CERTIFICATE-----", ""))); X509Certificate cert = (X509Certificate) certFactory.generateCertificate(in); client_cert_name = ssid + " " + INT_CLIENT_CERT_NAME; // Create a pkcs12 certificate/private key combination Security.addProvider(new BouncyCastleProvider()); KeyStore keystore = KeyStore.getInstance("PKCS12", "BC"); keystore.load(null, null); Certificate chain[] = new Certificate[] { (Certificate) cert }; keystore.setKeyEntry(client_cert_name, csr.getPrivate(), null, chain); ByteArrayOutputStream out = new ByteArrayOutputStream(); keystore.store(out, ssid.toCharArray()); out.flush(); byte[] buffer = out.toByteArray(); out.close(); // Install the private key/client certificate combination Intent intent = KeyChain.createInstallIntent(); intent.putExtra(KeyChain.EXTRA_NAME, ssid + " " + INT_CLIENT_CERT_NAME); intent.putExtra(KeyChain.EXTRA_PKCS12, buffer); startActivityForResult(intent, 3); } catch (CertificateException e) { e.printStackTrace(); throw new RuntimeException("Certificate error."); } catch (KeyStoreException e) { e.printStackTrace(); System.out.println(e.getMessage()); throw new RuntimeException("Certificate error: KeyStore"); } catch (NoSuchProviderException e) { e.printStackTrace(); throw new RuntimeException("Certificate error: Provider"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); throw new RuntimeException("Certificate error: Algorithm"); } catch (IOException e) { e.printStackTrace(); throw new RuntimeException("Certificate error: IO"); } }
From source file:org.jboss.as.test.integration.auditlog.AuditLogToTLSSyslogSetup.java
private void createKeyStoreTrustStore(KeyStore keyStore, KeyStore trustStore, String DN, String alias) throws Exception { X500Principal principal = new X500Principal(DN); SelfSignedX509CertificateAndSigningKey selfSignedX509CertificateAndSigningKey = SelfSignedX509CertificateAndSigningKey .builder().setKeyAlgorithmName("RSA").setSignatureAlgorithmName("SHA256withRSA").setDn(principal) .setKeySize(1024).build();// w w w.ja v a2 s . com X509Certificate certificate = selfSignedX509CertificateAndSigningKey.getSelfSignedCertificate(); keyStore.setKeyEntry(alias, selfSignedX509CertificateAndSigningKey.getSigningKey(), KEYSTORE_CREATION_PASSWORD, new X509Certificate[] { certificate }); trustStore.setCertificateEntry(alias, certificate); }
From source file:test.unit.be.fedict.eid.idp.protocol.openid.OpenIDSSLProtocolServiceTest.java
private void persistKey(File pkcs12keyStore, PrivateKey privateKey, X509Certificate certificate, char[] keyStorePassword, char[] keyEntryPassword) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException, NoSuchProviderException { KeyStore keyStore = KeyStore.getInstance("pkcs12", BouncyCastleProvider.PROVIDER_NAME); keyStore.load(null, keyStorePassword); keyStore.setKeyEntry("default", privateKey, keyEntryPassword, new Certificate[] { certificate }); FileOutputStream keyStoreOut = new FileOutputStream(pkcs12keyStore); keyStore.store(keyStoreOut, keyStorePassword); keyStoreOut.close();/*w ww . j a va 2 s.co m*/ }
From source file:org.alfresco.extension.countersign.signature.RepositoryManagedSignatureProvider.java
/** * Create a keystore for this user to be used for document signing, store it associated with the user's * person node//from ww w . ja va 2 s. c om * * @param person * @param password * * @return a Java KeyStore object suitable for document signing * @throws NoSuchAlgorithmException * @throws NoSuchProviderException * @throws KeyStoreException * @throws IOException * @throws CertificateException */ private KeyStore createUserKeyStore(NodeRef person, String password) throws NoSuchAlgorithmException, NoSuchProviderException, KeyStoreException, CertificateException, IOException { // get the alias from the configuration String alias = config.getProperty(RepositoryManagedSignatureProviderFactory.ALIAS); // initialize key generator KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA"); SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN"); keyGen.initialize(2048, random); // generate a keypair KeyPair pair = keyGen.generateKeyPair(); PrivateKey priv = pair.getPrivate(); PublicKey pub = pair.getPublic(); // generate the user certificate Certificate cert = generateCertificate(pair, person); // get the ca cert used to sign and create cert chain KeyStore trustedKs = getTrustedKeyStore(); Certificate[] caChain = getCaCertChain(trustedKs); Certificate[] certChain = new Certificate[caChain.length + 1]; certChain[0] = cert; for (int i = 0; i < caChain.length; i++) { certChain[i + 1] = caChain[i]; } // create keystore, adding private key and cert chain KeyStore ks = KeyStore.getInstance("pkcs12"); ks.load(null, password.toCharArray()); ks.setKeyEntry(alias, priv, password.toCharArray(), certChain); // save the keystore saveUserKeyStore(person, ks, password); // also save the public key separately, will need it // for later validaiton activities saveUserPublicKey(person, pub); // return the generated keystore return ks; }
From source file:org.kuali.coeus.propdev.impl.s2s.connect.S2SConnectorServiceBase.java
/** * This method is to confgiure KeyStore and Truststore for Grants.Gov webservice client * @param tlsConfig//from w w w. j a v a 2 s . co m * @param alias * @param mulitCampusEnabled * @throws S2sCommunicationException */ protected void configureKeyStoreAndTrustStore(TLSClientParameters tlsConfig, String alias, boolean mulitCampusEnabled) throws S2sCommunicationException { KeyStore keyStore = s2sCertificateReader.getKeyStore(); KeyManagerFactory keyManagerFactory; try { keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); if (alias != null && mulitCampusEnabled) { KeyStore keyStoreAlias; keyStoreAlias = KeyStore.getInstance(s2sCertificateReader.getJksType()); Certificate[] certificates = keyStore.getCertificateChain(alias); Key key = keyStore.getKey(alias, s2SConfigurationService .getValueAsString(s2sCertificateReader.getKeyStorePassword()).toCharArray()); keyStoreAlias.load(null, null); keyStoreAlias.setKeyEntry( alias, key, s2SConfigurationService .getValueAsString(s2sCertificateReader.getKeyStorePassword()).toCharArray(), certificates); keyManagerFactory.init(keyStoreAlias, s2SConfigurationService .getValueAsString(s2sCertificateReader.getKeyStorePassword()).toCharArray()); } else { keyManagerFactory.init(keyStore, s2SConfigurationService .getValueAsString(s2sCertificateReader.getKeyStorePassword()).toCharArray()); } KeyManager[] km = keyManagerFactory.getKeyManagers(); tlsConfig.setKeyManagers(km); KeyStore trustStore = s2sCertificateReader.getTrustStore(); TrustManagerFactory trustManagerFactory = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(trustStore); TrustManager[] tm = trustManagerFactory.getTrustManagers(); tlsConfig.setTrustManagers(tm); } catch (NoSuchAlgorithmException | KeyStoreException | UnrecoverableKeyException | CertificateException | IOException e) { LOG.error(e.getMessage(), e); throw new S2sCommunicationException(KeyConstants.ERROR_KEYSTORE_CONFIG, e.getMessage()); } }
From source file:org.kuali.kra.s2s.service.impl.S2SConnectorServiceBase.java
/** * This method is to confgiure KeyStore and Truststore for Grants.Gov webservice client * @param tlsConfig/* w ww . j av a 2s . c o m*/ * @param alias * @param mulitCampusEnabled * @throws S2SException */ protected void configureKeyStoreAndTrustStore(TLSClientParameters tlsConfig, String alias, boolean mulitCampusEnabled) throws S2SException { KeyStore keyStore = s2sCertificateReader.getKeyStore(); KeyManagerFactory keyManagerFactory; try { keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); if (alias != null && mulitCampusEnabled) { KeyStore keyStoreAlias; keyStoreAlias = KeyStore.getInstance(s2sCertificateReader.getJksType()); Certificate[] certificates = keyStore.getCertificateChain(alias); Key key = keyStore.getKey(alias, s2SUtilService.getProperty(s2sCertificateReader.getKeyStorePassword()).toCharArray()); keyStoreAlias.load(null, null); keyStoreAlias.setKeyEntry(alias, key, s2SUtilService.getProperty(s2sCertificateReader.getKeyStorePassword()).toCharArray(), certificates); keyManagerFactory.init(keyStoreAlias, s2SUtilService.getProperty(s2sCertificateReader.getKeyStorePassword()).toCharArray()); } else { keyManagerFactory.init(keyStore, s2SUtilService.getProperty(s2sCertificateReader.getKeyStorePassword()).toCharArray()); } KeyManager[] km = keyManagerFactory.getKeyManagers(); tlsConfig.setKeyManagers(km); KeyStore trustStore = s2sCertificateReader.getTrustStore(); TrustManagerFactory trustManagerFactory = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(trustStore); TrustManager[] tm = trustManagerFactory.getTrustManagers(); tlsConfig.setTrustManagers(tm); } catch (NoSuchAlgorithmException e) { LOG.error(e); throw new S2SException(KeyConstants.ERROR_KEYSTORE_CONFIG, e.getMessage()); } catch (KeyStoreException e) { LOG.error(e); throw new S2SException(KeyConstants.ERROR_KEYSTORE_CONFIG, e.getMessage()); } catch (UnrecoverableKeyException e) { LOG.error(e); throw new S2SException(KeyConstants.ERROR_KEYSTORE_CONFIG, e.getMessage()); } catch (CertificateException e) { LOG.error(e); throw new S2SException(KeyConstants.ERROR_KEYSTORE_CONFIG, e.getMessage()); } catch (IOException e) { LOG.error(e); throw new S2SException(KeyConstants.ERROR_KEYSTORE_CONFIG, e.getMessage()); } }
From source file:org.springframework.security.ldap.server.ApacheDsSSLContainer.java
public File getKeystore(File directory) throws Exception { KeyStore keyStore = KeyStore.getInstance("JKS"); keyStore.load(null, null);// w ww .j a v a 2 s.co m KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA"); keyPairGenerator.initialize(keysize); KeyPair keyPair = keyPairGenerator.generateKeyPair(); X509Certificate[] chain = { getSelfCertificate(new X500Name(commonName, organizationalUnit, organization, city, state, country), new Date(), (long) validity * 24 * 60 * 60, keyPair, "SHA256withRSA") }; keyStore.setKeyEntry(alias, keyPair.getPrivate(), keyPass, chain); String keystoreName = "ldap.keystore"; File keystore = new File(directory, keystoreName); if (!keystore.createNewFile()) { throw new FileNotFoundException("Unable to create file:" + keystore); } keyStore.store(new FileOutputStream(keystore, false), keyPass); return keystore; }
From source file:org.openanzo.security.keystore.SecretKeyStore.java
/** * Loads the secret key to use for encryption and decryption. It will read the key from the keystore if it exists. Otherwise it will create a new randomly * generated key and save it in a keystore at the given file. It will use the algorithm defined in the <code>algorithm</code> member. * // w ww . j a v a 2 s . c o m * @param keyStoreStream * stream from which to read the keystore which holds the secret key. If null, a new keystore is created. * @param password * password used to protect the and integrity-check the secret key. * @param keyStoreDestination * File path to which to save the keystore in case it is newly created or a new key was added. If null, then nothing is written out. * @return the loaded or newly generated secret key. * @throws AnzoException */ private SecretKey loadKey(InputStream keyStoreStream, String password, File keyStoreDestination, String keystoreType) throws AnzoException { try { KeyStore keyStore = KeyStore.getInstance(keystoreType); keyStore.load(keyStoreStream, password.toCharArray()); Key key = null; if (keyStore.containsAlias(KEY_NAME)) { key = keyStore.getKey(KEY_NAME, password.toCharArray()); } else { log.warn("Could not find key '{}' within keystore. Generating a new key.", KEY_NAME); KeyGenerator kgen = KeyGenerator.getInstance(algorithm); key = kgen.generateKey(); keyStore.setKeyEntry(KEY_NAME, key, password.toCharArray(), new Certificate[0]); if (keyStoreDestination != null) { log.warn("Storing new key in the keystore."); OutputStream outputStream = null; try { outputStream = FileUtils.openOutputStream(keyStoreDestination); keyStore.store(outputStream, password.toCharArray()); } finally { if (outputStream != null) { outputStream.close(); } } } } if (!(key instanceof SecretKey)) throw new AnzoException(ExceptionConstants.OSGI.INTERNAL_COMPONENT_ERROR, "key must be of type SecretKey: " + key); return (SecretKey) key; } catch (GeneralSecurityException e) { throw new AnzoException(ExceptionConstants.OSGI.INTERNAL_COMPONENT_ERROR, e); } catch (IOException e) { throw new AnzoException(ExceptionConstants.OSGI.INTERNAL_COMPONENT_ERROR, e); } }
From source file:com.isecpartners.gizmo.HttpRequest.java
private KeyManagerFactory createKeyManagerFactory(String cname) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException, UnrecoverableKeyException, InvalidKeyException, SignatureException, NoSuchProviderException, NoCertException { X509Certificate cert = KeyStoreManager.getCertificateByHostname(cname); cybervillains.ca.KeyStoreManager.getCertificateByHostname(cname); if (cert == null) { throw new NoCertException(); }/* w ww .ja v a 2s . co m*/ KeyStore ks = KeyStore.getInstance("JKS"); ks.load(null, pass); ks.setCertificateEntry(cname, cert); ks.setKeyEntry(cname, KeyStoreManager.getPrivateKeyForLocalCert(cert), pass, new X509Certificate[] { cert }); KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); kmf.init(ks, pass); return kmf; }