List of usage examples for java.security KeyStore getInstance
public static KeyStore getInstance(String type) throws KeyStoreException
From source file:com.github.technosf.posterer.models.impl.KeyStoreBeanTest.java
/** * Create clean temp key store files and ensure we can access the main test * key store file//from w w w. java 2 s . co m */ @BeforeClass private void init() throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException { // Delete preexisting testing keystores FileUtils.deleteQuietly(FileUtils.getFile(missingKeyStore)); FileUtils.deleteQuietly(FileUtils.getFile(unknownKeyStore)); FileUtils.deleteQuietly(FileUtils.getFile(emptyKeyStore)); // Get the keystore algo and create the ks in memory KeyStore ks = KeyStore.getInstance("JKS"); ks.load(null, passwordchr); // Write out unknown pw keystore FileOutputStream fos = new FileOutputStream(unknownKeyStore); ks.store(fos, "unknownpw".toCharArray()); fos.close(); assertFalse(FileUtils.getFile(missingKeyStore).exists()); // Write out empty key store fos = new FileOutputStream(emptyKeyStore); ks.store(fos, passwordchr); fos.close(); assertFalse(FileUtils.getFile(missingKeyStore).exists()); // Check the main test key store URL testKeystoreURL = this.getClass().getResource("/testkeystore.jks"); testKeyStoreFile = FileUtils.toFile(testKeystoreURL); assertNotNull(testKeyStoreFile); }
From source file:com.elkriefy.android.apps.authenticationexample.credentialsgrace.CredGraceActivity.java
/** * Tries to encrypt some data with the generated key in {@link #createKey} which is * only works if the user has just authenticated via device credentials. *//*ww w . j a v a 2 s.c om*/ private boolean tryEncrypt() { try { KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore"); keyStore.load(null); SecretKey secretKey = (SecretKey) keyStore.getKey(KEY_NAME, null); Cipher cipher = Cipher.getInstance(KeyProperties.KEY_ALGORITHM_AES + "/" + KeyProperties.BLOCK_MODE_CBC + "/" + KeyProperties.ENCRYPTION_PADDING_PKCS7); // Try encrypting something, it will only work if the user authenticated within // the last AUTHENTICATION_DURATION_SECONDS seconds. cipher.init(Cipher.ENCRYPT_MODE, secretKey); cipher.doFinal(SECRET_BYTE_ARRAY); // If the user has recently authenticated, you will reach here. showAlreadyAuthenticated(); return true; } catch (UserNotAuthenticatedException e) { // User is not authenticated, let's authenticate with device credentials. showAuthenticationScreen(); return false; } catch (KeyPermanentlyInvalidatedException e) { // This happens if the lock screen has been disabled or reset after the key was // generated after the key was generated. Toast.makeText(this, "Keys are invalidated after created. Retry the purchase\n" + e.getMessage(), Toast.LENGTH_LONG).show(); return false; } catch (BadPaddingException | IllegalBlockSizeException | KeyStoreException | CertificateException | UnrecoverableKeyException | IOException | NoSuchPaddingException | NoSuchAlgorithmException | InvalidKeyException e) { throw new RuntimeException(e); } }
From source file:me.xiaopan.android.gohttp.httpclient.MySSLSocketFactory.java
/** * Gets a KeyStore containing the Certificate * * @param cert InputStream of the Certificate * @return KeyStore//from w w w. j a v a2s. c om */ public static KeyStore getKeystoreOfCA(InputStream cert) { // Load CAs from an InputStream InputStream caInput = null; Certificate ca = null; try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); caInput = new BufferedInputStream(cert); ca = (Certificate) cf.generateCertificate(caInput); } catch (CertificateException e1) { e1.printStackTrace(); } finally { try { caInput.close(); } catch (IOException e) { e.printStackTrace(); } } // Create a KeyStore containing our trusted CAs String keyStoreType = KeyStore.getDefaultType(); KeyStore keyStore = null; try { keyStore = KeyStore.getInstance(keyStoreType); keyStore.load(null, null); keyStore.setCertificateEntry("ca", (Certificate) ca); } catch (Exception e) { e.printStackTrace(); } return keyStore; }
From source file:net.wasdev.gameon.concierge.PlayerClient.java
/** * Obtain the key we'll use to sign the jwts we use to talk to Player endpoints. * * @throws IOException/*from w w w. jav a2s. com*/ * if there are any issues with the keystore processing. */ private synchronized void getKeyStoreInfo() throws IOException { try { // load up the keystore.. FileInputStream is = new FileInputStream(keyStore); KeyStore signingKeystore = KeyStore.getInstance(KeyStore.getDefaultType()); signingKeystore.load(is, keyStorePW.toCharArray()); // grab the key we'll use to sign signingKey = signingKeystore.getKey(keyStoreAlias, keyStorePW.toCharArray()); } catch (KeyStoreException e) { throw new IOException(e); } catch (NoSuchAlgorithmException e) { throw new IOException(e); } catch (CertificateException e) { throw new IOException(e); } catch (UnrecoverableKeyException e) { throw new IOException(e); } }
From source file:org.muhia.app.psi.integ.config.ke.shared.SharedWsClientConfiguration.java
@Bean(name = "sharedSecureHttpClient") public CloseableHttpClient secureHttpClient() { CloseableHttpClient httpClient = HttpClientBuilder.create().build(); try {/*from www . j ava 2 s . c o m*/ /* TODO: Modify to accept only specific certificates, test implementation is as below, TODO: need to find a way of determining if server url is https or not TODO: Whether we have imported the certificate or not */ KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); Resource resource = loaderService.getResource(properties.getSharedKeystorePath()); keyStore.load(resource.getInputStream(), hasher.getDecryptedValue(properties.getSharedKeystorePassword()).toCharArray()); SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()) .loadKeyMaterial(keyStore, hasher.getDecryptedValue(properties.getSharedKeystorePassword()).toCharArray()) .build(); // SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, (certificate, authType) -> true).build(); RequestConfig config = RequestConfig.custom() .setConnectTimeout(properties.getSharedTransportConnectionTimeout()) .setConnectionRequestTimeout(properties.getSharedTransportConnectionRequestTimeout()) .setSocketTimeout(properties.getSharedTransportReadTimeout()).build(); CredentialsProvider provider = new BasicCredentialsProvider(); UsernamePasswordCredentials credentials = new UsernamePasswordCredentials( sharedDataDTO.getTransportUsername(), sharedDataDTO.getTransportPassword()); provider.setCredentials(AuthScope.ANY, credentials); PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(); connManager.setMaxTotal(properties.getSharedPoolMaxHost()); connManager.setDefaultMaxPerRoute(properties.getSharedPoolDefaultmaxPerhost()); connManager.setValidateAfterInactivity(properties.getSharedPoolValidateAfterInactivity()); httpClient = HttpClientBuilder.create().setSSLContext(sslContext) .setSSLHostnameVerifier(new NoopHostnameVerifier()).setDefaultRequestConfig(config) .setDefaultCredentialsProvider(provider).setConnectionManager(connManager) .evictExpiredConnections().addInterceptorFirst(new RemoveHttpHeadersInterceptor()).build(); } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException | CertificateException | IOException | UnrecoverableKeyException e) { Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, e.getMessage(), e); } return httpClient; }
From source file:com.google.jenkins.plugins.credentials.oauth.P12ServiceAccountConfig.java
private KeyStore getP12KeyStore() throws KeyStoreException, IOException, CertificateException, NoSuchAlgorithmException { FileInputStream in = null;/*from www.j a v a2 s . c om*/ try { KeyStore keyStore = KeyStore.getInstance("PKCS12"); KeyUtils.updatePermissions(new File(p12KeyFile)); in = new FileInputStream(p12KeyFile); keyStore.load(in, DEFAULT_P12_SECRET.toCharArray()); return keyStore; } finally { IOUtils.closeQuietly(in); } }
From source file:io.kubernetes.client.util.SSLUtils.java
public static KeyStore createKeyStore(InputStream certInputStream, InputStream keyInputStream, String clientKeyAlgo, char[] clientKeyPassphrase, String keyStoreFile, char[] keyStorePassphrase) throws IOException, CertificateException, NoSuchAlgorithmException, InvalidKeySpecException, KeyStoreException {//from w w w. j av a 2 s. c o m CertificateFactory certFactory = CertificateFactory.getInstance("X509"); X509Certificate cert = (X509Certificate) certFactory.generateCertificate(certInputStream); byte[] keyBytes = decodePem(keyInputStream); PrivateKey privateKey; KeyFactory keyFactory = KeyFactory.getInstance(clientKeyAlgo); try { // First let's try PKCS8 privateKey = keyFactory.generatePrivate(new PKCS8EncodedKeySpec(keyBytes)); } catch (InvalidKeySpecException e) { // Otherwise try PKCS8 RSAPrivateCrtKeySpec keySpec = decodePKCS1(keyBytes); privateKey = keyFactory.generatePrivate(keySpec); } KeyStore keyStore = KeyStore.getInstance("JKS"); if (keyStoreFile != null && keyStoreFile.length() > 0) { keyStore.load(new FileInputStream(keyStoreFile), keyStorePassphrase); } else { loadDefaultKeyStoreFile(keyStore, keyStorePassphrase); } String alias = cert.getSubjectX500Principal().getName(); keyStore.setKeyEntry(alias, privateKey, clientKeyPassphrase, new Certificate[] { cert }); return keyStore; }
From source file:com.apporiented.hermesftp.utils.SecurityUtil.java
/** * Create the security context required for SSL communication. * /*w ww .j a v a 2s . c om*/ * @param keyStoreFile The name of the keystore file. * @param keyStorePassword The password for the keystore. * @return The context. * @throws FtpConfigException Thrown on error in configuration. */ public static SSLContext createSslContext(String keyStoreFile, char[] keyStorePassword) throws FtpConfigException { SSLContext sslContext; try { /* Get keystore file and password */ InputStream ksInputStream = getKeyStoreInputStream(keyStoreFile); /* * Get the java keystore object an key manager. A keystore is where keys and * certificates are kept. */ KeyStore keystore = KeyStore.getInstance("JKS"); keystore.load(ksInputStream, keyStorePassword); KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509"); kmf.init(keystore, keyStorePassword); /* * An SSLContext is an environment for implementing JSSE. It is used to create a * ServerSocketFactory */ sslContext = SSLContext.getInstance("SSL"); sslContext.init(kmf.getKeyManagers(), null, null); } catch (KeyManagementException e) { throw new SecurityException("A key management authorization problem occurred."); } catch (FileNotFoundException e) { throw new SecurityException("The key store file could not be found."); } catch (KeyStoreException e) { throw new SecurityException("A key store problem occurred."); } catch (NoSuchAlgorithmException e) { throw new SecurityException("The hash algorithm is not supported."); } catch (CertificateException e) { throw new SecurityException("Certificate could not be loaded."); } catch (UnrecoverableKeyException e) { throw new SecurityException("Key store cannot be recovered."); } catch (IOException e) { throw new SecurityException("Reading the key store failed."); } return sslContext; }
From source file:edu.vt.alerts.android.library.util.HttpClientFactory.java
private KeyStore getInstallerKeyStore(Context context, InputStream installerKeystore) throws Exception { KeyStore installerKeyStore = KeyStore.getInstance("PKCS12"); installerKeyStore.load(installerKeystore, "changeit".toCharArray()); return installerKeyStore; }
From source file:it.cnr.icar.eric.client.xml.registry.util.SecurityUtil.java
private KeyStore loadKeyStore() throws JAXRException { String storepass = ProviderProperties.getInstance().getProperty("jaxr-ebxml.security.storepass"); try {/*from w w w . jav a2 s . c o m*/ keyStore = KeyStore .getInstance(ProviderProperties.getInstance().getProperty("jaxr-ebxml.security.storetype")); } catch (KeyStoreException x) { throw new JAXRException(x); } File keyStoreFile = KeystoreUtil.getKeystoreFile(); if (!keyStoreFile.exists()) { throw new JAXRException(JAXRResourceBundle.getInstance().getString("message.error.no.keystore.file", new Object[] { keyStoreFile.toString() })); } try { InputStream keyIS = new BufferedInputStream(new FileInputStream(keyStoreFile)); keyStore.load(keyIS, storepass.toCharArray()); log.debug("Keystore loaded from '" + keyStoreFile.getCanonicalPath() + "'"); } catch (IOException x) { throw new JAXRException(x); } catch (GeneralSecurityException x) { throw new JAXRException(x); } return keyStore; }