Java 类java.security.KeyStoreException 实例源码

项目:mi-firma-android    文件:UrlHttpManagerImpl.java   
/** 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;
            }
        }
    );
}
项目:openjdk-jdk10    文件:KeyStore.java   
/**
 * 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.");
    }
}
项目:nutz-pay    文件:CertUtil.java   
/**
 * 通过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;
    }
}
项目:websocket-poc    文件:App.java   
@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);
}
项目:message-broker    文件:SslHandlerFactory.java   
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);
}
项目:smart-id-java-client    文件:AuthenticationResponseValidator.java   
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);
  }
}
项目:Android-Signature    文件:ApkSignerTool.java   
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;
    }
}
项目:athena    文件:RestSBControllerImpl.java   
private CloseableHttpClient getApacheSslBypassClient() throws NoSuchAlgorithmException,
        KeyManagementException, KeyStoreException {
    return HttpClients.custom().
            setHostnameVerifier(new AllowAllHostnameVerifier()).
            setSslcontext(new SSLContextBuilder()
                                  .loadTrustMaterial(null, (arg0, arg1) -> true)
                                  .build()).build();
}
项目:openjdk-jdk10    文件:ConvertP12Test.java   
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);
    }
}
项目:q-mail    文件:MockPop3Server.java   
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);
    }
}
项目:q-mail    文件:MockPop3Server.java   
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()));
}
项目:GitHub    文件:MainActivity.java   
@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();
    }
}
项目:syndesis-qe    文件:RestUtils.java   
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;
}
项目:cyberduck    文件:DefaultX509TrustManager.java   
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;
}
项目:FirefoxData-android    文件:SSLSocketFactory.java   
/**
 * @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);
}
项目:FApkSigner    文件:ApkSignerTool.java   
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;
    }
}
项目:RISE-V2G    文件:SecurityUtils.java   
/**
 * 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;
}
项目:alexa-gira-bridge    文件:Util.java   
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;
}
项目:jdk8u-jdk    文件:PKIXParameters.java   
/**
 * 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>();
}
项目:jdk8u-jdk    文件:JceKeyStore.java   
/**
 * 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);
    }
}
项目:osc-core    文件:KeyStoreProvider.java   
/**
 * 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);
    }
}
项目:AgentWorkbench    文件:OIDCPanel.java   
@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);
        }
    }
}
项目:SmartChart    文件:HttpsUtils.java   
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);
    }
}
项目:MQTT-Essentials-A-Lightweight-IoT-Protocol    文件:SecurityHelper.java   
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;
}
项目:AgentWorkbench    文件:TrustStoreController.java   
/**
 * 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();
    }
}
项目:AgentWorkbench    文件:TrustStoreController.java   
/**
 * 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() + "!");
        }
    }
}
项目:javaide    文件:JKS.java   
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);
    }
}
项目:AgentWorkbench    文件:KeyStoreController.java   
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();
    }
}
项目:RISE-V2G    文件:SecurityUtils.java   
/**
 * 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;
}
项目:jdk8u-jdk    文件:PKCS12KeyStore.java   
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 +
            "'");
    }
}
项目:Java-APIs    文件:CloudSemanticEnhancement.java   
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());
        }
    }
项目:aos-FileCoreLibrary    文件:KeyManagerUtils.java   
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");
}
项目:jetfuel    文件:X509CertificateWithKey.java   
public void loadPfx(byte[] bytes, String password)
        throws NoSuchAlgorithmException,
            CertificateException,
            KeyStoreException,
            UnrecoverableEntryException,
            IOException {
    loadPfx(new ByteArrayInputStream(bytes), password);
}
项目:BTNotifierAndroid    文件:Server.java   
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());
}
项目:FirefoxData-android    文件:SSLContextBuilder.java   
public SSLContextBuilder loadKeyMaterial(
        final KeyStore keystore,
        final char[] keyPassword)
            throws NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException {
    loadKeyMaterial(keystore, keyPassword, null);
    return this;
}
项目:devops-cstack    文件:KeyStoreUtils.java   
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);
    }
}
项目:chromium-net-for-android    文件:X509Util.java   
/**
 * 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();
}
项目:OpenJSharp    文件:KeyStore.java   
/**
 * 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;
        }
    }
}
项目:okhttpUtil    文件:HttpsUtil.java   
public MyTrustManager(X509TrustManager localTrustManager) throws NoSuchAlgorithmException, KeyStoreException
{
    TrustManagerFactory var4 = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    var4.init((KeyStore) null);
    defaultTrustManager = chooseTrustManager(var4.getTrustManagers());
    this.localTrustManager = localTrustManager;
}
项目:oscm    文件:X509KeySelector.java   
KeySelectorResult getPublicKeyFromKeystore(X509Certificate certificate,
        SignatureMethod signatureMethod) throws KeyStoreException,
        KeySelectorException {

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