/** * Takes a GFIPM entity ID or a Java key store entry alias name and deletes its entry from the * Java key store. Writes out an error messages on an exception. * * @param entityid The GFIPM entity or key store alias to be deleted. * @return true on success, false otherwise. */ public boolean deleteEntry(String entityid) { if (entityid == null) { System.err.println("ERROR: GFIPMKeystore.deleteEntry: No entityid or alias name. Aborted."); System.err.flush(); return false; } String alias = makeEntityAliasName(entityid); try { if (keyStore.containsAlias(alias)) { if (verboseOut) { System.out.println("Key store: delete entry " + alias); System.out.flush(); } keyStore.deleteEntry(alias); modifiedFlag = true; } else { if (verboseOut) { System.out.println("Key store: Entry to be delete not found with alias " + alias); } } } catch (KeyStoreException e) { System.err.println("ERROR: GFIPMKeystore.deleteEntry failed: "); System.err.println(e.toString()); System.err.flush(); return false; } return true; } // end deleteEntry
/** Writes out the alias names of all the key store entries. For debugging purposes. */ public void printKeyStoreAliases() { try { String alias = null; for (Enumeration<String> aliases = keyStore.aliases(); aliases.hasMoreElements(); ) { alias = aliases.nextElement(); if (alias.startsWith(aliasPrefix)) { System.out.print(" * "); } else { System.out.print(" "); } System.out.println(alias); } System.out.println(""); System.out.print("Number of entries in key store: "); System.out.println(keyStore.size()); System.out.flush(); } catch (KeyStoreException e) { System.err.println("ERROR: GFIPMKeystore.printKeyStoreAliases failed: "); System.err.println(e.toString()); System.err.flush(); } } // end printKeyStoreAliases
/** {@inheritDoc} */ public void saveKeyStore(KeyStore store, char[] password) throws KeyStoreException, IOException { if (LOG.isEnabledFor(Level.DEBUG)) { LOG.debug("Writing " + store + " to " + keystore_location); } try { OutputStream os = null; if ("file".equalsIgnoreCase(keystore_location.getScheme())) { os = new FileOutputStream(new File(keystore_location)); } else { os = keystore_location.toURL().openConnection().getOutputStream(); } store.store(os, password); } catch (NoSuchAlgorithmException failed) { KeyStoreException failure = new KeyStoreException("NoSuchAlgorithmException during keystore processing"); failure.initCause(failed); throw failure; } catch (CertificateException failed) { KeyStoreException failure = new KeyStoreException("CertificateException during keystore processing"); failure.initCause(failed); throw failure; } }
private static KeyStore getKeyStore(Certificate[] chain, PrivateKey pk) { try { KeyStore ks = KeyStore.getInstance(KEYSTORE_TYPE); try { ks.load(null, null); } // empty catch (Exception ignore) { } // @SuppressWarnings("unused") KeyStore.Entry ke = new KeyStore.PrivateKeyEntry(pk, chain); ks.setKeyEntry(CERT_ALIAS, pk, THE_PASSWORD, chain); log.debug( "added certificate chain to keystore: " + CERT_ALIAS + "," + pk + "," + THE_PASSWORD + "," + chain); return ks; } catch (KeyStoreException ex) { if (ex.getCause() != null && ex.getCause() instanceof java.security.NoSuchAlgorithmException) { throw new IllegalArgumentException( "Sorry, this implementation of Java, issued by " + System.getProperty("java.vendor") + ", does not support CADC Certificates."); } throw new RuntimeException("failed to find/load KeyStore of type " + KEYSTORE_TYPE, ex); } }
/** * ִ��http���á�true:�ɹ� false:ʧ�� * * @return boolean */ public boolean call() { boolean isRet = false; // http if (null == this.caFile && null == this.certFile) { try { this.callHttp(); isRet = true; } catch (IOException e) { this.errInfo = e.getMessage(); } return isRet; } // https try { this.callHttps(); isRet = true; } catch (UnrecoverableKeyException e) { this.errInfo = e.getMessage(); } catch (KeyManagementException e) { this.errInfo = e.getMessage(); } catch (CertificateException e) { this.errInfo = e.getMessage(); } catch (KeyStoreException e) { this.errInfo = e.getMessage(); } catch (NoSuchAlgorithmException e) { this.errInfo = e.getMessage(); } catch (IOException e) { this.errInfo = e.getMessage(); } return isRet; }
/** * Key store 类型HttpClient * * @param keystore keystore * @param keyPassword keyPassword * @param supportedProtocols supportedProtocols * @param timeout timeout * @param retryExecutionCount retryExecutionCount * @return CloseableHttpClient */ public static CloseableHttpClient createKeyMaterialHttpClient( KeyStore keystore, String keyPassword, String[] supportedProtocols, int timeout, int retryExecutionCount) { try { SSLContext sslContext = SSLContexts.custom() .useSSL() .loadKeyMaterial(keystore, keyPassword.toCharArray()) .build(); SSLConnectionSocketFactory sf = new SSLConnectionSocketFactory( sslContext, supportedProtocols, null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); SocketConfig socketConfig = SocketConfig.custom().setSoTimeout(timeout).build(); return HttpClientBuilder.create() .setDefaultSocketConfig(socketConfig) .setSSLSocketFactory(sf) .setRetryHandler(new HttpRequestRetryHandlerImpl(retryExecutionCount)) .build(); } catch (KeyManagementException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (UnrecoverableKeyException e) { e.printStackTrace(); } catch (KeyStoreException e) { e.printStackTrace(); } return null; }
void update(WssCrypto crypto) { try { if (crypto == null || crypto.getCrypto() == null) { keyStore = null; } else { Merlin merlinCrypto = (Merlin) crypto.getCrypto(); if (crypto.getType() == CryptoType.KEYSTORE) { keyStore = merlinCrypto.getKeyStore(); } else if (crypto.getType() == CryptoType.TRUSTSTORE) { keyStore = merlinCrypto.getTrustStore(); } } } catch (WSSecurityException wssecurityException) { wssecurityException.printStackTrace(); } if (keyStore != null) { if (!aliases.isEmpty()) { int sz = aliases.size(); aliases.clear(); fireIntervalRemoved(this, 0, sz - 1); } try { for (Enumeration e = keyStore.aliases(); e.hasMoreElements(); ) { aliases.add(e.nextElement().toString()); } fireIntervalAdded(this, 0, aliases.size() - 1); } catch (KeyStoreException e) { e.printStackTrace(); } } }
private searchMenuMgr() { try { KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(null, null); MySSLSocketFactory socketFactory = new MySSLSocketFactory(trustStore); socketFactory.setHostnameVerifier(MySSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); client = new AsyncHttpClient(); client.setSSLSocketFactory(socketFactory); client.setCookieStore(new PersistentCookieStore(Login_Main.getContext())); client.setTimeout(10000); } catch (KeyStoreException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (CertificateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (KeyManagementException e) { e.printStackTrace(); } catch (UnrecoverableKeyException e) { e.printStackTrace(); } }
public static CloseableHttpClient createSSLClientDefault() { try { SSLContext sslContext = new SSLContextBuilder() .loadTrustMaterial( null, new TrustStrategy() { // 信任所有 public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { return true; } }) .build(); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext); return HttpClients.custom().setSSLSocketFactory(sslsf).build(); } catch (KeyManagementException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyStoreException e) { e.printStackTrace(); } return HttpClients.createDefault(); }
private KeyManager[] prepareKeyManager(InputStream bksFile, String password) { try { if (bksFile == null || password == null) return null; KeyStore clientKeyStore = KeyStore.getInstance("BKS"); clientKeyStore.load(bksFile, password.toCharArray()); KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); keyManagerFactory.init(clientKeyStore, password.toCharArray()); return keyManagerFactory.getKeyManagers(); } catch (KeyStoreException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (UnrecoverableKeyException e) { e.printStackTrace(); } catch (CertificateException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return null; }
private static SSLSocketFactory getSocketFactory(Boolean d) { // Enable debug mode to ignore all certificates if (DEBUG) { KeyStore trustStore; try { trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(null, null); SSLSocketFactory sf = new DebugSSLSocketFactory(trustStore); sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); return sf; } catch (KeyStoreException e2) { // TODO Auto-generated catch block e2.printStackTrace(); } catch (NoSuchAlgorithmException e3) { // TODO Auto-generated catch block e3.printStackTrace(); } catch (CertificateException e3) { // TODO Auto-generated catch block e3.printStackTrace(); } catch (IOException e3) { // TODO Auto-generated catch block e3.printStackTrace(); } catch (KeyManagementException e2) { // TODO Auto-generated catch block e2.printStackTrace(); } catch (UnrecoverableKeyException e2) { // TODO Auto-generated catch block e2.printStackTrace(); } } return SSLSocketFactory.getSocketFactory(); }
/** * Returns the private key for the specified ID. * * @param id The ID of the requested private key. * @param key_password The passphrase associated with the private key or {@code null} if the key * has no passphrase. * @return PrivateKey for the specified ID. * @throws KeyStoreException When the wrong keystore has been provided. * @throws IOException For errors related to processing the keystore. */ public PrivateKey getKey(ID id, char[] key_password) throws KeyStoreException, IOException { String alias = id.toString(); try { synchronized (keystore_manager) { KeyStore store = keystore_manager.loadKeyStore(keystore_password); if (!store.containsAlias(alias) || !store.isKeyEntry(alias)) { return null; } return (PrivateKey) store.getKey(alias, key_password); } } catch (NoSuchAlgorithmException failed) { Logging.logCheckedSevere(LOG, "Something failed\n", failed); KeyStoreException failure = new KeyStoreException("Something Failed"); failure.initCause(failed); throw failure; } catch (UnrecoverableKeyException failed) { Logging.logCheckedSevere(LOG, "Key passphrase failure\n", failed); KeyStoreException failure = new KeyStoreException("Key passphrase failure"); failure.initCause(failed); throw failure; } }
public static KeyPair getPrivateKey(String alias, char[] password) throws FileNotFoundException, IOException, CertificateException { try { KeyStore ks = KeyStore.getInstance("JKS"); char[] passPhrase = "123456".toCharArray(); // BASE64Encoder myB64 = new BASE64Encoder(); File certificateFile = new File("C:\\Temp\\repositorio.jks"); ks.load(new FileInputStream(certificateFile), passPhrase); // Get private key Key key = ks.getKey(alias, password); if (key instanceof PrivateKey) { // Get certificate of public key Certificate cert = ks.getCertificate(alias); // Get public key PublicKey publicKey = cert.getPublicKey(); // Return a key pair return new KeyPair(publicKey, (PrivateKey) key); } } catch (UnrecoverableKeyException e) { System.out.print(e.getMessage()); } catch (NoSuchAlgorithmException e) { System.out.print(e.getMessage()); } catch (KeyStoreException e) { System.out.print(e.getMessage()); } return null; }
/** * Test for <code>KeyStoreException(String)</code> constructor Assertion: constructs * KeyStoreException with detail message msg. Parameter <code>msg</code> is not null. */ public void testKeyStoreException02() { KeyStoreException tE; for (int i = 0; i < msgs.length; i++) { tE = new KeyStoreException(msgs[i]); assertEquals("getMessage() must return: ".concat(msgs[i]), tE.getMessage(), msgs[i]); assertNull("getCause() must return null", tE.getCause()); } }
/** * Test for <code>KeyStoreException(Throwable)</code> constructor Assertion: constructs * KeyStoreException when <code>cause</code> is not null */ public void testKeyStoreException05() { KeyStoreException tE = new KeyStoreException(tCause); if (tE.getMessage() != null) { String toS = tCause.toString(); String getM = tE.getMessage(); assertTrue("getMessage() should contain ".concat(toS), (getM.indexOf(toS) != -1)); } assertNotNull("getCause() must not return null", tE.getCause()); assertEquals("getCause() must return ".concat(tCause.toString()), tE.getCause(), tCause); }
private void testIt() { String https_url = requestURL; URL url; SSLSocketFactory socketFactory = null; try { try { socketFactory = createSSLContext().getSocketFactory(); } catch (UnrecoverableKeyException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (KeyManagementException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (KeyStoreException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (CertificateException e) { // TODO Auto-generated catch block e.printStackTrace(); } url = new URL(https_url); HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); conn.setDoInput(true); // Allow Inputs conn.setDoOutput(true); // Allow Outputs conn.setRequestMethod("POST"); conn.setRequestProperty("Connection", "Keep-Alive"); conn.setRequestProperty("ENCTYPE", "multipart/form-data"); conn.setSSLSocketFactory(socketFactory); DataOutputStream dos = new DataOutputStream(conn.getOutputStream()); conn.addRequestProperty("app_id", app_id); conn.addRequestProperty("app_key", app_key); // dump all cert info // print_https_cert(con); // dump all the content print_content(conn); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
public void testCreateWallet() { try { Wallet w = new Wallet(context, "test.db", "password"); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (KeyStoreException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvalidPasswordException e) { fail("Invalid password???"); } }
private void sslFileTransfer(String filename) { try { KeyStore trusted = KeyStore.getInstance("BKS"); // Get the raw resource, which contains the keystore with // your trusted certificates (root and any intermediate certs) InputStream in = context.getResources().openRawResource(tracker.springversion1.R.raw.mykeystore); trusted.load(in, "mysecret".toCharArray()); String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); tmf.init(trusted); // Create an SSLContext that uses our TrustManager SSLContext context = SSLContext.getInstance("TLS"); context.init(null, tmf.getTrustManagers(), null); URL url = new URL(host); HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection(); urlConnection.setSSLSocketFactory(context.getSocketFactory()); transfer(urlConnection, filename); // SSLSocketFactory sf = new SSLSocketFactory(trusted); // // Hostname verification from certificate // // http://hc.apache.org/httpcomponents-client-ga/tutorial/html/connmgmt.html#d4e506 // sf.setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER); // // Socket sslsocket = sf.createSocket(); // sslsocket.setKeepAlive(true); // // InetSocketAddress address = new InetSocketAddress(host, 443); // sslsocket.connect(address); // // OutputStream sout = sslsocket.getOutputStream(); } catch (KeyStoreException e) { Log.v("mark", "KeyStoreException:" + e.getMessage()); } catch (NoSuchAlgorithmException e) { Log.v("mark", "NoSuchAlgorithmException:" + e.getMessage()); } catch (CertificateException e) { Log.v("mark", "CertificateException:" + e.getMessage()); } catch (IOException e) { Log.v("mark", "IOException:" + e.getMessage()); } catch (KeyManagementException e) { Log.v("mark", "KeyManagementException:" + e.getMessage()); } }
/** * Test for <code>KeyStoreException(String, Throwable)</code> constructor Assertion: constructs * KeyStoreException when <code>cause</code> is not null <code>msg</code> is not null */ public void testKeyStoreException09() { KeyStoreException tE; for (int i = 0; i < msgs.length; i++) { tE = new KeyStoreException(msgs[i], tCause); String getM = tE.getMessage(); String toS = tCause.toString(); if (msgs[i].length() > 0) { assertTrue("getMessage() must contain ".concat(msgs[i]), getM.indexOf(msgs[i]) != -1); if (!getM.equals(msgs[i])) { assertTrue("getMessage() should contain ".concat(toS), getM.indexOf(toS) != -1); } } assertNotNull("getCause() must not return null", tE.getCause()); assertEquals("getCause() must return ".concat(tCause.toString()), tE.getCause(), tCause); } }
private static String getAlias(KeyStore keyStore) throws IOException { String alias = null; try { Enumeration nombres = keyStore.aliases(); while (nombres.hasMoreElements()) { String tmpAlias = (String) nombres.nextElement(); if (keyStore.isKeyEntry(tmpAlias)) { alias = tmpAlias; } } } catch (KeyStoreException e) { throw new IOException("Error: " + e.getMessage()); } return alias; }
public static void main(String[] args) { // TODO Auto-generated method stub SSLContextBuilder builder = new SSLContextBuilder(); try { builder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); SSLConnectionSocketFactory sslFactory = new SSLConnectionSocketFactory(builder.build()); CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslFactory).build(); HttpPost httpPost = new HttpPost("https://*****:*****@api.netkiller.com/v1/withdraw/create.json"); httpPost.addHeader("content-type", "application/json"); httpPost.addHeader("Accept", "application/json"); HttpEntity httpEntity = new StringEntity( "{\"loginname\":\"888666\", \"bankname\":\"中国银行\",\"billno\":\"B040216210517590856\",\"flag\":\"a\",\"amount\":12,\"accountnumber\":\"9555500060007000\",\"accounttype\":\"借记卡\",\"createdate\":\"2016-09-10T20:12:12\",\"remarks\":\"CFD\",\"currency\":\"CNY\",\"accountname\":\"王宝强\",\"branchname\":\"南山支行\",\"bankaddress\":\"深圳市南山区科技园\",\"customerlevel\":2,\"trustlevel\":1}", "UTF-8"); httpPost.setEntity(httpEntity); // HttpGet("https://*****:*****@api.netkiller.com/v1/withdraw/ping.json"); CloseableHttpResponse response = httpclient.execute(httpPost); System.out.println(response.getStatusLine()); HttpEntity entity = response.getEntity(); String responseBody = EntityUtils.toString(entity, "UTF-8"); System.out.println(responseBody.toString()); response.close(); } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (KeyStoreException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (KeyManagementException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { } }
private KeyStore getKeyStore() throws CertificateException, IOException { KeyStore ks = null; try { ks = KeyStore.getInstance("PKCS12"); ks.load(new FileInputStream(this.pathSignature), this.passSignature.toCharArray()); } catch (KeyStoreException e) { throw new IOException("Error: " + e.getMessage()); } catch (NoSuchAlgorithmException e) { throw new IOException("Error: " + e.getMessage()); } catch (CertificateException e) { throw new IOException("Error: " + e.getMessage()); } catch (IOException e) { throw new IOException("Error: " + e.getMessage()); } return ks; }
protected void execute() throws CertificateException, IOException { KeyStore keyStore = getKeyStore(); if (keyStore == null) { throw new IOException("No se pudo obtener almacen de firma."); } String alias = getAlias(keyStore); X509Certificate certificate = null; try { certificate = (X509Certificate) keyStore.getCertificate(alias); if (certificate == null) { throw new IOException("No existe ningún certificado para firmar."); } } catch (KeyStoreException e1) { throw new IOException("Error: " + e1.getMessage()); } PrivateKey privateKey = null; KeyStore tmpKs = keyStore; try { privateKey = (PrivateKey) tmpKs.getKey(alias, this.passSignature.toCharArray()); } catch (UnrecoverableKeyException e) { throw new IOException("No existe clave privada para firmar."); } catch (KeyStoreException e) { throw new IOException("No existe clave privada para firmar."); } catch (NoSuchAlgorithmException e) { throw new IOException("No existe clave privada para firmar."); } Provider provider = keyStore.getProvider(); DataToSign dataToSign = createDataToSign(); FirmaXML firma = new FirmaXML(); Document docSigned = null; try { Object[] res = firma.signFile(certificate, dataToSign, privateKey, provider); docSigned = (Document) res[0]; } catch (Exception ex) { throw new IOException("Error realizando la firma: " + ex.getMessage()); } String filePath = getPathOut() + File.separatorChar + getSignatureFileName(); saveDocumenteDisk(docSigned, filePath); }
/** * Get java.security.Kestore instance from JKS * * @return */ private KeyStore loadKeyStore() { File keySF = new File(keyStorePath); KeyStore keystore = null; try { FileInputStream is = new FileInputStream(keySF); keystore = KeyStore.getInstance(KeyStore.getDefaultType()); keystore.load(is, keyStorePassword.toCharArray()); } catch (KeyStoreException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (CertificateException e) { e.printStackTrace(); } return keystore; }
public GoogleClientManager() { try { Initiallize(); } catch (KeyManagementException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (UnrecoverableKeyException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (KeyStoreException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
static void disableCertificateValidation(Context context, OkHttpClient.Builder builder) { try { CertificateFactory cf = CertificateFactory.getInstance("X.509"); InputStream caInput = context.getResources().openRawResource(R.raw.ca); Certificate ca; try { ca = cf.generateCertificate(caInput); System.out.println("ca=" + ((X509Certificate) ca).getSubjectDN()); } finally { caInput.close(); } String keyStoreType = KeyStore.getDefaultType(); KeyStore keyStore = KeyStore.getInstance(keyStoreType); keyStore.load(null, null); keyStore.setCertificateEntry("ca", ca); String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); tmf.init(keyStore); SSLContext sc = SSLContext.getInstance("TLS"); sc.init(null, tmf.getTrustManagers(), null); HostnameVerifier hv = new HostnameVerifier() { public boolean verify(String hostname, SSLSession session) { return true; } }; sc.init(null, tmf.getTrustManagers(), null); builder.sslSocketFactory(sc.getSocketFactory()); builder.hostnameVerifier(hv); } catch (CertificateException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyStoreException e) { e.printStackTrace(); } catch (KeyManagementException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
/** * Assigns the given key to the given alias, protecting it with the given password. * * <p>If the given key is of type <code>java.security.PrivateKey</code>, it must be accompanied by * a certificate chain certifying the corresponding public key. * * <p>If the given alias already exists, the keystore information associated with it is overridden * by the given key (and possibly certificate chain). * * @param alias the alias name * @param key the key to be associated with the alias * @param password the password to protect the key * @param chain the certificate chain for the corresponding public key (only required if the given * key is of type <code>java.security.PrivateKey</code>). * @exception KeyStoreException if the given key cannot be protected, or this operation fails for * some other reason */ public void engineSetKeyEntry(String alias, Key key, char[] password, Certificate[] chain) throws KeyStoreException { permissionCheck(); synchronized (entries) { try { KeyEntry entry = new KeyEntry(); entry.date = new Date(); if (key instanceof PrivateKey) { if ((key.getFormat().equals("PKCS#8")) || (key.getFormat().equals("PKCS8"))) { entry.protectedPrivKey = encryptPrivateKey(key.getEncoded(), password); entry.password = password.clone(); } else { throw new KeyStoreException("Private key is not encoded as PKCS#8"); } } else { throw new KeyStoreException("Key is not a PrivateKey"); } // clone the chain if (chain != null) { if ((chain.length > 1) && !validateChain(chain)) { throw new KeyStoreException("Certificate chain does not validate"); } entry.chain = chain.clone(); entry.chainRefs = new long[entry.chain.length]; } String lowerAlias = alias.toLowerCase(); if (entries.get(lowerAlias) != null) { deletedEntries.put(lowerAlias, entries.get(lowerAlias)); } entries.put(lowerAlias, entry); addedEntries.put(lowerAlias, entry); } catch (Exception nsae) { KeyStoreException ke = new KeyStoreException("Key protection algorithm not found: " + nsae); ke.initCause(nsae); throw ke; } } }
public void setCertificates(InputStream[] certificates, InputStream bksFile, String password) { try { TrustManager[] trustManagers = prepareTrustManager(certificates); KeyManager[] keyManagers = prepareKeyManager(bksFile, password); SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init( keyManagers, new TrustManager[] {new MyTrustManager(chooseTrustManager(trustManagers))}, new SecureRandom()); mOkHttpClient.setSslSocketFactory(sslContext.getSocketFactory()); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (KeyManagementException e) { e.printStackTrace(); } catch (KeyStoreException e) { e.printStackTrace(); } }
public void onGenerateClicked(View view) { try { log.debug("Key name {}", getKeyName()); log.debug("Key type {}", getKeyType()); log.debug("Key bits {}", getKeyBits()); KeyChain.getInstance(getActivity()) .generateKeyAsync(getKeyName(), getKeyType(), getKeyBits()); getActivity() .finish(); // this has to be changed if we are using single activity at some point } catch (InvalidInputException e) { log.warn("TODO: handle specific cases"); Toast.makeText(getActivity(), R.string.pk_invalid_input, Toast.LENGTH_SHORT).show(); } catch (ViewNotFoundException e) { log.error(e.getMessage(), e); } catch (KeyStoreException e) { log.error(e.getMessage(), e); } }
/** {@inheritDoc} */ public void createKeyStore(char[] store_password) throws KeyStoreException, IOException { try { KeyStore store; if (null == keystore_provider) { store = KeyStore.getInstance(keystore_type); } else { store = KeyStore.getInstance(keystore_type, keystore_provider); } store.load(null, store_password); saveKeyStore(store, store_password); } catch (NoSuchProviderException failed) { KeyStoreException failure = new KeyStoreException("NoSuchProviderException during keystore processing"); failure.initCause(failed); throw failure; } catch (NoSuchAlgorithmException failed) { KeyStoreException failure = new KeyStoreException("NoSuchAlgorithmException during keystore processing"); failure.initCause(failed); throw failure; } catch (CertificateException failed) { KeyStoreException failure = new KeyStoreException("CertificateException during keystore processing"); failure.initCause(failed); throw failure; } }