Java Code Examples for java.security.KeyStore

The following are top voted examples for showing how to use java.security.KeyStore. 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: mapbook-android   File: CredentialCryptographer.java   Source Code and License 8 votes vote down vote up
/**
 * Create a new key in the Keystore
 */
private void createNewKey(){
  try {
    final KeyStore keyStore = KeyStore.getInstance(AndroidKeyStore);
    keyStore.load(null);

    final KeyGenerator keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, AndroidKeyStore);

    // Build one key to be used for encrypting and decrypting the file
    keyGenerator.init(
        new KeyGenParameterSpec.Builder(ALIAS,
            KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
            .setBlockModes(KeyProperties.BLOCK_MODE_GCM)
            .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
            .build());
    keyGenerator.generateKey();
    Log.i(TAG, "Key created in Keystore");

  }catch (KeyStoreException | InvalidAlgorithmParameterException | NoSuchProviderException | NoSuchAlgorithmException | CertificateException | IOException  kS){
    Log.e(TAG, kS.getMessage());
  }
}
 
Example 2
Project: jdk8u-jdk   File: MetadataStoreLoadTest.java   Source Code and License 6 votes vote down vote up
private void storeAttrs() throws UnrecoverableEntryException,
        GeneralSecurityException, NoSuchAlgorithmException,
        KeyStoreException, IOException {
    KeyStore ksIn = Utils.loadKeyStore(KEYSTORE_PATH,
            Utils.KeyStoreType.pkcs12, PASSWORD);
    KeyStore ksAttr = KeyStore
            .getInstance(Utils.KeyStoreType.pkcs12.name());
    ksAttr.load(null);
    Key key = ksIn.getKey(ALIAS, PASSWORD);
    Certificate cert = ksIn.getCertificate(ALIAS);
    Set<KeyStore.Entry.Attribute> attrs =
            new HashSet<>(Arrays.asList(ATTR_SET));
    KeyStore.Entry e = new KeyStore.PrivateKeyEntry((PrivateKey) key,
            new Certificate[]{cert}, attrs);
    ksAttr.setEntry(ALIAS, e, new KeyStore.PasswordProtection(
            KEY_PASSWORD));

    out.println("Attributes before store:");
    e.getAttributes().stream().forEach((attr) -> {
        out.println(attr.getName() + ", '" + attr.getValue() + "'");
    });
    Utils.saveKeyStore(ksAttr, WORKING_DIRECTORY + File.separator
            + KESTORE_NEW, PASSWORD);
}
 
Example 3
Project: jdk8u-jdk   File: ClientHelloRead.java   Source Code and License 6 votes vote down vote up
private static ServerSocketFactory getServerSocketFactory
               (boolean useSSL) throws Exception {
    if (useSSL) {
        SSLServerSocketFactory ssf = null;
        // set up key manager to do server authentication
        SSLContext ctx;
        KeyManagerFactory kmf;
        KeyStore ks;
        char[] passphrase = passwd.toCharArray();

        ctx = SSLContext.getInstance("TLS");
        kmf = KeyManagerFactory.getInstance("SunX509");
        ks = KeyStore.getInstance("JKS");

        ks.load(new FileInputStream(System.getProperty(
                    "javax.net.ssl.keyStore")), passphrase);
        kmf.init(ks, passphrase);
        ctx.init(kmf.getKeyManagers(), null, null);

        ssf = ctx.getServerSocketFactory();
        return ssf;
    } else {
        return ServerSocketFactory.getDefault();
    }
}
 
Example 4
Project: sample-acmegifts   File: AuthResourceTest.java   Source Code and License 6 votes vote down vote up
/**
 * Tests the JWT we get back from the auth service is valid. We test the JWT to make sure it was
 * signed correctly.
 *
 * <p>We do not validate other things, like the issued at time, expired time, etc.
 *
 * <p>The test case has access to the keystore that the server should have used to sign the JWT.
 */
@Test
public void testLoginJwtValidity() throws Exception {
  // Get the JWT from the auth service.
  Response response = processRequest(authServiceURL, "GET", null, null);
  assertEquals(
      "HTTP response code should have been " + Status.OK.getStatusCode() + ".",
      Status.OK.getStatusCode(),
      response.getStatus());
  String authHeader = response.getHeaderString("Authorization");

  // Open the keystore that the server should have used to sign the JWT.
  KeyStore ks = KeyStore.getInstance("JCEKS");
  InputStream ksStream = this.getClass().getResourceAsStream("/keystore.jceks");
  char[] password = new String("secret").toCharArray();
  ks.load(ksStream, password);
  java.security.cert.Certificate cert = ks.getCertificate("default");
  PublicKey publicKey = cert.getPublicKey();

  // Make sure it's valid.  Use the server's public key to check.
  new JWTVerifier().validateJWT(authHeader, publicKey);
}
 
Example 5
Project: iBase4J-Common   File: HTTPSPKCSCoder.java   Source Code and License 6 votes vote down vote up
/**
 * 获得SSLSocektFactory
 * 
 * @param password 密码
 * @param keyStorePath 密钥库路径
 * @param trustStorePath 信任库路径
 * @return SSLSocketFactory
 * @throws Exception
 */
private static SSLSocketFactory getSSLSocketFactory(String password, String keyStorePath, String trustStorePath)
		throws Exception {
	// 实例化密钥库
	KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
	// 获得密钥库
	KeyStore keyStore = getKeyStore(keyStorePath, password);
	// 初始化密钥工厂
	keyManagerFactory.init(keyStore, password.toCharArray());
	// 实例化信任库
	TrustManagerFactory trustManagerFactory = TrustManagerFactory
			.getInstance(TrustManagerFactory.getDefaultAlgorithm());
	// 获得信任库
	KeyStore trustStore = getKeyStore(trustStorePath, password);
	// 初始化信任库
	trustManagerFactory.init(trustStore);
	// 实例化SSL上下文
	SSLContext ctx = SSLContext.getInstance(PROTOCOL);
	// 初始化SSL上下文
	ctx.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), new SecureRandom());
	// 获得SSLSocketFactory
	return ctx.getSocketFactory();

}
 
Example 6
Project: RISE-V2G   File: SecurityUtils.java   Source Code and License 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 7
Project: cyberduck   File: DefaultX509TrustManager.java   Source Code and License 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 8
Project: wx-idk   File: HttpsRequestTools.java   Source Code and License 6 votes vote down vote up
/**
   * 创建Http/Https请求对象
   * @author Rocye
   * @param url 请求地址
   * @param method 请求方式:GET/POST
   * @param certPath 证书路径
   * @param certPass 证书密码
* @param useCert 是否需要证书
   * @return Https连接
   * @throws Exception 任何异常
   * @version 2017.11.14
   */
  private HttpsURLConnection createRequest(String url, String method, String certPath, String certPass, boolean useCert) throws Exception{
      URL realUrl = new URL(url);
      HttpsURLConnection connection = (HttpsURLConnection)realUrl.openConnection();

      //设置证书
if(useCert){
	KeyStore clientStore = KeyStore.getInstance("PKCS12");
	InputStream inputStream = new FileInputStream(certPath);
	clientStore.load(inputStream, certPass.toCharArray());
	KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
	kmf.init(clientStore, certPass.toCharArray());
	KeyManager[] kms = kmf.getKeyManagers();
	SSLContext sslContext = SSLContext.getInstance("TLSv1");
	sslContext.init(kms, null, new SecureRandom());
	connection.setSSLSocketFactory(sslContext.getSocketFactory());
}

      // 设置通用的请求属性
      connection.setRequestProperty("Accept", "*/*");
      connection.setRequestProperty("Connection", "Keep-Alive");
      connection.setConnectTimeout(this.connectTimeout);
      connection.setReadTimeout(this.readTimeout);
      if("POST".equals(method)){
          // 发送POST请求必须设置如下两行
          connection.setDoOutput(true);
          connection.setDoInput(true);
          connection.setUseCaches(false);   // 忽略缓存
          connection.setRequestMethod("POST");
      }
      return connection;
  }
 
Example 9
Project: OpenJSharp   File: PKIXParameters.java   Source Code and License 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 10
Project: jdk8u-jdk   File: ConvertP12Test.java   Source Code and License 6 votes vote down vote up
private void compareKeyStore(KeyStore a, KeyStore b, String inKeyPass,
        String outKeyPass, int keyStoreSize) throws Exception {
    if (a.size() != keyStoreSize || b.size() != keyStoreSize) {
        throw new RuntimeException("size not match or size not equal to "
                + keyStoreSize);
    }

    Enumeration<String> eA = a.aliases();
    while (eA.hasMoreElements()) {
        String aliasA = eA.nextElement();

        if (!b.containsAlias(aliasA)) {
            throw new RuntimeException("alias not match for alias:"
                    + aliasA);
        }

        compareKeyEntry(a, b, inKeyPass, outKeyPass, aliasA);
    }
}
 
Example 11
Project: jdk8u-jdk   File: Main.java   Source Code and License 6 votes vote down vote up
private static String verifyCRL(KeyStore ks, CRL crl)
        throws Exception {
    X509CRLImpl xcrl = (X509CRLImpl)crl;
    X500Principal issuer = xcrl.getIssuerX500Principal();
    for (String s: e2i(ks.aliases())) {
        Certificate cert = ks.getCertificate(s);
        if (cert instanceof X509Certificate) {
            X509Certificate xcert = (X509Certificate)cert;
            if (xcert.getSubjectX500Principal().equals(issuer)) {
                try {
                    ((X509CRLImpl)crl).verify(cert.getPublicKey());
                    return s;
                } catch (Exception e) {
                }
            }
        }
    }
    return null;
}
 
Example 12
Project: MakiLite   File: FingerprintUiHelper.java   Source Code and License 6 votes vote down vote up
/**
 * Initialize the {@link Cipher} instance with the created key in the {@link #createKey()}
 * method.
 *
 * @return {@code true} if initialization is successful, {@code false} if the lock screen has
 * been disabled or reset after the key was generated, or if a fingerprint got enrolled after
 * the key was generated.
 */
private boolean initCipher() {
    try {
        if (mKeyStore == null) {
            mKeyStore = KeyStore.getInstance("AndroidKeyStore");
        }
        createKey();
        mKeyStore.load(null);
        SecretKey key = (SecretKey) mKeyStore.getKey(KEY_NAME, null);
        mCipher = Cipher.getInstance("AES/CBC/PKCS7Padding");
        mCipher.init(Cipher.ENCRYPT_MODE, key);
        return true;
    } catch (NoSuchPaddingException | KeyStoreException | CertificateException | UnrecoverableKeyException | IOException
            | NoSuchAlgorithmException | InvalidKeyException e) {
        return false;
    }
}
 
Example 13
Project: OpenJSharp   File: Main.java   Source Code and License 6 votes vote down vote up
/**
 * Locates a signer for a given certificate from a given keystore and
 * returns the signer's certificate.
 * @param cert the certificate whose signer is searched, not null
 * @param ks the keystore to search with, not null
 * @return <code>cert</code> itself if it's already inside <code>ks</code>,
 * or a certificate inside <code>ks</code> who signs <code>cert</code>,
 * or null otherwise.
 */
private static Certificate getTrustedSigner(Certificate cert, KeyStore ks)
        throws Exception {
    if (ks.getCertificateAlias(cert) != null) {
        return cert;
    }
    for (Enumeration<String> aliases = ks.aliases();
            aliases.hasMoreElements(); ) {
        String name = aliases.nextElement();
        Certificate trustedCert = ks.getCertificate(name);
        if (trustedCert != null) {
            try {
                cert.verify(trustedCert.getPublicKey());
                return trustedCert;
            } catch (Exception e) {
                // Not verified, skip to the next one
            }
        }
    }
    return null;
}
 
Example 14
Project: webtrekk-android-sdk   File: NanoHTTPD.java   Source Code and License 6 votes vote down vote up
/**
 * Creates an SSLSocketFactory for HTTPS. Pass a KeyStore resource with your
 * certificate and passphrase
 */
public static SSLServerSocketFactory makeSSLSocketFactory(String keyAndTrustStoreClasspathPath, char[] passphrase) throws IOException {
    try {
        KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
        InputStream keystoreStream = NanoHTTPD.class.getResourceAsStream(keyAndTrustStoreClasspathPath);

        if (keystoreStream == null) {
            throw new IOException("Unable to load keystore from classpath: " + keyAndTrustStoreClasspathPath);
        }

        keystore.load(keystoreStream, passphrase);
        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keystore, passphrase);
        return makeSSLSocketFactory(keystore, keyManagerFactory);
    } catch (Exception e) {
        throw new IOException(e.getMessage());
    }
}
 
Example 15
Project: zabbkit-android   File: SSLManager.java   Source Code and License 6 votes vote down vote up
public void dumpTrustedCerts() {
	try {
		TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory
				.getDefaultAlgorithm());
		tmf.init((KeyStore) null);
		X509TrustManager xtm = (X509TrustManager) tmf.getTrustManagers()[0];
		StringBuffer buff = new StringBuffer();
		for (X509Certificate cert : xtm.getAcceptedIssuers()) {
			String certStr = "S:" + cert.getSubjectDN().getName() + "\nI:"
					+ cert.getIssuerDN().getName();
			Log.d(TAG, certStr);
			buff.append(certStr + "\n\n");
		}
	} catch (GeneralSecurityException e) {
		throw new RuntimeException(e);
	}
}
 
Example 16
Project: AgentWorkbench   File: TrustStoreController.java   Source Code and License 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 17
Project: jdk8u-jdk   File: KeyToolTest.java   Source Code and License 6 votes vote down vote up
void sqeImportTest() throws Exception {
    KeyStore ks;
    remove("x.jks");
    testOK("", "-keystore x.jks -storepass changeit -keypass changeit -genkeypair -dname CN=olala");
    testOK("", "-keystore x.jks -storepass changeit -exportcert -file x.jks.p1.cert");
    /* deleted */ testOK("", "-keystore x.jks -storepass changeit -delete -alias mykey");
    testOK("", "-keystore x.jks -storepass changeit -importcert -file x.jks.p1.cert -noprompt");
    /* deleted */ testOK("", "-keystore x.jks -storepass changeit -delete -alias mykey");
    testOK("yes\n", "-keystore x.jks -storepass changeit -importcert -file x.jks.p1.cert");
    ks = loadStore("x.jks", "changeit", "JKS");
    assertTrue(ks.containsAlias("mykey"), "imported");
    /* deleted */ testOK("", "-keystore x.jks -storepass changeit -delete -alias mykey");
    testOK("\n", "-keystore x.jks -storepass changeit -importcert -file x.jks.p1.cert");
    ks = loadStore("x.jks", "changeit", "JKS");
    assertTrue(!ks.containsAlias("mykey"), "imported");
    testOK("no\n", "-keystore x.jks -storepass changeit -importcert -file x.jks.p1.cert");
    ks = loadStore("x.jks", "changeit", "JKS");
    assertTrue(!ks.containsAlias("mykey"), "imported");
    testFail("no\n", "-keystore x.jks -storepass changeit -importcert -file nonexist");
    testFail("no\n", "-keystore x.jks -storepass changeit -importcert -file x.jks");
    remove("x.jks");
}
 
Example 18
Project: CacheManage   File: KeyStoreHelper.java   Source Code and License 6 votes vote down vote up
/**
 * JBMR2+ If Key with the default alias exists, returns true, else false.
 * on pre-JBMR2 returns true always.
 */
public static boolean isSigningKey(String alias) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
        try {
            KeyStore keyStore =
                    KeyStore.getInstance(SecurityConstants.KEYSTORE_PROVIDER_ANDROID_KEYSTORE);
            keyStore.load(null);
            return keyStore.containsAlias(alias);
        } catch (Exception e) {
            Log.e(TAG, e.getMessage(), e);
            return false;
        }
    } else {
        return false;
    }
}
 
Example 19
Project: OSchina_resources_android   File: ApiHttpClient.java   Source Code and License 6 votes vote down vote up
private static void initSSL(AsyncHttpClient client) {
    try {
        /// We initialize a default Keystore
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        // We load the KeyStore
        trustStore.load(null, null);
        // We initialize a new SSLSocketFacrory
        MySSLSocketFactory socketFactory = new MySSLSocketFactory(trustStore);
        // We set that all host names are allowed in the socket factory
        socketFactory.setHostnameVerifier(MySSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        // We set the SSL Factory
        client.setSSLSocketFactory(socketFactory);
        // We initialize a GET http request
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 20
Project: monarch   File: PKCSAuthInit.java   Source Code and License 5 votes vote down vote up
@Override
public Properties getCredentials(final Properties securityProperties,
    final DistributedMember server, final boolean isPeer) throws AuthenticationFailedException {
  final String keyStorePath = securityProperties.getProperty(KEYSTORE_FILE_PATH);
  if (keyStorePath == null) {
    throw new AuthenticationFailedException(
        "PKCSAuthInit: key-store file path property [" + KEYSTORE_FILE_PATH + "] not set.");
  }

  final String alias = securityProperties.getProperty(KEYSTORE_ALIAS);
  if (alias == null) {
    throw new AuthenticationFailedException(
        "PKCSAuthInit: key alias name property [" + KEYSTORE_ALIAS + "] not set.");
  }

  final String keyStorePass = securityProperties.getProperty(KEYSTORE_PASSWORD);

  try {
    final KeyStore ks = KeyStore.getInstance("PKCS12");
    final char[] passPhrase = (keyStorePass != null ? keyStorePass.toCharArray() : null);
    final FileInputStream certificatefile = new FileInputStream(keyStorePath);

    try {
      ks.load(certificatefile, passPhrase);
    } finally {
      certificatefile.close();
    }

    final Key key = ks.getKey(alias, passPhrase);

    if (key instanceof PrivateKey) {
      final PrivateKey privKey = (PrivateKey) key;
      final X509Certificate cert = (X509Certificate) ks.getCertificate(alias);
      final Signature sig = Signature.getInstance(cert.getSigAlgName());

      sig.initSign(privKey);
      sig.update(alias.getBytes("UTF-8"));
      final byte[] signatureBytes = sig.sign();

      final Properties newprops = new Properties();
      newprops.put(KEYSTORE_ALIAS, alias);
      newprops.put(SIGNATURE_DATA, signatureBytes);
      return newprops;

    } else {
      throw new AuthenticationFailedException(
          "PKCSAuthInit: " + "Failed to load private key from the given file: " + keyStorePath);
    }

  } catch (Exception ex) {
    throw new AuthenticationFailedException(
        "PKCSAuthInit: Exception while getting credentials: " + ex, ex);
  }
}
 
Example 21
Project: FastLib   File: SSLUtil.java   Source Code and License 5 votes vote down vote up
private static 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 kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmf.init(clientKeyStore, password.toCharArray());
        return kmf.getKeyManagers();
    } catch (Exception e) {
        Log.e("ssl", e.getMessage());
    }
    return null;
}
 
Example 22
Project: apache-tomcat-7.0.73-with-comment   File: JSSESocketFactory.java   Source Code and License 5 votes vote down vote up
/**
 * Gets the initialized key managers.
 */
protected KeyManager[] getKeyManagers(String keystoreType,
                                      String keystoreProvider,
                                      String algorithm,
                                      String keyAlias)
            throws Exception {

    KeyManager[] kms = null;

    String keystorePass = getKeystorePassword();

    KeyStore ks = getKeystore(keystoreType, keystoreProvider, keystorePass);
    if (keyAlias != null && !ks.isKeyEntry(keyAlias)) {
        throw new IOException(
                sm.getString("jsse.alias_no_key_entry", keyAlias));
    }

    KeyManagerFactory kmf = KeyManagerFactory.getInstance(algorithm);
    String keyPass = endpoint.getKeyPass();
    if (keyPass == null) {
        keyPass = keystorePass;
    }
    kmf.init(ks, keyPass.toCharArray());

    kms = kmf.getKeyManagers();
    if (keyAlias != null) {
        String alias = keyAlias;
        if (JSSESocketFactory.defaultKeystoreType.equals(keystoreType)) {
            alias = alias.toLowerCase(Locale.ENGLISH);
        }
        for(int i=0; i<kms.length; i++) {
            kms[i] = new JSSEKeyManager((X509KeyManager)kms[i], alias);
        }
    }

    return kms;
}
 
Example 23
Project: automat   File: HTTPSPKCSCoder.java   Source Code and License 5 votes vote down vote up
/**
 * 获得KeyStore
 * 
 * @param keyStorePath 密钥库路径
 * @param password 密码
 * @return KeyStore 密钥库
 * @throws Exception
 */
private static KeyStore getKeyStore(String keyStorePath, String password) throws Exception {
	// 实例化密钥库
	KeyStore ks = KeyStore.getInstance("PKCS12");
	// KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
	// 获得密钥库文件流
	FileInputStream is = new FileInputStream(keyStorePath);
	// 加载密钥库
	ks.load(is, password.toCharArray());
	// 关闭密钥库文件流
	is.close();
	return ks;
}
 
Example 24
Project: neoscada   File: KeyStoreFactory.java   Source Code and License 5 votes vote down vote up
/**
 * Creates a new {@link KeyStore}. This method will be called
 * by the base class when Spring creates a bean using this FactoryBean.
 *
 * @return a new {@link KeyStore} instance.
 */
public KeyStore newInstance() throws KeyStoreException, NoSuchProviderException, NoSuchAlgorithmException,
        CertificateException, IOException {
    if (data == null) {
        throw new IllegalStateException("data property is not set.");
    }

    KeyStore ks;
    if (provider == null) {
        ks = KeyStore.getInstance(type);
    } else {
        ks = KeyStore.getInstance(type, provider);
    }

    InputStream is = new ByteArrayInputStream(data);
    try {
        ks.load(is, password);
    } finally {
        try {
            is.close();
        } catch (IOException ignored) {
            // Do nothing
        }
    }

    return ks;
}
 
Example 25
Project: lighthouse   File: SSLContextBuilder.java   Source Code and License 5 votes vote down vote up
public SSLContextBuilder loadTrustMaterial(
        final File file,
        final char[] storePassword,
        final TrustStrategy trustStrategy) throws NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException {
    Args.notNull(file, "Truststore file");
    final KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
    final FileInputStream instream = new FileInputStream(file);
    try {
        trustStore.load(instream, storePassword);
    } finally {
        instream.close();
    }
    return loadTrustMaterial(trustStore, trustStrategy);
}
 
Example 26
Project: Mobike   File: MySSLSocketFactory.java   Source Code and License 5 votes vote down vote up
/**
 * Gets getUrl Default KeyStore
 *
 * @return KeyStore
 */
public static KeyStore getKeystore() {
    KeyStore trustStore = null;
    try {
        trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);
    } catch (Throwable t) {
        t.printStackTrace();
    }
    return trustStore;
}
 
Example 27
Project: trust-wallet-android   File: KS.java   Source Code and License 5 votes vote down vote up
private synchronized static void removeAliasAndFiles(Context context, String alias, String dataFileName, String ivFileName) {
	KeyStore keyStore;
	try {
		keyStore = KeyStore.getInstance(ANDROID_KEY_STORE);
		keyStore.load(null);
		keyStore.deleteEntry(alias);
		new File(getFilePath(context, dataFileName)).delete();
		new File(getFilePath(context, ivFileName)).delete();
	} catch (KeyStoreException | CertificateException | NoSuchAlgorithmException | IOException e) {
		e.printStackTrace();
	}
}
 
Example 28
Project: q-mail   File: KeyStoreProvider.java   Source Code and License 5 votes vote down vote up
public X509Certificate getServerCertificate() {
    try {
        KeyStore keyStore = loadKeyStore();
        return (X509Certificate) keyStore.getCertificate(SERVER_CERTIFICATE_ALIAS);
    } catch (KeyStoreException e) {
        throw new RuntimeException(e);
    }
}
 
Example 29
Project: webtrekk-android-sdk   File: NanoHTTPD.java   Source Code and License 5 votes vote down vote up
/**
 * Creates an SSLSocketFactory for HTTPS. Pass a loaded KeyStore and a
 * loaded KeyManagerFactory. These objects must properly loaded/initialized
 * by the caller.
 */
public static SSLServerSocketFactory makeSSLSocketFactory(KeyStore loadedKeyStore, KeyManagerFactory loadedKeyFactory) throws IOException {
    try {
        return makeSSLSocketFactory(loadedKeyStore, loadedKeyFactory.getKeyManagers());
    } catch (Exception e) {
        throw new IOException(e.getMessage());
    }
}
 
Example 30
Project: mumu-core   File: HTTPSCoder.java   Source Code and License 5 votes vote down vote up
/**
 * 获得KeyStore
 * 
 * @param keyStorePath 密钥库路径
 * @param password 密码
 * @return KeyStore 密钥库
 * @throws Exception
 */
private static KeyStore getKeyStore(String keyStorePath, String password) throws Exception {
	// 实例化密钥库
	KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
	// 获得密钥库文件流
	FileInputStream is = new FileInputStream(keyStorePath);
	// 加载密钥库
	ks.load(is, password.toCharArray());
	// 关闭密钥库文件流
	is.close();
	return ks;
}
 
Example 31
Project: elasticsearch_my   File: ESRestTestCase.java   Source Code and License 5 votes vote down vote up
protected RestClient buildClient(Settings settings, HttpHost[] hosts) throws IOException {
    RestClientBuilder builder = RestClient.builder(hosts);
    String keystorePath = settings.get(TRUSTSTORE_PATH);
    if (keystorePath != null) {
        final String keystorePass = settings.get(TRUSTSTORE_PASSWORD);
        if (keystorePass == null) {
            throw new IllegalStateException(TRUSTSTORE_PATH + " is provided but not " + TRUSTSTORE_PASSWORD);
        }
        Path path = PathUtils.get(keystorePath);
        if (!Files.exists(path)) {
            throw new IllegalStateException(TRUSTSTORE_PATH + " is set but points to a non-existing file");
        }
        try {
            KeyStore keyStore = KeyStore.getInstance("jks");
            try (InputStream is = Files.newInputStream(path)) {
                keyStore.load(is, keystorePass.toCharArray());
            }
            SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(keyStore, null).build();
            SSLIOSessionStrategy sessionStrategy = new SSLIOSessionStrategy(sslcontext);
            builder.setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setSSLStrategy(sessionStrategy));
        } catch (KeyStoreException|NoSuchAlgorithmException|KeyManagementException|CertificateException e) {
            throw new RuntimeException("Error setting up ssl", e);
        }
    }

    try (ThreadContext threadContext = new ThreadContext(settings)) {
        Header[] defaultHeaders = new Header[threadContext.getHeaders().size()];
        int i = 0;
        for (Map.Entry<String, String> entry : threadContext.getHeaders().entrySet()) {
            defaultHeaders[i++] = new BasicHeader(entry.getKey(), entry.getValue());
        }
        builder.setDefaultHeaders(defaultHeaders);
    }
    return builder.build();
}
 
Example 32
Project: xitk   File: KeyUtil.java   Source Code and License 5 votes vote down vote up
public static KeyStore getKeyStore(String storeType)
        throws KeyStoreException, NoSuchProviderException {
    ParamUtil.requireNonBlank("storeType", storeType);
    if ("JKS".equalsIgnoreCase(storeType) || "JCEKS".equalsIgnoreCase(storeType)) {
        return KeyStore.getInstance(storeType);
    } else {
        try {
            return KeyStore.getInstance(storeType, "BC");
        } catch (KeyStoreException | NoSuchProviderException ex) {
            return KeyStore.getInstance(storeType);
        }
    }
}
 
Example 33
Project: GitHub   File: MySSLSocketFactory.java   Source Code and License 5 votes vote down vote up
/**
 * Gets a Default KeyStore
 *
 * @return KeyStore
 */
public static KeyStore getKeystore() {
    KeyStore trustStore = null;
    try {
        trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);
    } catch (Throwable t) {
        t.printStackTrace();
    }
    return trustStore;
}
 
Example 34
Project: apache-tomcat-7.0.73-with-comment   File: JSSESocketFactory.java   Source Code and License 5 votes vote down vote up
protected KeyStore getKeystore(String type, String provider, String pass)
        throws IOException {

    String keystoreFile = endpoint.getKeystoreFile();
    if (keystoreFile == null)
        keystoreFile = defaultKeystoreFile;

    return getStore(type, provider, keystoreFile, pass);
}
 
Example 35
Project: iotplatform   File: MqttSslHandlerProvider.java   Source Code and License 5 votes vote down vote up
public SslHandler getSslHandler() {
    try {
        URL ksUrl = Resources.getResource(keyStoreFile);
        File ksFile = new File(ksUrl.toURI());
        URL tsUrl = Resources.getResource(keyStoreFile);
        File tsFile = new File(tsUrl.toURI());

        TrustManagerFactory tmFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        KeyStore trustStore = KeyStore.getInstance(keyStoreType);
        trustStore.load(new FileInputStream(tsFile), keyStorePassword.toCharArray());
        tmFactory.init(trustStore);

        KeyStore ks = KeyStore.getInstance(keyStoreType);

        ks.load(new FileInputStream(ksFile), keyStorePassword.toCharArray());
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmf.init(ks, keyPassword.toCharArray());

        KeyManager[] km = kmf.getKeyManagers();
        TrustManager x509wrapped = getX509TrustManager(tmFactory);
        TrustManager[] tm = {x509wrapped};
        SSLContext sslContext = SSLContext.getInstance(TLS);
        sslContext.init(km, tm, null);
        SSLEngine sslEngine = sslContext.createSSLEngine();
        sslEngine.setUseClientMode(false);
        sslEngine.setNeedClientAuth(false);
        sslEngine.setWantClientAuth(true);
        sslEngine.setEnabledProtocols(sslEngine.getSupportedProtocols());
        sslEngine.setEnabledCipherSuites(sslEngine.getSupportedCipherSuites());
        sslEngine.setEnableSessionCreation(true);
        return new SslHandler(sslEngine);
    } catch (Exception e) {
        log.error("Unable to set up SSL context. Reason: " + e.getMessage(), e);
        throw new RuntimeException("Failed to get SSL handler", e);
    }
}
 
Example 36
Project: jdk8u-jdk   File: SSLCtxAccessToSessCtx.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    String keyFilename =
        System.getProperty("test.src", "./") + "/" + pathToStores +
            "/" + keyStoreFile;
    String trustFilename =
        System.getProperty("test.src", "./") + "/" + pathToStores +
            "/" + trustStoreFile;

    System.setProperty("javax.net.ssl.keyStore", keyFilename);
    System.setProperty("javax.net.ssl.keyStorePassword", passwd);
    System.setProperty("javax.net.ssl.trustStore", trustFilename);
    System.setProperty("javax.net.ssl.trustStorePassword", passwd);

    sslctx = SSLContext.getInstance("TLS");
    KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
    KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(new FileInputStream(keyFilename), passwd.toCharArray());
    kmf.init(ks, passwd.toCharArray());
    sslctx.init(kmf.getKeyManagers(), null, null);

    sslssf = (SSLServerSocketFactory) sslctx.getServerSocketFactory();
    sslsf = (SSLSocketFactory) sslctx.getSocketFactory();

    if (debug)
        System.setProperty("javax.net.debug", "all");

    /*
     * Start the tests.
     */
    new SSLCtxAccessToSessCtx();
}
 
Example 37
Project: jdk8u-jdk   File: TestJKSWithSecretKey.java   Source Code and License 5 votes vote down vote up
public static void main (String[] args) throws Exception {
    SecretKey key = new SecretKeySpec(new byte[8], "DES");

    KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(null, passwd);

    try {
        // store the SecretKey
        ks.setKeyEntry("test_encrypt_key", key, passwd, null);
        throw new Exception("Should throw KeyStoreException when " +
            "storing SecretKey into JKS keystores");
    } catch (KeyStoreException kse) {
        // expected exception thrown; swallow
    }
}
 
Example 38
Project: TPlayer   File: HttpsUtils.java   Source Code and License 5 votes vote down vote up
private static 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 kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmf.init(clientKeyStore, password.toCharArray());
        return kmf.getKeyManagers();
    } catch (Exception e) {
        OkLogger.printStackTrace(e);
    }
    return null;
}
 
Example 39
Project: GitHub   File: MySSLSocketFactory.java   Source Code and License 5 votes vote down vote up
/**
 * Gets a Default KeyStore
 *
 * @return KeyStore
 */
public static KeyStore getKeystore() {
    KeyStore trustStore = null;
    try {
        trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);
    } catch (Throwable t) {
        t.printStackTrace();
    }
    return trustStore;
}
 
Example 40
Project: verify-hub   File: ConfigServiceKeyStore.java   Source Code and License 5 votes vote down vote up
private void validate(final X509Certificate certificate, final KeyStore trustStore) {
    CertificateValidity certificateValidity = certificateChainValidator.validate(certificate, trustStore);
    if (!certificateValidity.isValid()) {
        throw new CertificateChainValidationException(
                format("Certificate is not valid: {0}", getDnForCertificate(certificate)),
                certificateValidity.getException().get());
    }
}
 
Example 41
Project: java-android-websocket-client   File: SSLContextBuilder.java   Source Code and License 5 votes vote down vote up
public SSLContextBuilder loadTrustMaterial(
        final URL url,
        final char[] storePassword,
        final TrustStrategy trustStrategy) throws NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException {
    Args.notNull(url, "Truststore URL");
    final KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
    final InputStream instream = url.openStream();
    try {
        trustStore.load(instream, storePassword);
    } finally {
        instream.close();
    }
    return loadTrustMaterial(trustStore, trustStrategy);
}
 
Example 42
Project: mobile-store   File: NanoHTTPD.java   Source Code and License 5 votes vote down vote up
/**
 * Creates an SSLSocketFactory for HTTPS.
 *
 * Pass a loaded KeyStore and an array of loaded KeyManagers.
 * These objects must properly loaded/initialized by the caller.
 */
public static SSLServerSocketFactory makeSSLSocketFactory(KeyStore loadedKeyStore, KeyManager[] keyManagers) throws IOException {
   SSLServerSocketFactory res = null;
   try {
      TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
      trustManagerFactory.init(loadedKeyStore);
      SSLContext ctx = SSLContext.getInstance("TLS");
      ctx.init(keyManagers, trustManagerFactory.getTrustManagers(), null);
      res = ctx.getServerSocketFactory();
   } catch (Exception e) {
      throw new IOException(e.getMessage());
   }
   return res;
}
 
Example 43
Project: BiglyBT   File: SESecurityManagerImpl.java   Source Code and License 5 votes vote down vote up
protected boolean
checkKeyStoreHasEntry()
{
	File	f  = new File(keystore_name);

	if ( !f.exists()){
		Logger.logTextResource(new LogAlert(LogAlert.UNREPEATABLE,
				LogAlert.AT_ERROR, "Security.keystore.empty"),
				new String[] { keystore_name });

		return( false );
	}

	try{
		KeyStore key_store = loadKeyStore();

		Enumeration enumx = key_store.aliases();

		if ( !enumx.hasMoreElements()){
			Logger.logTextResource(new LogAlert(LogAlert.UNREPEATABLE,
					LogAlert.AT_ERROR, "Security.keystore.empty"),
					new String[] { keystore_name });

			return( false );
		}

	}catch( Throwable e ){

		Logger.logTextResource(new LogAlert(LogAlert.UNREPEATABLE,
				LogAlert.AT_ERROR, "Security.keystore.corrupt"),
				new String[] { keystore_name });

		return( false );
	}

	return( true );
}
 
Example 44
Project: letv   File: SystemKeyStore.java   Source Code and License 5 votes vote down vote up
private HashMap<Principal, X509Certificate> initializeTrustedRoots(KeyStore trustStore) {
    try {
        HashMap<Principal, X509Certificate> trusted = new HashMap();
        Enumeration<String> aliases = trustStore.aliases();
        while (aliases.hasMoreElements()) {
            X509Certificate cert = (X509Certificate) trustStore.getCertificate((String) aliases.nextElement());
            if (cert != null) {
                trusted.put(cert.getSubjectX500Principal(), cert);
            }
        }
        return trusted;
    } catch (KeyStoreException e) {
        throw new AssertionError(e);
    }
}
 
Example 45
Project: Spark   File: NetCode.java   Source Code and License 5 votes vote down vote up
public static SSLContext getSSLContext()
{
	try
	{
		String filename = "Keystore";
		String PASSWORD = "secret";

		char[] passphrase = PASSWORD.toCharArray();
		KeyStore ks = KeyStore.getInstance("JKS");
		ks.load(new FileInputStream(filename), passphrase);

		KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
		kmf.init(ks, passphrase);

		TrustManagerFactory tmf = TrustManagerFactory
				.getInstance("SunX509");
		tmf.init(ks);

		SSLContext sslContext = SSLContext.getInstance("TLS");
		sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);

		return sslContext;

	}
	catch (Exception e)
	{
		e.printStackTrace();
		return null;
	}
}
 
Example 46
Project: lams   File: SSLSocketFactory.java   Source Code and License 5 votes vote down vote up
/**
 * @deprecated Use {@link #SSLSocketFactory(String, KeyStore, String, KeyStore, SecureRandom, X509HostnameVerifier)}
 */
@Deprecated
public SSLSocketFactory(
        final String algorithm,
        final KeyStore keystore,
        final String keystorePassword,
        final KeyStore truststore,
        final SecureRandom random,
        final HostNameResolver nameResolver)
            throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
    this(createSSLContext(
            algorithm, keystore, keystorePassword, truststore, random, null),
            nameResolver);
}
 
Example 47
Project: react-native-caller-id-android   File: DataBase.java   Source Code and License 5 votes vote down vote up
private static String decryptString_old(Context ctx, String alias) {
    String finalText = null;
    try {
        KeyStore.PrivateKeyEntry privateKeyEntry = getPrivateKeyEntry(alias);
        if (null == privateKeyEntry) return null;

        Cipher output = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        output.init(Cipher.DECRYPT_MODE, privateKeyEntry.getPrivateKey());


        String strEnc = prefs.getString("hash", null);
        byte[] encB = Base64.decode(strEnc, Base64.DEFAULT);

        CipherInputStream cipherInputStream = new CipherInputStream(
                new ByteArrayInputStream(encB), output);
        ArrayList<Byte> values = new ArrayList<>();
        int nextByte;
        while ((nextByte = cipherInputStream.read()) != -1) {
            values.add((byte)nextByte);
        }

        byte[] bytes = new byte[values.size()];
        for(int i = 0; i < bytes.length; i++) {
            bytes[i] = values.get(i).byteValue();
        }

        finalText = new String(bytes, 0, bytes.length, "UTF-8");

    } catch (Exception e) {
        Toast.makeText(ctx, "Exception " + e.getMessage() + " occured", Toast.LENGTH_LONG).show();
        Log.e(TAG, Log.getStackTraceString(e));
    }
    return finalText;
}
 
Example 48
Project: RISE-V2G   File: SecurityUtils.java   Source Code and License 5 votes vote down vote up
/**
 * Returns the certificate chain from a PKCS#12 container holding credentials such as private key,
 * leaf certificate and zero or more intermediate certificates.
 * 
 * @param pkcs12Resource The PKCS#12 container
 * @return The certificate chain
 */
public static CertificateChainType getCertificateChain(String pkcs12Resource) {
	CertificateChainType certChain = new CertificateChainType();
	
	/*
	 * For testing purposes, the respective PKCS12 container file has already been put in the 
	 * resources folder. However, when implementing a real interface to a secondary actor's backend, 
	 * the retrieval of a certificate must be done via some other online mechanism.
	 */
	KeyStore contractCertificateKeystore = getPKCS12KeyStore(pkcs12Resource, GlobalValues.PASSPHRASE_FOR_CERTIFICATES_AND_KEYS.toString());
	
	if (contractCertificateKeystore == null) {
		getLogger().error("Unable to access certificate chain because no PKCS#12 container found at " +
						  "location '" + pkcs12Resource + "'");
		return null;
	}
	
	try {
		Enumeration<String> aliases = contractCertificateKeystore.aliases();
		Certificate[] tempCertChain = null;
		// Only one certificate chain (and therefore alias) should be available
		while (aliases.hasMoreElements()) {
			tempCertChain = contractCertificateKeystore.getCertificateChain(aliases.nextElement());
			certChain.setCertificate(getLeafCertificate(tempCertChain).getEncoded());
			certChain.setSubCertificates(getSubCertificates(tempCertChain));
		}
	} catch (KeyStoreException | CertificateEncodingException | NullPointerException e) {
		getLogger().error(e.getClass().getSimpleName() + " occurred while  trying to get " +
						  "certificate chain from resource '" + pkcs12Resource + "'", e);
	}
	
	return certChain;
}
 
Example 49
Project: lighthouse   File: SSLContextBuilder.java   Source Code and License 5 votes vote down vote up
public SSLContextBuilder loadTrustMaterial(
        final URL url,
        final char[] storePassword,
        final TrustStrategy trustStrategy) throws NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException {
    Args.notNull(url, "Truststore URL");
    final KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
    final InputStream instream = url.openStream();
    try {
        trustStore.load(instream, storePassword);
    } finally {
        instream.close();
    }
    return loadTrustMaterial(trustStore, trustStrategy);
}
 
Example 50
Project: BiglyBT   File: SESecurityManagerImpl.java   Source Code and License 5 votes vote down vote up
public KeyStore
getTrustStore()

	throws Exception
{
	return( getTrustStore( true ));
}
 
Example 51
Project: an2linuxclient   File: TlsHelper.java   Source Code and License 5 votes vote down vote up
public static SSLContext getNotificationTlsContext(Context c, Certificate serverCert){
    try {
        SSLContext tlsContext = SSLContext.getInstance(TLS_VERSIONS[0]);

        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(null, null);
        keyStore.setKeyEntry("key", RsaHelper.getPrivateKey(c), "".toCharArray(),
                new Certificate[]{TlsHelper.getCertificate(c)});
        keyStore.setCertificateEntry("serverCert", serverCert);

        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(keyStore, "".toCharArray());

        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(keyStore);

        tlsContext.init(keyManagerFactory.getKeyManagers(), tmf.getTrustManagers(), null);
        return tlsContext;
    } catch (Exception e){
        Log.e("TlsHelper", "getNotificationTlsContext");
        Log.e("StackTrace", Log.getStackTraceString(e));
        return null;
    }
}
 
Example 52
Project: jdk8u-jdk   File: Utils.java   Source Code and License 5 votes vote down vote up
public static void saveKeyStore(KeyStore ks, String file, char[] passwd)
        throws IOException, KeyStoreException, NoSuchAlgorithmException,
        CertificateException {
    try (FileOutputStream fout = new FileOutputStream(file)) {
        ks.store(fout, passwd);
    }
}
 
Example 53
Project: boohee_v5.6   File: MySSLSocketFactory.java   Source Code and License 5 votes vote down vote up
public static DefaultHttpClient getNewHttpClient(KeyStore keyStore) {
    try {
        SSLSocketFactory sf = new MySSLSocketFactory(keyStore);
        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        registry.register(new Scheme(b.a, sf, WebSocket.DEFAULT_WSS_PORT));
        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, "UTF-8");
        return new DefaultHttpClient(new ThreadSafeClientConnManager(params, registry), params);
    } catch (Exception e) {
        return new DefaultHttpClient();
    }
}
 
Example 54
Project: openjdk-jdk10   File: Utils.java   Source Code and License 5 votes vote down vote up
public static KeyStore loadKeyStore(String file, KeyStoreType type,
        char[] passwd)
        throws IOException, KeyStoreException,
        NoSuchAlgorithmException, CertificateException {
    KeyStore ks = KeyStore.getInstance(type.name());
    try (FileInputStream fin = new FileInputStream(file)) {
        ks.load(fin, passwd);
    }
    return ks;
}
 
Example 55
Project: aos-FileCoreLibrary   File: KeyManagerUtils.java   Source Code and License 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 56
Project: okhttpUtil   File: HttpsUtil.java   Source Code and License 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 57
Project: ucar-weex-core   File: HttpsUtils.java   Source Code and License 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 58
Project: OrigamiSMTP   File: STARTTLSHandler.java   Source Code and License 5 votes vote down vote up
public STARTTLSHandler(Socket old)
{
	try
	{
		keyStore  = KeyStore.getInstance(KeyStore.getDefaultType());
		InputStream ksIs = STARTTLSHandler.class.getClassLoader().getResourceAsStream("keys");
		keyStore.load(ksIs,"password".toCharArray());
		if(ksIs != null)
		{
			ksIs.close();
		}
		
		keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
		keyManagerFactory.init(keyStore, "password".toCharArray());
		
		InputStream trustStoreIs = STARTTLSHandler.class.getClassLoader().getResourceAsStream("truststore");
		trustStore = KeyStore.getInstance("JKS");
		trustStore.load(trustStoreIs, "password".toCharArray());
		trustFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
		trustFactory.init(trustStore);
		
		sslContext = SSLContext.getInstance("TLSv1.2");
		sslContext.init(keyManagerFactory.getKeyManagers(),trustFactory.getTrustManagers(), null);
		
		if(old instanceof SSLSocket)
		{
			Response = "454 TLS not available due to temporary reason: TLS already active";
		}
		else
		{
			Response = "220 Ready to start TLS" + Variables.CRLF;
		}
	}
	catch(Exception e)
	{
		System.err.println("Fatal Error: "+e.getMessage());
		e.printStackTrace();
	}
}
 
Example 59
Project: openjdk-jdk10   File: BadPem.java   Source Code and License 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    String ks = System.getProperty("test.src", ".")
            + "/../../../../javax/net/ssl/etc/keystore";
    String pass = "passphrase";
    String alias = "dummy";

    KeyStore keyStore = KeyStore.getInstance("JKS");
    keyStore.load(new FileInputStream(ks), pass.toCharArray());
    byte[] cert = keyStore.getCertificate(alias).getEncoded();

    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    PrintStream pout = new PrintStream(bout);
    byte[] CRLF = new byte[] {'\r', '\n'};
    pout.println(X509Factory.BEGIN_CERT);
    for (int i=0; i<cert.length; i += 48) {
        int blockLen = (cert.length > i + 48) ? 48 : (cert.length - i);
        pout.println("!" + Base64.getEncoder()
                .encodeToString(Arrays.copyOfRange(cert, i, i + blockLen)));
    }
    pout.println(X509Factory.END_CERT);

    CertificateFactory cf = CertificateFactory.getInstance("X.509");

    try {
        cf.generateCertificate(new ByteArrayInputStream(bout.toByteArray()));
        throw new Exception("Should fail");
    } catch (CertificateException e) {
        // Good
    }
}
 
Example 60
Project: PI-Web-API-Client-Java-Android   File: ApiClient.java   Source Code and License 5 votes vote down vote up
private KeyStore newEmptyKeyStore(char[] password) throws GeneralSecurityException {
    try {
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(null, password);
        return keyStore;
    } catch (IOException e) {
        throw new AssertionError(e);
    }
}