Java Code Examples for java.security.KeyStoreException

The following are top voted examples for showing how to use java.security.KeyStoreException. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: mi-firma-android   File: UrlHttpManagerImpl.java   View source code 8 votes vote down vote up
/** Deshabilita las comprobaciones de certificados en conexiones SSL, aceptádose entonces
 * cualquier certificado.
 * @throws KeyManagementException Si hay problemas en la gestión de claves SSL.
 * @throws NoSuchAlgorithmException Si el JRE no soporta algún algoritmo necesario.
 * @throws KeyStoreException Si no se puede cargar el KeyStore SSL.
 * @throws IOException Si hay errores en la carga del fichero KeyStore SSL.
 * @throws CertificateException Si los certificados del KeyStore SSL son inválidos.
 * @throws UnrecoverableKeyException Si una clave del KeyStore SSL es inválida.
 * @throws NoSuchProviderException Si ocurre un error al recuperar la instancia del Keystore.*/
public static void disableSslChecks() throws KeyManagementException,
                                             NoSuchAlgorithmException,
                                             KeyStoreException,
                                             UnrecoverableKeyException,
                                             CertificateException,
                                             IOException,
                                             NoSuchProviderException {
	final SSLContext sc = SSLContext.getInstance(SSL_CONTEXT);
	sc.init(getKeyManager(), DUMMY_TRUST_MANAGER, new java.security.SecureRandom());
	HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
	HttpsURLConnection.setDefaultHostnameVerifier(
		new HostnameVerifier() {
			@Override
			public boolean verify(final String hostname, final SSLSession session) {
				return true;
			}
		}
	);
}
 
Example 2
Project: websocket-poc   File: App.java   View source code 8 votes vote down vote up
@Bean
public RestTemplate restTemplate() throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {

    SSLContext sslContext = SSLContexts.custom()
            .loadTrustMaterial(null, new TrustSelfSignedStrategy())
            .build();

    SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
    CloseableHttpClient httpClient = HttpClients.custom()
            .setSSLSocketFactory(sslConnectionSocketFactory)
            .build();

    HttpComponentsClientHttpRequestFactory requestFactory =
            new HttpComponentsClientHttpRequestFactory();

    requestFactory.setHttpClient(httpClient);

    return new RestTemplate(requestFactory);
}
 
Example 3
Project: openjdk-jdk10   File: KeyStore.java   View source code 7 votes vote down vote up
/**
 * Assigns the given certificate to the given alias.
 *
 * <p>If the given alias already exists in this keystore and identifies a
 * <i>trusted certificate entry</i>, the certificate associated with it is
 * overridden by the given certificate.
 *
 * @param alias the alias name
 * @param cert the certificate
 *
 * @exception KeyStoreException if the given alias already exists and does
 * not identify a <i>trusted certificate entry</i>, or this operation
 * fails for some other reason.
 */
public void engineSetCertificateEntry(String alias, Certificate cert)
    throws KeyStoreException
{
    if (alias == null) {
        throw new KeyStoreException("alias must not be null");
    }

    if (cert instanceof X509Certificate) {

        // TODO - build CryptoAPI chain?
        X509Certificate[] chain =
            new X509Certificate[]{ (X509Certificate) cert };
        KeyEntry entry = entries.get(alias);

        if (entry == null) {
            entry =
                new KeyEntry(alias, null, chain);
            storeWithUniqueAlias(alias, entry);
        }

        if (entry.getPrivateKey() == null) { // trusted-cert entry
            entry.setAlias(alias);

            try {
                entry.setCertificateChain(chain);

            } catch (CertificateException ce) {
                throw new KeyStoreException(ce);
            }
        }

    } else {
        throw new UnsupportedOperationException(
            "Cannot assign the certificate to the given alias.");
    }
}
 
Example 4
Project: nutz-pay   File: CertUtil.java   View source code 7 votes vote down vote up
/**
 * 通过keystore获取私钥证书的certId值
 * @param keyStore
 * @return
 */
private static String getCertIdIdByStore(KeyStore keyStore) {
	Enumeration<String> aliasenum = null;
	try {
		aliasenum = keyStore.aliases();
		String keyAlias = null;
		if (aliasenum.hasMoreElements()) {
			keyAlias = aliasenum.nextElement();
		}
		X509Certificate cert = (X509Certificate) keyStore
				.getCertificate(keyAlias);
		return cert.getSerialNumber().toString();
	} catch (KeyStoreException e) {
		log.error("getCertIdIdByStore Error", e);
		return null;
	}
}
 
Example 5
Project: message-broker   File: SslHandlerFactory.java   View source code 7 votes vote down vote up
public SslHandlerFactory(AmqpServerConfiguration configuration) throws KeyStoreException, IOException,
        CertificateException, NoSuchAlgorithmException, UnrecoverableKeyException, KeyManagementException {
    KeyStore keyStore = getKeyStore(configuration.getSsl().getKeyStore().getType(),
                                    configuration.getSsl().getKeyStore().getLocation(),
                                    configuration.getSsl().getKeyStore().getPassword());
    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(configuration.getSsl()
                                                                                     .getKeyStore()
                                                                                     .getCertType());
    keyManagerFactory.init(keyStore, configuration.getSsl().getKeyStore().getPassword().toCharArray());

    KeyStore trustStore = getKeyStore(configuration.getSsl().getTrustStore().getType(),
                                      configuration.getSsl().getTrustStore().getLocation(),
                                      configuration.getSsl().getTrustStore().getPassword());
    TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(configuration.getSsl()
                                                                           .getTrustStore()
                                                                           .getCertType());
    trustManagerFactory.init(trustStore);

    sslContext = SSLContext.getInstance(configuration.getSsl().getProtocol());
    sslContext.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);
}
 
Example 6
Project: smart-id-java-client   File: AuthenticationResponseValidator.java   View source code 6 votes vote down vote up
private void initializeTrustedCACertificatesFromKeyStore() {
  try {
    InputStream is = AuthenticationResponseValidator.class.getResourceAsStream("/trusted_certificates.jks");
    KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
    keystore.load(is, "changeit".toCharArray());
    Enumeration<String> aliases = keystore.aliases();
    while (aliases.hasMoreElements()) {
      String alias = aliases.nextElement();
      X509Certificate certificate = (X509Certificate) keystore.getCertificate(alias);
      addTrustedCACertificate(certificate);
    }
  } catch (IOException | CertificateException | KeyStoreException | NoSuchAlgorithmException e) {
    logger.error("Error initializing trusted CA certificates", e);
    throw new TechnicalErrorException("Error initializing trusted CA certificates", e);
  }
}
 
Example 7
Project: Android-Signature   File: ApkSignerTool.java   View source code 6 votes vote down vote up
private static Key getKeyStoreKey(KeyStore ks, String keyAlias, List<char[]> passwords)
        throws UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException {
    UnrecoverableKeyException lastFailure = null;
    for (char[] password : passwords) {
        try {
            return ks.getKey(keyAlias, password);
        } catch (UnrecoverableKeyException e) {
            lastFailure = e;
        }
    }
    if (lastFailure == null) {
        throw new RuntimeException("No key passwords");
    } else {
        throw lastFailure;
    }
}
 
Example 8
Project: athena   File: RestSBControllerImpl.java   View source code 6 votes vote down vote up
private CloseableHttpClient getApacheSslBypassClient() throws NoSuchAlgorithmException,
        KeyManagementException, KeyStoreException {
    return HttpClients.custom().
            setHostnameVerifier(new AllowAllHostnameVerifier()).
            setSslcontext(new SSLContextBuilder()
                                  .loadTrustMaterial(null, (arg0, arg1) -> true)
                                  .build()).build();
}
 
Example 9
Project: openjdk-jdk10   File: ConvertP12Test.java   View source code 6 votes vote down vote up
private void compareKeyEntry(KeyStore a, KeyStore b, String aPass,
        String bPass, String alias) throws KeyStoreException,
        UnrecoverableKeyException, NoSuchAlgorithmException {
    Certificate[] certsA = a.getCertificateChain(alias);
    Certificate[] certsB = b.getCertificateChain(alias);

    if (!Arrays.equals(certsA, certsB)) {
        throw new RuntimeException("Certs don't match for alias:" + alias);
    }

    Key keyA = a.getKey(alias, aPass.toCharArray());
    Key keyB = b.getKey(alias, bPass.toCharArray());

    if (!keyA.equals(keyB)) {
        throw new RuntimeException(
                "Key don't match for alias:" + alias);
    }
}
 
Example 10
Project: q-mail   File: MockPop3Server.java   View source code 6 votes vote down vote up
private void handleInteractions(Socket socket) throws IOException, KeyStoreException,
        NoSuchAlgorithmException, CertificateException, UnrecoverableKeyException, KeyManagementException,
        UnexpectedCommandException {

    ImapInteraction interaction = interactions.pop();
    if (interaction instanceof ExpectedCommand) {
        readExpectedCommand((ExpectedCommand) interaction);
    } else if (interaction instanceof CannedResponse) {
        writeCannedResponse((CannedResponse) interaction);
    } else if (interaction instanceof CloseConnection) {
        clientSocket.close();
    } else if (interaction instanceof EnableCompression) {
        enableCompression(socket);
    } else if (interaction instanceof UpgradeToTls) {
        upgradeToTls(socket);
    }
}
 
Example 11
Project: q-mail   File: MockPop3Server.java   View source code 6 votes vote down vote up
private void upgradeToTls(Socket socket) throws KeyStoreException, IOException, NoSuchAlgorithmException,
        CertificateException, UnrecoverableKeyException, KeyManagementException {

    KeyStore keyStore = keyStoreProvider.getKeyStore();

    String defaultAlgorithm = KeyManagerFactory.getDefaultAlgorithm();
    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(defaultAlgorithm);
    keyManagerFactory.init(keyStore, keyStoreProvider.getPassword());

    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(keyManagerFactory.getKeyManagers(), null, null);
    SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();

    SSLSocket sslSocket = (SSLSocket) sslSocketFactory.createSocket(
            socket, socket.getInetAddress().getHostAddress(), socket.getPort(), true);
    sslSocket.setUseClientMode(false);
    sslSocket.startHandshake();

    input = Okio.buffer(Okio.source(sslSocket.getInputStream()));
    output = Okio.buffer(Okio.sink(sslSocket.getOutputStream()));
}
 
Example 12
Project: GitHub   File: MainActivity.java   View source code 6 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    txtKeystoreState = (TextView) findViewById(R.id.txtLabelKeyStore);

    try {
        secureUserStore = new SecureUserStore(this);
        SyncManager.setUserStore(secureUserStore);

        if (secureUserStore.isKeystoreUnlocked()) {
            buildSyncConf();
            keystoreUnlockedMessage();
        } else {
            secureUserStore.unlockKeystore();
        }
    } catch (KeyStoreException e) {
        e.printStackTrace();
    }
}
 
Example 13
Project: syndesis-qe   File: RestUtils.java   View source code 6 votes vote down vote up
private static HttpClient createAllTrustingClient() throws RestClientException {
	HttpClient httpclient = null;
	try {
		final SSLContextBuilder builder = new SSLContextBuilder();
		builder.loadTrustMaterial((TrustStrategy) (X509Certificate[] chain, String authType) -> true);
		final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
				builder.build());
		httpclient = HttpClients
				.custom()
				.setSSLSocketFactory(sslsf)
				.setMaxConnTotal(1000)
				.setMaxConnPerRoute(1000)
				.build();
	} catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) {
		throw new RestClientException("Cannot create all SSL certificates trusting client", e);
	}
	return httpclient;
}
 
Example 14
Project: cyberduck   File: DefaultX509TrustManager.java   View source code 6 votes vote down vote up
public DefaultX509TrustManager init() throws IOException {
    try {
        final TrustManagerFactory factory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        factory.init(KeyStore.getInstance(KeyStore.getDefaultType()));
        final TrustManager[] trustmanagers = factory.getTrustManagers();
        if(trustmanagers.length == 0) {
            throw new NoSuchAlgorithmException("SunX509 trust manager not supported");
        }
        system = (javax.net.ssl.X509TrustManager) trustmanagers[0];
    }
    catch(NoSuchAlgorithmException | KeyStoreException e) {
        log.error(String.format("Initialization of trust store failed. %s", e.getMessage()));
        throw new IOException(e);
    }
    return this;
}
 
Example 15
Project: FirefoxData-android   File: SSLSocketFactory.java   View source code 6 votes vote down vote up
/**
 * @since 4.1
 */
public SSLSocketFactory(
        final String algorithm,
        final KeyStore keystore,
        final String keyPassword,
        final KeyStore truststore,
        final SecureRandom random,
        final TrustStrategy trustStrategy,
        final X509HostnameVerifier hostnameVerifier)
            throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
    this(SSLContexts.custom()
            .useProtocol(algorithm)
            .setSecureRandom(random)
            .loadKeyMaterial(keystore, keyPassword != null ? keyPassword.toCharArray() : null)
            .loadTrustMaterial(truststore, trustStrategy)
            .build(),
            hostnameVerifier);
}
 
Example 16
Project: FApkSigner   File: ApkSignerTool.java   View source code 6 votes vote down vote up
private static Key getKeyStoreKey(KeyStore ks, String keyAlias, List<char[]> passwords)
        throws UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException {
    UnrecoverableKeyException lastFailure = null;
    for (char[] password : passwords) {
        try {
            return ks.getKey(keyAlias, password);
        } catch (UnrecoverableKeyException e) {
            lastFailure = e;
        }
    }
    if (lastFailure == null) {
        throw new RuntimeException("No key passwords");
    } else {
        throw lastFailure;
    }
}
 
Example 17
Project: RISE-V2G   File: SecurityUtils.java   View source code 6 votes vote down vote up
/**
 * Returns a standard keystore which holds the respective credentials (private key and certificate chain).
 * 
 * @param keyStoreIS The input stream of the keystore
 * @param keyStorePassword The password which protects the keystore
 * @param keyStoreType The type of the keystore, either "jks" or "pkcs12"
 * @return The respective keystore
 */
private static KeyStore getKeyStore(InputStream keyStoreIS, String keyStorePassword, String keyStoreType) {
	KeyStore keyStore = null;
	
	try {
		keyStore = KeyStore.getInstance(keyStoreType);
		keyStore.load(keyStoreIS, keyStorePassword.toCharArray());
		keyStoreIS.close();
		return keyStore;
	} catch (KeyStoreException | NoSuchAlgorithmException | CertificateException | 
			IOException | NullPointerException e) {
		getLogger().error(e.getClass().getSimpleName() + " occurred while trying to load keystore", e);
	} 
	
	return null;
}
 
Example 18
Project: alexa-gira-bridge   File: Util.java   View source code 6 votes vote down vote up
public static String triggerHttpGetWithCustomSSL(String requestUrl) {
	String result = null;
	try {
		SSLContextBuilder builder = new SSLContextBuilder();
		builder.loadTrustMaterial(null, new TrustSelfSignedStrategy() {
			public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
				return true;
			}
		});
		@SuppressWarnings("deprecation")
		HostnameVerifier hostnameVerifier = SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;

		SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build(), hostnameVerifier);

		CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();

		HttpGet httpGet = new HttpGet("https://" + requestUrl);
		CloseableHttpResponse response = httpclient.execute(httpGet);
		try {
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				HttpEntity entity = response.getEntity();
				result = EntityUtils.toString(entity);
				log.debug("Received response: " + result);
			} else {
				log.error("Request not successful. StatusCode was " + response.getStatusLine().getStatusCode());
			}
		} finally {
			response.close();
		}
	} catch (IOException | KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) {
		log.error("Error executing the request.", e);
	}
	return result;
}
 
Example 19
Project: jdk8u-jdk   File: PKIXParameters.java   View source code 6 votes vote down vote up
/**
 * Creates an instance of {@code PKIXParameters} that
 * populates the set of most-trusted CAs from the trusted
 * certificate entries contained in the specified {@code KeyStore}.
 * Only keystore entries that contain trusted {@code X509Certificates}
 * are considered; all other certificate types are ignored.
 *
 * @param keystore a {@code KeyStore} from which the set of
 * most-trusted CAs will be populated
 * @throws KeyStoreException if the keystore has not been initialized
 * @throws InvalidAlgorithmParameterException if the keystore does
 * not contain at least one trusted certificate entry
 * @throws NullPointerException if the keystore is {@code null}
 */
public PKIXParameters(KeyStore keystore)
    throws KeyStoreException, InvalidAlgorithmParameterException
{
    if (keystore == null)
        throw new NullPointerException("the keystore parameter must be " +
            "non-null");
    Set<TrustAnchor> hashSet = new HashSet<TrustAnchor>();
    Enumeration<String> aliases = keystore.aliases();
    while (aliases.hasMoreElements()) {
        String alias = aliases.nextElement();
        if (keystore.isCertificateEntry(alias)) {
            Certificate cert = keystore.getCertificate(alias);
            if (cert instanceof X509Certificate)
                hashSet.add(new TrustAnchor((X509Certificate)cert, null));
        }
    }
    setTrustAnchors(hashSet);
    this.unmodInitialPolicies = Collections.<String>emptySet();
    this.certPathCheckers = new ArrayList<PKIXCertPathChecker>();
    this.certStores = new ArrayList<CertStore>();
}
 
Example 20
Project: jdk8u-jdk   File: JceKeyStore.java   View source code 6 votes vote down vote up
/**
 * Assigns the given key (that has already been protected) to the given
 * alias.
 *
 * <p>If the protected 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 (in protected format) to be associated with the alias
 * @param chain the certificate chain for the corresponding public
 * key (only useful if the protected key is of type
 * <code>java.security.PrivateKey</code>).
 *
 * @exception KeyStoreException if this operation fails.
 */
public void engineSetKeyEntry(String alias, byte[] key,
                              Certificate[] chain)
    throws KeyStoreException
{
    synchronized(entries) {
        // We assume it's a private key, because there is no standard
        // (ASN.1) encoding format for wrapped secret keys
        PrivateKeyEntry entry = new PrivateKeyEntry();
        entry.date = new Date();

        entry.protectedKey = key.clone();
        if ((chain != null) &&
            (chain.length != 0)) {
            entry.chain = chain.clone();
        } else {
            entry.chain = null;
        }

        entries.put(alias.toLowerCase(Locale.ENGLISH), entry);
    }
}
 
Example 21
Project: osc-core   File: KeyStoreProvider.java   View source code 6 votes vote down vote up
/**
 * Puts password in keystore under given alias. Secret password is secured with the entry password.
 * The keystore change is persistant.
 * @param alias alias to secret password
 * @param password password to store as secret
 * @param entryPassword password to secret password
 * @throws KeyStoreProviderException
 */
public void putPassword(String alias, String password, String entryPassword) throws KeyStoreProviderException {
    try {
        LOG.info(String.format("Putting password with alias %s in keystore ...", alias));

        SecretKeyFactory skFactory = SecretKeyFactory.getInstance(SECRET_KEY_PASSWORD_ALGORITHM);
        SecretKey secret = skFactory.generateSecret(new PBEKeySpec(password.toCharArray()));
        this.keystore.setEntry(alias, new KeyStore.SecretKeyEntry(secret),
                new KeyStore.PasswordProtection(entryPassword.toCharArray()));
        factory.persist(this.keystore);
    } catch (NoSuchAlgorithmException nsae) {
        throw new KeyStoreProviderException("Algorithm used to create PBE secret cannot be found.", nsae);
    } catch (InvalidKeySpecException ikse) {
        throw new KeyStoreProviderException("Invalid key spec used to create PBE secret.", ikse);
    } catch (KeyStoreException kse) {
        throw new KeyStoreProviderException("Failed to put PBE secret to keystore.", kse);
    } catch (Exception e) {
        throw new KeyStoreProviderException("Failed to put PBE secret in keystore", e);
    }
}
 
Example 22
Project: AgentWorkbench   File: OIDCPanel.java   View source code 6 votes vote down vote up
@Override
public void actionPerformed(ActionEvent ae) {

	String actCMD = ae.getActionCommand();
	if (actCMD.equalsIgnoreCase(COMMAND_CONNECT)) {
		char[] pswd = getJPasswordField().getPassword();
		String userName = getJTextFieldUsername().getText().trim();
		try {
			displayResult(owner.authorizeByUserAndPW(userName, new String(pswd)),null, userName);
		} catch (URISyntaxException | IOException | KeyManagementException | NoSuchAlgorithmException | CertificateException | KeyStoreException e) {
			displayResult(false, e.getLocalizedMessage(), null);
			e.printStackTrace();
		}

	} else {
		if (parentGUI != null) {
			parentGUI.actionPerformed(ae);
		}
	}
}
 
Example 23
Project: SmartChart   File: HttpsUtils.java   View source code 6 votes vote down vote up
public static SSLParams getSslSocketFactory(InputStream[] certificates, InputStream bksFile, String password) {
    SSLParams sslParams = new SSLParams();
    try {
        TrustManager[] trustManagers = prepareTrustManager(certificates);
        KeyManager[] keyManagers = prepareKeyManager(bksFile, password);
        SSLContext sslContext = SSLContext.getInstance("TLS");
        X509TrustManager trustManager = null;
        if (trustManagers != null) {
            trustManager = new MyTrustManager(chooseTrustManager(trustManagers));
        } else {
            trustManager = new UnSafeTrustManager();
        }
        sslContext.init(keyManagers, new TrustManager[]{trustManager}, null);
        sslParams.sSLSocketFactory = sslContext.getSocketFactory();
        sslParams.trustManager = trustManager;
        return sslParams;
    } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) {
        throw new AssertionError(e);
    }
}
 
Example 24
Project: MQTT-Essentials-A-Lightweight-IoT-Protocol   File: SecurityHelper.java   View source code 6 votes vote down vote up
private static TrustManagerFactory createTrustManagerFactory(
	final String caCertificateFileName) 
	throws CertificateException, NoSuchAlgorithmException, IOException, KeyStoreException 
{
	// Creates a trust manager factory
	// Load CA certificate
	final X509Certificate caCertificate = (X509Certificate) createX509CertificateFromFile(caCertificateFileName);
	// CA certificate is used to authenticate server
	final KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); 
	keyStore.load(null, null);
	keyStore.setCertificateEntry("ca-certificate", caCertificate);
	final TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
	trustManagerFactory.init(keyStore);

	return trustManagerFactory;
}
 
Example 25
Project: AgentWorkbench   File: TrustStoreController.java   View source code 6 votes vote down vote up
/**
 * This Initializes the TrustStoreController.
 */
public TrustStoreController(Dialog ownerDialog, File trustStoreFile, String trustStorePassword, boolean edit) {
	this.ownerDialog = ownerDialog;
	try {
		trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
		if (trustStoreFile != null && trustStorePassword != null) {
			if(edit){
				openTrustStore(trustStoreFile, trustStorePassword);
			} else {
				createTrustStore(trustStoreFile, trustStorePassword);
			}
		}
	} catch (KeyStoreException e) {
		e.printStackTrace();
	}
}
 
Example 26
Project: AgentWorkbench   File: TrustStoreController.java   View source code 6 votes vote down vote up
/**
 * Save the trust store.
 * @param trustStorePassword the trust store password
 */
public void saveTrustStore(String trustStorePassword) {
	try {
		// ----- Create a FileOutputStream --------------------------------
		trustStoreOutputStream = new FileOutputStream(trustStoreFile);
		// ----- Store the TrustStore -------------------------------
		trustStore.store(trustStoreOutputStream, trustStorePassword.toCharArray());
		// ----- Close the FileOutputStream -------------------------------
		trustStoreOutputStream.close();
	} catch (FileNotFoundException | KeyStoreException | NoSuchAlgorithmException | CertificateException e) {
		e.printStackTrace();
	} catch (IOException e1) {
		e1.printStackTrace();
		if (ownerDialog != null) {
			JOptionPane.showMessageDialog(ownerDialog, e1.getMessage() + "!");
		}
	}
}
 
Example 27
Project: javaide   File: JKS.java   View source code 6 votes vote down vote up
public void engineSetKeyEntry(String alias, byte[] encodedKey, Certificate[] certChain)
    throws KeyStoreException
{
    alias = alias.toLowerCase();
    if (trustedCerts.containsKey(alias))
        throw new KeyStoreException("\"" + alias + "\" is a trusted certificate entry");
    try
    {
        new EncryptedPrivateKeyInfo(encodedKey);
    }
    catch (IOException ioe)
    {
        throw new KeyStoreException("encoded key is not an EncryptedPrivateKeyInfo");
    }
    privateKeys.put(alias, encodedKey);
    if (certChain != null)
        certChains.put(alias, certChain);
    else
        certChains.put(alias, new Certificate[0]);
    if (!aliases.contains(alias))
    {
        dates.put(alias, new Date());
        aliases.add(alias);
    }
}
 
Example 28
Project: AgentWorkbench   File: KeyStoreController.java   View source code 6 votes vote down vote up
public void printAliasesList(String keyPasswd) {
	try {
		System.out.println("trustStoreType=" + trustStore.getType());
		System.out.println("size=" + trustStore.size());

		// --- Get All TrustStore's Certificates Alias -----------
		Enumeration<String> enumeration = trustStore.aliases();
		while (enumeration.hasMoreElements()) {
			String alias = enumeration.nextElement();
			System.out.println("alias=" + alias);
			// Entry entry = trustStore.getEntry(alias, null);

			Entry entry = trustStore.getEntry(alias, new PasswordProtection(keyPasswd.toCharArray()));

			System.out.println("entryClass=" + entry.getClass());
		}
	} catch (KeyStoreException | NoSuchAlgorithmException | UnrecoverableEntryException e) {
		e.printStackTrace();
	}
}
 
Example 29
Project: RISE-V2G   File: SecurityUtils.java   View source code 6 votes vote down vote up
/**
 * Returns the mobility operator Sub-CA 2 certificate (MOSubCA2 certificate) which can verify the signature of the  
 * contract certificate from the given keystore. The public key of the MOSub2Certificate is then used to verify 
 * the signature of sales tariffs.
 * 
 * @param keyStoreFileName The relative path and file name of the keystore
 * @return The X.509 mobility operator Sub-CA2 certificate (a certificate from a Sub-CA)
 */
public static X509Certificate getMOSubCA2Certificate(String keyStoreFileName) {
	KeyStore keystore = getKeyStore(keyStoreFileName, GlobalValues.PASSPHRASE_FOR_CERTIFICATES_AND_KEYS.toString());
	X509Certificate moSubCA2Certificate = null;
	
	try {
		Certificate[] certChain = keystore.getCertificateChain(GlobalValues.ALIAS_CONTRACT_CERTIFICATE.toString());
		X509Certificate contractCertificate = getLeafCertificate(certChain);
		SubCertificatesType subCertificates = getSubCertificates(certChain); 
		
		for (byte[] certificate : subCertificates.getCertificate()) {
			X509Certificate x509Cert = getCertificate(certificate);
			if (contractCertificate.getIssuerX500Principal().getName().equals(
				x509Cert.getSubjectX500Principal().getName())) {
				moSubCA2Certificate = x509Cert;
				break;
			}
		}
	} catch (KeyStoreException e) {
		getLogger().error("KeyStoreException occurred while trying to get MOSubCA2 certificate");
	}
	
	return moSubCA2Certificate;
}
 
Example 30
Project: jdk8u-jdk   File: PKCS12KeyStore.java   View source code 6 votes vote down vote up
private void setCertEntry(String alias, Certificate cert,
    Set<KeyStore.Entry.Attribute> attributes) throws KeyStoreException {

    Entry entry = entries.get(alias.toLowerCase(Locale.ENGLISH));
    if (entry != null && entry instanceof KeyEntry) {
        throw new KeyStoreException("Cannot overwrite own certificate");
    }

    CertEntry certEntry =
        new CertEntry((X509Certificate) cert, null, alias, AnyUsage,
            attributes);
    certificateCount++;
    entries.put(alias, certEntry);

    if (debug != null) {
        debug.println("Setting a trusted certificate at alias '" + alias +
            "'");
    }
}
 
Example 31
Project: Java-APIs   File: CloudSemanticEnhancement.java   View source code 6 votes vote down vote up
public static void main(String[] args) throws SESException, KeyManagementException, ClientProtocolException, NoSuchAlgorithmException, KeyStoreException, IOException, CloudException {

		// Create the Cloud Access API Token from the supplied key
		TokenFetcher tokenFetcher = new TokenFetcher(CloudConfiguration.get("tokenRequestURL"), CloudConfiguration.get("apiKey"));
		Token token = tokenFetcher.getAccessToken();

		// Create the Semantic Enhancement Server client 
		SESClient sesClient = new SESClient();
		sesClient.setUrl(CloudConfiguration.get("sesUrl"));
		sesClient.setApiToken(token.getAccess_token());
		sesClient.setOntology("ProductSupport");

//		sesClient.setProxyHost("localhost");
//		sesClient.setProxyPort(8888);


		// Fetch term details for particular term
		Term term = sesClient.getTermDetails("39581488874379468426238", DetailLevel.FULL);
		System.out.println(term);

		Metadata metadata = term.getMetadata();
		for (Map.Entry<String, Field> entry: metadata.getFields().entrySet()) {
			System.out.println(entry.getValue().getName() + " : " + entry.getValue().getValue());
		}
	}
 
Example 32
Project: aos-FileCoreLibrary   File: KeyManagerUtils.java   View source code 5 votes vote down vote up
private static String findAlias(KeyStore ks) throws KeyStoreException {
    Enumeration<String> e = ks.aliases();
    while(e.hasMoreElements()) {
        String entry = e.nextElement();
        if (ks.isKeyEntry(entry)) {
            return entry;
        }
    }
    throw new KeyStoreException("Cannot find a private key entry");
}
 
Example 33
Project: jetfuel   File: X509CertificateWithKey.java   View source code 5 votes vote down vote up
public void loadPfx(byte[] bytes, String password)
		throws NoSuchAlgorithmException,
			CertificateException,
			KeyStoreException,
			UnrecoverableEntryException,
			IOException {
	loadPfx(new ByteArrayInputStream(bytes), password);
}
 
Example 34
Project: BTNotifierAndroid   File: Server.java   View source code 5 votes vote down vote up
private void startNetwork() {
    if (networkAvailable()) {
        try {
            if (ssl) {
                networkConnectionProvider = new SslNetworkConnectionProvider(this, new File(context.getFilesDir(), "custom.bks"));
            } else {
                networkConnectionProvider = new NetworkConnectionProvider(this);
            }
            networkConnectionProvider.start();
        } catch (CertificateException | NoSuchAlgorithmException | KeyStoreException | IOException e) {
            Log.e(TAG, "Error creating SSL server", e);
        }
    }
    notifyListener(getStatusMessage());
}
 
Example 35
Project: FirefoxData-android   File: SSLContextBuilder.java   View source code 5 votes vote down vote up
public SSLContextBuilder loadKeyMaterial(
        final KeyStore keystore,
        final char[] keyPassword)
            throws NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException {
    loadKeyMaterial(keystore, keyPassword, null);
    return this;
}
 
Example 36
Project: devops-cstack   File: KeyStoreUtils.java   View source code 5 votes vote down vote up
private static void addCA(KeyStore keyStore, String caPath)
		throws KeyStoreException, FileNotFoundException, CertificateException {
	for (Certificate cert : loadCertificates(caPath)) {
		X509Certificate crt = (X509Certificate) cert;
		String alias = crt.getSubjectX500Principal().getName();
		keyStore.setCertificateEntry(alias, crt);
	}
}
 
Example 37
Project: chromium-net-for-android   File: X509Util.java   View source code 5 votes vote down vote up
/**
 * After each modification by the system of the key store, trust manager has to be regenerated.
 */
private static void reloadDefaultTrustManager() throws KeyStoreException,
        NoSuchAlgorithmException, CertificateException {
    synchronized (sLock) {
        sDefaultTrustManager = null;
        sSystemTrustAnchorCache = null;
        ensureInitializedLocked();
    }
    nativeNotifyKeyChainChanged();
}
 
Example 38
Project: OpenJSharp   File: KeyStore.java   View source code 5 votes vote down vote up
/**
 * Deletes the entry identified by the given alias from this keystore.
 *
 * @param alias the alias name
 *
 * @exception KeyStoreException if the entry cannot be removed.
 */
public void engineDeleteEntry(String alias)
    throws KeyStoreException
{
    if (alias == null) {
        throw new KeyStoreException("alias must not be null");
    }

    for (KeyEntry entry : entries) {
        if (alias.equals(entry.getAlias())) {

            // Get end-entity certificate and remove from system cert store
            X509Certificate[] certChain = entry.getCertificateChain();
            if (certChain != null) {

                try {

                    byte[] encoding = certChain[0].getEncoded();
                    removeCertificate(getName(), alias, encoding,
                        encoding.length);

                } catch (CertificateException e) {
                    throw new KeyStoreException("Cannot remove entry: " +
                        e);
                }
            }
            Key privateKey = entry.getPrivateKey();
            if (privateKey != null) {
                destroyKeyContainer(
                    Key.getContainerName(privateKey.getHCryptProvider()));
            }

            entries.remove(entry);
            break;
        }
    }
}
 
Example 39
Project: okhttpUtil   File: HttpsUtil.java   View source code 5 votes vote down vote up
public MyTrustManager(X509TrustManager localTrustManager) throws NoSuchAlgorithmException, KeyStoreException
{
    TrustManagerFactory var4 = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    var4.init((KeyStore) null);
    defaultTrustManager = chooseTrustManager(var4.getTrustManagers());
    this.localTrustManager = localTrustManager;
}
 
Example 40
Project: oscm   File: X509KeySelector.java   View source code 5 votes vote down vote up
KeySelectorResult getPublicKeyFromKeystore(X509Certificate certificate,
        SignatureMethod signatureMethod) throws KeyStoreException,
        KeySelectorException {

    isSigningCertificate(certificate);
    return searchInKeystore(certificate, signatureMethod);
}