Java Code Examples for java.security.KeyStore

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project avro, under directory /lang/java/ipc/src/test/java/org/apache/avro/ipc/.

Source file: TestNettyServerWithSSL.java

  22 
vote

private SSLContext createServerSSLContext(){
  try {
    KeyStore ks=KeyStore.getInstance("PKCS12");
    ks.load(TestNettyServer.class.getResource(TEST_CERTIFICATE).openStream(),TEST_CERTIFICATE_PASSWORD.toCharArray());
    KeyManagerFactory kmf=KeyManagerFactory.getInstance(getAlgorithm());
    kmf.init(ks,TEST_CERTIFICATE_PASSWORD.toCharArray());
    SSLContext serverContext=SSLContext.getInstance("TLS");
    serverContext.init(kmf.getKeyManagers(),null,null);
    return serverContext;
  }
 catch (  Exception e) {
    throw new Error("Failed to initialize the server-side SSLContext",e);
  }
}
 

Example 2

From project caseconductor-platform, under directory /utest-webservice/utest-webservice-client/src/main/java/com/utest/webservice/client/util/.

Source file: SSLUtil.java

  20 
vote

public static TLSClientParameters getTLSconfiguration(String keyStoreFile,String kestorepassword) throws Exception {
  final TLSClientParameters tlsParams=new TLSClientParameters();
  final KeyStore trustStore=KeyStore.getInstance("JKS");
  final File truststoreFile=new File(keyStoreFile);
  trustStore.load(new FileInputStream(truststoreFile),kestorepassword.toCharArray());
  final TrustManagerFactory trustFactory=TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
  trustFactory.init(trustStore);
  final TrustManager[] tm=trustFactory.getTrustManagers();
  tlsParams.setTrustManagers(tm);
  tlsParams.setSecureSocketProtocol("SSL");
  tlsParams.setDisableCNCheck(true);
  return tlsParams;
}
 

Example 3

From project httpbuilder, under directory /src/main/java/groovyx/net/http/.

Source file: AuthConfig.java

  19 
vote

/** 
 * Sets a certificate to be used for SSL authentication.  See  {@link Class#getResource(String)} for how to get a URL from a resource on the classpath.
 * @param certURL URL to a JKS keystore where the certificate is stored.  
 * @param password password to decrypt the keystore
 */
public void certificate(String certURL,String password) throws GeneralSecurityException, IOException {
  KeyStore keyStore=KeyStore.getInstance(KeyStore.getDefaultType());
  InputStream jksStream=new URL(certURL).openStream();
  try {
    keyStore.load(jksStream,password.toCharArray());
  }
  finally {
    jksStream.close();
  }
  SSLSocketFactory ssl=new SSLSocketFactory(keyStore,password);
  ssl.setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
  builder.getClient().getConnectionManager().getSchemeRegistry().register(new Scheme("https",ssl,443));
}
 

Example 4

From project httpcore, under directory /httpcore-nio/src/test/java/org/apache/http/testserver/.

Source file: SSLTestContexts.java

  19 
vote

public static SSLContext createServerSSLContext() throws Exception {
  ClassLoader cl=SSLTestContexts.class.getClassLoader();
  URL url=cl.getResource("test.keystore");
  Assert.assertNotNull("Keystore URL should not be null",url);
  KeyStore keystore=KeyStore.getInstance("jks");
  keystore.load(url.openStream(),"nopassword".toCharArray());
  KeyManagerFactory kmfactory=createKeyManagerFactory();
  kmfactory.init(keystore,"nopassword".toCharArray());
  KeyManager[] keymanagers=kmfactory.getKeyManagers();
  SSLContext sslcontext=SSLContext.getInstance("TLS");
  sslcontext.init(keymanagers,null,null);
  return sslcontext;
}
 

Example 5

From project jentrata-msh, under directory /Ext/ebxml-pkg/src/main/java/hk/hku/cecid/ebms/pkg/pki/.

Source file: CompositeKeyStore.java

  19 
vote

/** 
 * Gets the certificate named by the given alias, from the collection of keystores pointed by this composite keystore.
 * @param alias the alias of the key/certificate
 * @return the certificate named by the given alias, null if not found
 * @throws KeyStoreException the keystore is corrupted
 */
public Certificate getCertificate(String alias) throws KeyStoreException {
  if (cache == null) {
    loadCache();
  }
  KeyStore ks=(KeyStore)cache.get(alias);
  if (ks != null) {
    return ks.getCertificate(alias);
  }
  return null;
}
 

Example 6

From project components-ness-httpclient, under directory /client/src/main/java/com/nesscomputing/httpclient/internal/.

Source file: HttpClientTrustManagerFactory.java

  18 
vote

@Nonnull public static X509KeyManager getKeyManager(String keystorePath,String keystoreType,String keystorePassword) throws IOException, GeneralSecurityException {
  Preconditions.checkArgument(keystorePath != null,"keystore path must not be null!");
  Preconditions.checkArgument(keystoreType != null,"keystore type must not be null!");
  Preconditions.checkArgument(keystorePassword != null,"keystore password must not be null!");
  KeyStore keyStore=loadKeystore(keystorePath,keystoreType,keystorePassword);
  return getKeyManagerForKeystore(keyStore,keystorePassword);
}
 

Example 7

From project dcm4che, under directory /dcm4che-net/src/main/java/org/dcm4che/net/.

Source file: SSLManagerFactory.java

  18 
vote

public static KeyStore loadKeyStore(String type,String url,char[] password) throws IOException, KeyStoreException, NoSuchAlgorithmException, CertificateException {
  KeyStore ks=KeyStore.getInstance(type);
  InputStream in=StreamUtils.openFileOrURL(url);
  try {
    ks.load(in,password);
  }
  finally {
    SafeClose.close(in);
  }
  return ks;
}
 

Example 8

From project GNDMS, under directory /gndmc-rest/test-src/de/zib/gndms/gndmc/test/.

Source file: KeyStoreTest.java

  18 
vote

public static SetupSSL initSSL(final String kpass,final String kpass2,final String truststorePassword) throws KeyStoreException, NoSuchAlgorithmException, IOException, CertificateException, UnrecoverableEntryException {
  SetupSSL sslSetup=new SetupSSL();
  sslSetup.setKeyStoreLocation("/tmp/awicert.p12");
  sslSetup.prepareKeyStore(kpass,kpass2);
  KeyStore ks=sslSetup.getKeyStore();
  analyseKeyStore(kpass.toCharArray(),ks);
  System.out.println("now the trustStore");
  sslSetup.setTrustStoreLocation("/tmp/keystore");
  sslSetup.prepareTrustStore(truststorePassword);
  analyseKeyStore(new char[1],sslSetup.getTrustStore());
  return sslSetup;
}
 

Example 9

From project integration-tests, under directory /picketlink-sts-tests/src/test/java/org/picketlink/test/integration/sts/.

Source file: PicketLinkSTSIntegrationUnitTestCase.java

  18 
vote

@BeforeClass public static void initClient() throws Exception {
  client=new WSTrustClient("PicketLinkSTS","PicketLinkSTSPort","http://localhost:8080/picketlink-sts/PicketLinkSTS",new SecurityInfo("tomcat","tomcat"));
  InputStream stream=Thread.currentThread().getContextClassLoader().getResourceAsStream("keystore/sts_keystore.jks");
  KeyStore keyStore=KeyStore.getInstance("JKS");
  keyStore.load(stream,"testpass".toCharArray());
  certificate=keyStore.getCertificate("service2");
}
 

Example 10

From project JGlobus, under directory /gss/src/main/java/org/globus/gsi/gssapi/.

Source file: GlobusGSSContextImpl.java

  18 
vote

private static KeyStore getTrustStore(String caCertsLocation) throws GeneralSecurityException, IOException {
  if (GlobusGSSContextImpl.ms_trustStore != null)   return GlobusGSSContextImpl.ms_trustStore;
  String caCertsPattern=caCertsLocation + "/*.0";
  KeyStore keyStore=KeyStore.getInstance(GlobusProvider.KEYSTORE_TYPE,GlobusProvider.PROVIDER_NAME);
  keyStore.load(KeyStoreParametersFactory.createTrustStoreParameters(caCertsPattern));
  GlobusGSSContextImpl.ms_trustStore=keyStore;
  return keyStore;
}
 

Example 11

From project netty-socketio, under directory /src/main/java/com/corundumstudio/socketio/.

Source file: SocketIOPipelineFactory.java

  18 
vote

private SSLContext createSSLContext(InputStream keyStoreFile,String keyStoreFilePassword) throws Exception {
  String algorithm=Security.getProperty("ssl.KeyManagerFactory.algorithm");
  if (algorithm == null) {
    algorithm="SunX509";
  }
  KeyStore ks=KeyStore.getInstance("JKS");
  ks.load(keyStoreFile,keyStoreFilePassword.toCharArray());
  KeyManagerFactory kmf=KeyManagerFactory.getInstance(algorithm);
  kmf.init(ks,keyStoreFilePassword.toCharArray());
  SSLContext serverContext=SSLContext.getInstance("TLS");
  serverContext.init(kmf.getKeyManagers(),null,null);
  return serverContext;
}
 

Example 12

From project OpenMEAP, under directory /java-shared/openmeap-shared-jdk5/src/com/openmeap/util/.

Source file: SSLUtils.java

  18 
vote

public static KeyStore loadKeyStore(String keyStoreFileName,String password) throws CertificateException, IOException, NoSuchAlgorithmException, KeyStoreException {
  KeyStore ks=null;
  FileInputStream fis=null;
  try {
    fis=new FileInputStream(keyStoreFileName);
    ks=loadKeyStore(fis,password);
  }
  finally {
    if (fis != null) {
      fis.close();
    }
  }
  return ks;
}
 

Example 13

From project org.openscada.atlantis, under directory /org.openscada.core.net/src/org/openscada/core/net/.

Source file: ConnectionHelper.java

  18 
vote

private static KeyManager[] getKeyManagers(final ConnectionInformation connectionInformation,final boolean isClient) throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException, CertificateException, IOException {
  if (isClient) {
    return null;
  }
  final KeyStore keyStore;
  keyStore=createKeyStore(connectionInformation);
  final String keyManagerFactory=KeyManagerFactory.getDefaultAlgorithm();
  final KeyManagerFactory kmf=KeyManagerFactory.getInstance(keyManagerFactory);
  kmf.init(keyStore,getPassword(connectionInformation,"sslCertPassword"));
  return kmf.getKeyManagers();
}
 

Example 14

From project OWASP-WebScarab, under directory /src/org/owasp/webscarab/httpclient/.

Source file: AbstractCertificateRepository.java

  18 
vote

public Certificate getCertificate(int keystoreIndex,int aliasIndex){
  try {
    KeyStore ks=(KeyStore)_keyStores.get(keystoreIndex);
    String alias=getAliasAt(keystoreIndex,aliasIndex);
    return ks.getCertificate(alias);
  }
 catch (  Exception e) {
    return null;
  }
}
 

Example 15

From project 4308Cirrus, under directory /tendril-android-lib/src/main/java/edu/colorado/cs/cirrus/android/.

Source file: HttpUtils.java

  17 
vote

public static HttpClient getNewHttpClient(){
  try {
    KeyStore trustStore=KeyStore.getInstance(KeyStore.getDefaultType());
    trustStore.load(null,null);
    SSLSocketFactory sf=new EasySSLSocketFactory(trustStore);
    sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    HttpParams params=new BasicHttpParams();
    HttpProtocolParams.setVersion(params,HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params,HTTP.UTF_8);
    SchemeRegistry registry=new SchemeRegistry();
    registry.register(new Scheme("http",PlainSocketFactory.getSocketFactory(),80));
    registry.register(new Scheme("https",sf,443));
    ClientConnectionManager ccm=new ThreadSafeClientConnManager(params,registry);
    return new DefaultHttpClient(ccm,params);
  }
 catch (  Exception e) {
    return new DefaultHttpClient();
  }
}
 

Example 16

From project AmDroid, under directory /AmenLib/src/main/java/com.jaeckel/amenoid/api/.

Source file: AmenHttpClient.java

  17 
vote

private SSLSocketFactory newSslSocketFactory(){
  try {
    KeyStore trusted=KeyStore.getInstance(keyStoreType);
    try {
      trusted.load(keyStoreStream,keyStorePassword.toCharArray());
    }
  finally {
      keyStoreStream.close();
    }
    SSLSocketFactory sf=new SSLSocketFactory(trusted);
    sf.setHostnameVerifier(new MyVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER));
    return sf;
  }
 catch (  Exception e) {
    throw new AssertionError(e);
  }
}
 

Example 17

From project androidpn, under directory /androidpn-server-bin-tomcat/src/org/androidpn/server/xmpp/net/.

Source file: Connection.java

  17 
vote

public void startTLS(ClientAuth authentication) throws Exception {
  log.debug("startTLS()...");
  KeyStore ksKeys=SSLConfig.getKeyStore();
  String keypass=SSLConfig.getKeyPassword();
  KeyStore ksTrust=SSLConfig.getc2sTrustStore();
  String trustpass=SSLConfig.getc2sTrustPassword();
  KeyManager[] km=SSLKeyManagerFactory.getKeyManagers(ksKeys,keypass);
  TrustManager[] tm=SSLTrustManagerFactory.getTrustManagers(ksTrust,trustpass);
  SSLContext tlsContext=SSLContext.getInstance("TLS");
  tlsContext.init(km,tm,null);
  SslFilter filter=new SslFilter(tlsContext);
  ioSession.getFilterChain().addFirst("tls",filter);
  ioSession.setAttribute(SslFilter.DISABLE_ENCRYPTION_ONCE,Boolean.TRUE);
  deliverRawText("<proceed xmlns=\"urn:ietf:params:xml:ns:xmpp-tls\"/>");
}
 

Example 18

From project anode, under directory /src/net/haltcondition/anode/.

Source file: WebtoolsHttpClient.java

  17 
vote

private SSLSocketFactory newSslSocketFactory(){
  try {
    KeyStore trusted=KeyStore.getInstance("BKS");
    InputStream in=context.getResources().openRawResource(R.raw.geotrust);
    try {
      trusted.load(in,"dummypass".toCharArray());
    }
  finally {
      in.close();
    }
    return new SSLSocketFactory(trusted);
  }
 catch (  Exception e) {
    throw new AssertionError(e);
  }
}
 

Example 19

From project apjp, under directory /APJP_LOCAL_JAVA/src/main/java/APJP/HTTPS/.

Source file: HTTPS.java

  17 
vote

public static synchronized SSLSocket createSSLSocket() throws HTTPSException {
  try {
    KeyStore defaultKeyStore=getDefaultKeyStore();
    PrivateKey privateKey=(PrivateKey)defaultKeyStore.getKey("APJP","APJP".toCharArray());
    Certificate certificateAuthority=defaultKeyStore.getCertificate("APJP");
    Certificate[] certificateArray=new Certificate[1];
    certificateArray[0]=certificateAuthority;
    KeyStore keyStore=KeyStore.getInstance(KeyStore.getDefaultType());
    keyStore.load(null,"APJP".toCharArray());
    keyStore.setCertificateEntry("APJP",certificateAuthority);
    keyStore.setKeyEntry("APJP",privateKey,"APJP".toCharArray(),certificateArray);
    SSLContext sslContext=SSLContext.getInstance("TLS");
    KeyManagerFactory keyManagerFactory=KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    keyManagerFactory.init(keyStore,"APJP".toCharArray());
    TrustManagerFactory trustManagerFactory=TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(keyStore);
    sslContext.init(keyManagerFactory.getKeyManagers(),trustManagerFactory.getTrustManagers(),null);
    SSLSocketFactory sslSocketFactory=(SSLSocketFactory)sslContext.getSocketFactory();
    return (SSLSocket)sslSocketFactory.createSocket();
  }
 catch (  Exception e) {
    logger.log(2,"HTTPS/CREATE_SSL_SOCKET: EXCEPTION",e);
    throw new HTTPSException("HTTPS/CREATE_SSL_SOCKET",e);
  }
}
 

Example 20

From project chililog-server, under directory /src/main/java/org/chililog/server/pubsub/jsonhttp/.

Source file: JsonHttpSslContextManager.java

  17 
vote

/** 
 * Constructor for singleton
 */
private JsonHttpSslContextManager(){
  try {
    String algorithm=Security.getProperty("ssl.KeyManagerFactory.algorithm");
    if (algorithm == null) {
      algorithm="SunX509";
    }
    SSLContext serverContext=null;
    try {
      KeyStore ks=KeyStore.getInstance("JKS");
      FileInputStream fin=new FileInputStream(AppProperties.getInstance().getPubSubJsonHttpKeyStorePath());
      ks.load(fin,AppProperties.getInstance().getPubSubJsonHttpKeyStorePassword().toCharArray());
      KeyManagerFactory kmf=KeyManagerFactory.getInstance(algorithm);
      kmf.init(ks,AppProperties.getInstance().getPubSubJsonHttpKeyStoreKeyPassword().toCharArray());
      serverContext=SSLContext.getInstance(PROTOCOL);
      serverContext.init(kmf.getKeyManagers(),null,null);
    }
 catch (    Exception e) {
      throw new Error("Failed to initialize the server-side SSLContext",e);
    }
    _serverContext=serverContext;
    SSLContext clientContext=null;
    try {
      clientContext=SSLContext.getInstance(PROTOCOL);
      clientContext.init(null,JsonHttpSSLTrustManager.getInstance().getTrustManagers(),null);
    }
 catch (    Exception e) {
      throw new Error("Failed to initialize the client-side SSLContext",e);
    }
    _clientContext=clientContext;
    return;
  }
 catch (  Exception ex) {
    _logger.error("Error initializing SslContextManager. " + ex.getMessage(),ex);
    System.exit(1);
  }
}
 

Example 21

From project cloudify, under directory /esc/src/main/java/org/cloudifysource/esc/driver/provisioning/azure/client/.

Source file: MicrosoftAzureSSLHelper.java

  17 
vote

/** 
 * @return .
 * @throws NoSuchAlgorithmException .
 * @throws KeyStoreException .
 * @throws CertificateException .
 * @throws IOException .
 * @throws UnrecoverableKeyException .
 * @throws KeyManagementException .
 */
public SSLContext createSSLContext() throws NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException, UnrecoverableKeyException, KeyManagementException {
  InputStream pfxFile=null;
  SSLContext context=null;
  try {
    pfxFile=new FileInputStream(new File(pathToPfxFile));
    KeyManagerFactory keyManagerFactory=KeyManagerFactory.getInstance(SUN_X_509_ALGORITHM);
    KeyStore keyStore=KeyStore.getInstance(KEY_STORE_CONTEXT);
    keyStore.load(pfxFile,pfxPassword.toCharArray());
    pfxFile.close();
    keyManagerFactory.init(keyStore,pfxPassword.toCharArray());
    context=SSLContext.getInstance("SSL");
    context.init(keyManagerFactory.getKeyManagers(),null,new SecureRandom());
    return context;
  }
  finally {
    if (pfxFile != null) {
      pfxFile.close();
    }
  }
}
 

Example 22

From project Cours-3eme-ann-e, under directory /Java/FerryInpres/src/identity_server/.

Source file: IdentityServer.java

  17 
vote

private void verifId(ObjectInputStream in,ObjectOutputStream out,Cipher cryptor,Cipher decryptor) throws IOException, ClassNotFoundException, IllegalBlockSizeException, BadPaddingException, SQLException, KeyStoreException, NoSuchAlgorithmException, CertificateException, UnrecoverableKeyException, KeyManagementException {
  for (; ; ) {
    VerifId query=(VerifId)Utils.decryptObject((byte[])in.readObject(),decryptor);
    Protocol valide;
    if ("BE".equals(query.getNationalite())) {
      PreparedStatement instruc=this._con.prepareStatement("SELECT COUNT(*) AS existe " + "FROM voyageur " + "WHERE id_national = ? AND nom = ? AND prenom = ?");
      instruc.setInt(1,query.getClientNationalId());
      instruc.setString(2,query.getClientName());
      instruc.setString(3,query.getClientSurname());
      ResultSet rs=instruc.executeQuery();
      rs.next();
      if (rs.getInt("existe") != 0)       valide=new Ack();
 else       valide=new Fail();
    }
 else {
      System.out.println("Consultation du registre international");
      KeyStore store=KeyStore.getInstance("JKS");
      store.load(new FileInputStream("client_keystore.jks"),"pwdpwd".toCharArray());
      KeyManagerFactory kmf=KeyManagerFactory.getInstance("SunX509");
      kmf.init(store,"pwdpwd".toCharArray());
      TrustManagerFactory tmf=TrustManagerFactory.getInstance("SunX509");
      tmf.init(store);
      SSLContext context=SSLContext.getInstance("SSLv3");
      context.init(kmf.getKeyManagers(),tmf.getTrustManagers(),null);
      SSLSocketFactory factory=context.getSocketFactory();
      SSLSocket sock=(SSLSocket)factory.createSocket(IdentityServer.prop.getProperty("INTERNATIONAL_SERVER"),Integer.parseInt(IdentityServer.prop.getProperty("INTERNATIONAL_PORT")));
      ObjectInputStream ssl_in=new ObjectInputStream(sock.getInputStream());
      ObjectOutputStream ssl_out=new ObjectOutputStream(sock.getOutputStream());
      ssl_out.writeObject(query);
      ssl_out.flush();
      valide=(Protocol)ssl_in.readObject();
      sock.close();
    }
    out.writeObject(Utils.cryptObject(valide,cryptor));
    out.flush();
  }
}
 

Example 23

From project DTE, under directory /src/cl/nic/dte/examples/.

Source file: EnviaDocumento.java

  17 
vote

/** 
 * @param args
 */
public static void main(String[] args) throws Exception {
  CmdLineParser parser=new CmdLineParser();
  CmdLineParser.Option certOpt=parser.addStringOption('c',"cert");
  CmdLineParser.Option passOpt=parser.addStringOption('s',"password");
  CmdLineParser.Option compaOpt=parser.addStringOption('f',"compania");
  try {
    parser.parse(args);
  }
 catch (  CmdLineParser.OptionException e) {
    printUsage();
    System.exit(2);
  }
  String certS=(String)parser.getOptionValue(certOpt);
  String passS=(String)parser.getOptionValue(passOpt);
  String compaS=(String)parser.getOptionValue(compaOpt);
  if (certS == null || passS == null || compaS == null) {
    printUsage();
    System.exit(2);
  }
  String[] otherArgs=parser.getRemainingArgs();
  if (otherArgs.length != 1) {
    printUsage();
    System.exit(2);
  }
  ConexionSii con=new ConexionSii();
  KeyStore ks=KeyStore.getInstance("PKCS12");
  ks.load(new FileInputStream(certS),passS.toCharArray());
  String alias=ks.aliases().nextElement();
  System.out.println("Usando certificado " + alias + " del archivo PKCS12: "+ certS);
  X509Certificate x509=(X509Certificate)ks.getCertificate(alias);
  PrivateKey pKey=(PrivateKey)ks.getKey(alias,passS.toCharArray());
  String token=con.getToken(pKey,x509);
  System.out.println("Token: " + token);
  String enviadorS=Utilities.getRutFromCertificate(x509);
  RECEPCIONDTEDocument recp=con.uploadEnvioCertificacion(enviadorS,compaS,new File(otherArgs[0]),token);
  System.out.println(recp.xmlText());
}
 

Example 24

From project flume, under directory /flume-ng-channels/flume-file-channel/src/test/java/org/apache/flume/channel/file/encryption/.

Source file: EncryptionTestUtils.java

  17 
vote

public static void createKeyStore(File keyStoreFile,File keyStorePasswordFile,Map<String,File> keyAliasPassword) throws Exception {
  KeyStore ks=KeyStore.getInstance("jceks");
  ks.load(null);
  List<String> keysWithSeperatePasswords=Lists.newArrayList();
  for (  String alias : keyAliasPassword.keySet()) {
    Key key=newKey();
    char[] password=null;
    File passwordFile=keyAliasPassword.get(alias);
    if (passwordFile == null) {
      password=Files.toString(keyStorePasswordFile,Charsets.UTF_8).toCharArray();
    }
 else {
      keysWithSeperatePasswords.add(alias);
      password=Files.toString(passwordFile,Charsets.UTF_8).toCharArray();
    }
    ks.setKeyEntry(alias,key,password,null);
  }
  char[] keyStorePassword=Files.toString(keyStorePasswordFile,Charsets.UTF_8).toCharArray();
  FileOutputStream outputStream=new FileOutputStream(keyStoreFile);
  ks.store(outputStream,keyStorePassword);
  outputStream.close();
}
 

Example 25

From project Fotolia-API, under directory /java/libs/httpcomponents-client-4.1.2/examples/org/apache/http/examples/client/.

Source file: ClientCustomSSL.java

  17 
vote

public final static void main(String[] args) throws Exception {
  DefaultHttpClient httpclient=new DefaultHttpClient();
  try {
    KeyStore trustStore=KeyStore.getInstance(KeyStore.getDefaultType());
    FileInputStream instream=new FileInputStream(new File("my.keystore"));
    try {
      trustStore.load(instream,"nopassword".toCharArray());
    }
  finally {
      try {
        instream.close();
      }
 catch (      Exception ignore) {
      }
    }
    SSLSocketFactory socketFactory=new SSLSocketFactory(trustStore);
    Scheme sch=new Scheme("https",443,socketFactory);
    httpclient.getConnectionManager().getSchemeRegistry().register(sch);
    HttpGet httpget=new HttpGet("https://localhost/");
    System.out.println("executing request" + httpget.getRequestLine());
    HttpResponse response=httpclient.execute(httpget);
    HttpEntity entity=response.getEntity();
    System.out.println("----------------------------------------");
    System.out.println(response.getStatusLine());
    if (entity != null) {
      System.out.println("Response content length: " + entity.getContentLength());
    }
    EntityUtils.consume(entity);
  }
  finally {
    httpclient.getConnectionManager().shutdown();
  }
}
 

Example 26

From project friendica-for-android, under directory /mw-android-friendica-01/src/de/wikilab/android/friendica01/.

Source file: TwAjax.java

  17 
vote

public DefaultHttpClient getNewHttpClient(){
  if (ignoreSSLCerts) {
    try {
      KeyStore trustStore=KeyStore.getInstance(KeyStore.getDefaultType());
      trustStore.load(null,null);
      SSLSocketFactory sf=new IgnoreCertsSSLSocketFactory(trustStore);
      sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
      HttpParams params=new BasicHttpParams();
      HttpProtocolParams.setVersion(params,HttpVersion.HTTP_1_1);
      HttpProtocolParams.setContentCharset(params,HTTP.UTF_8);
      SchemeRegistry registry=new SchemeRegistry();
      registry.register(new Scheme("http",PlainSocketFactory.getSocketFactory(),80));
      registry.register(new Scheme("https",sf,443));
      ClientConnectionManager ccm=new ThreadSafeClientConnManager(params,registry);
      return new DefaultHttpClient(ccm,params);
    }
 catch (    Exception e) {
      return new DefaultHttpClient();
    }
  }
 else {
    return new DefaultHttpClient();
  }
}
 

Example 27

From project gitblit, under directory /src/com/gitblit/.

Source file: MakeCertificate.java

  17 
vote

public static void generateSelfSignedCertificate(String hostname,File keystore,String keystorePassword){
  try {
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
    KeyPairGenerator kpGen=KeyPairGenerator.getInstance("RSA","BC");
    kpGen.initialize(1024,new SecureRandom());
    KeyPair pair=kpGen.generateKeyPair();
    X500NameBuilder builder=new X500NameBuilder(BCStyle.INSTANCE);
    builder.addRDN(BCStyle.OU,Constants.NAME);
    builder.addRDN(BCStyle.O,Constants.NAME);
    builder.addRDN(BCStyle.CN,hostname);
    Date notBefore=new Date(System.currentTimeMillis() - TimeUtils.ONEDAY);
    Date notAfter=new Date(System.currentTimeMillis() + 10 * TimeUtils.ONEYEAR);
    BigInteger serial=BigInteger.valueOf(System.currentTimeMillis());
    X509v3CertificateBuilder certGen=new JcaX509v3CertificateBuilder(builder.build(),serial,notBefore,notAfter,builder.build(),pair.getPublic());
    ContentSigner sigGen=new JcaContentSignerBuilder("SHA256WithRSAEncryption").setProvider(BC).build(pair.getPrivate());
    X509Certificate cert=new JcaX509CertificateConverter().setProvider(BC).getCertificate(certGen.build(sigGen));
    cert.checkValidity(new Date());
    cert.verify(cert.getPublicKey());
    KeyStore store=KeyStore.getInstance("JKS");
    if (keystore.exists()) {
      FileInputStream fis=new FileInputStream(keystore);
      store.load(fis,keystorePassword.toCharArray());
      fis.close();
    }
 else {
      store.load(null);
    }
    store.setKeyEntry(hostname,pair.getPrivate(),keystorePassword.toCharArray(),new java.security.cert.Certificate[]{cert});
    FileOutputStream fos=new FileOutputStream(keystore);
    store.store(fos,keystorePassword.toCharArray());
    fos.close();
  }
 catch (  Throwable t) {
    t.printStackTrace();
    throw new RuntimeException("Failed to generate self-signed certificate!",t);
  }
}
 

Example 28

From project gmc, under directory /src/org.gluster.storage.management.client/src/org/gluster/storage/management/client/.

Source file: AbstractClient.java

  17 
vote

private SSLContext initializeSSLContext(){
  SSLContext context=null;
  try {
    context=SSLContext.getInstance(PROTOCOL_TLS);
    KeyStore keyStore=KeyStore.getInstance(KEYSTORE_TYPE_JKS);
    keyStore.load(loadResource(TRUSTED_KEYSTORE),TRUSTED_KEYSTORE_ACCESS.toCharArray());
    KeyManagerFactory keyManagerFactory=KeyManagerFactory.getInstance(ALGORITHM_SUNX509);
    keyManagerFactory.init(keyStore,TRUSTED_KEYSTORE_ACCESS.toCharArray());
    TrustManagerFactory trustManagerFactory=TrustManagerFactory.getInstance(ALGORITHM_SUNX509);
    trustManagerFactory.init(keyStore);
    context.init(keyManagerFactory.getKeyManagers(),trustManagerFactory.getTrustManagers(),null);
  }
 catch (  Exception e) {
    throw new GlusterRuntimeException("Couldn't initialize SSL Context with Gluster Management Gateway! Error: " + e,e);
  }
  return context;
}
 

Example 29

From project ha-jdbc, under directory /src/main/java/net/sf/hajdbc/codec/crypto/.

Source file: CipherCodecFactory.java

  17 
vote

/** 
 * {@inheritDoc}
 * @see net.sf.hajdbc.codec.CodecFactory#createCodec(java.lang.String)
 */
@Override public Codec createCodec(String clusterId) throws SQLException {
  String type=this.getProperty(clusterId,Property.KEYSTORE_TYPE);
  File file=new File(this.getProperty(clusterId,Property.KEYSTORE_FILE));
  String password=this.getProperty(clusterId,Property.KEYSTORE_PASSWORD);
  String keyAlias=this.getProperty(clusterId,Property.KEY_ALIAS);
  String keyPassword=this.getProperty(clusterId,Property.KEY_PASSWORD);
  try {
    KeyStore store=KeyStore.getInstance(type);
    InputStream input=new FileInputStream(file);
    try {
      store.load(input,(password != null) ? password.toCharArray() : null);
    }
  finally {
      Resources.close(input);
    }
    return new CipherCodec(store.getKey(keyAlias,(keyPassword != null) ? keyPassword.toCharArray() : null));
  }
 catch (  GeneralSecurityException e) {
    throw new SQLException(e);
  }
catch (  IOException e) {
    throw new SQLException(e);
  }
}
 

Example 30

From project heritrix3, under directory /engine/src/main/java/org/archive/crawler/.

Source file: Heritrix.java

  17 
vote

/** 
 * Perform preparation to use an ad-hoc, created-as-necessary  certificate/keystore for HTTPS access. A keystore with new cert is created if necessary, as adhoc.keystore in the working directory. Otherwise, a preexisting adhoc.keystore is read  and the certificate fingerprint shown to assist in operator browser-side verification.
 * @param startupOut where to report fingerprint
 */
protected void useAdhocKeystore(PrintStream startupOut){
  try {
    File keystoreFile=new File(ADHOC_KEYSTORE);
    if (!keystoreFile.exists()) {
      String[] args={"-keystore",ADHOC_KEYSTORE,"-storepass",ADHOC_PASSWORD,"-keypass",ADHOC_PASSWORD,"-alias","adhoc","-genkey","-keyalg","RSA","-dname","CN=Heritrix Ad-Hoc HTTPS Certificate","-validity","3650"};
      KeyTool.main(args);
    }
    KeyStore keystore=KeyStore.getInstance(KeyStore.getDefaultType());
    InputStream inStream=new ByteArrayInputStream(FileUtils.readFileToByteArray(keystoreFile));
    keystore.load(inStream,ADHOC_PASSWORD.toCharArray());
    Certificate cert=keystore.getCertificate("adhoc");
    byte[] certBytes=cert.getEncoded();
    byte[] sha1=MessageDigest.getInstance("SHA1").digest(certBytes);
    startupOut.print("Using ad-hoc HTTPS certificate with fingerprint...\nSHA1");
    for (    byte b : sha1) {
      startupOut.print(String.format(":%02X",b));
    }
    startupOut.println("\nVerify in browser before accepting exception.");
  }
 catch (  Exception e) {
    throw new RuntimeException(e);
  }
}
 

Example 31

From project hotpotato, under directory /src/main/java/com/biasedbit/hotpotato/util/.

Source file: DummyHttpServer.java

  17 
vote

public static SslHandler createSelfSignedSslHandler() throws Exception {
  String algorithm="SunX509";
  String password="password";
  KeyStore keyStore=KeyStore.getInstance("JKS");
  InputStream keyStoreAsStream=null;
  try {
    keyStoreAsStream=new BufferedInputStream(new FileInputStream("src/main/resources/dummyserver/selfsigned.jks"));
    keyStore.load(keyStoreAsStream,password.toCharArray());
  }
  finally {
    if (keyStoreAsStream != null) {
      try {
        keyStoreAsStream.close();
      }
 catch (      Exception e) {
      }
    }
  }
  KeyManagerFactory keyManagerFactory=KeyManagerFactory.getInstance(algorithm);
  TrustManagerFactory trustManagerFactory=TrustManagerFactory.getInstance(algorithm);
  keyManagerFactory.init(keyStore,password.toCharArray());
  trustManagerFactory.init(keyStore);
  SSLContext context=SSLContext.getInstance("TLS");
  context.init(keyManagerFactory.getKeyManagers(),trustManagerFactory.getTrustManagers(),new SecureRandom());
  SSLEngine engine=context.createSSLEngine();
  engine.setUseClientMode(false);
  return new SslHandler(engine,true);
}
 

Example 32

From project hqapi, under directory /hqapi1/src/main/java/org/hyperic/hq/hqapi1/.

Source file: HQConnection.java

  17 
vote

private KeyStore getKeyStore(String keyStorePath,String keyStorePassword) throws KeyStoreException, IOException {
  FileInputStream keyStoreFileInputStream=null;
  try {
    KeyStore keystore=KeyStore.getInstance(KeyStore.getDefaultType());
    File file=new File(keyStorePath);
    char[] password=null;
    if (!file.exists()) {
      if (StringUtils.hasText(keyStorePath)) {
        throw new IOException("User specified keystore [" + keyStorePath + "] does not exist.");
      }
      password=keyStorePassword.toCharArray();
    }
    keyStoreFileInputStream=new FileInputStream(file);
    keystore.load(keyStoreFileInputStream,password);
    return keystore;
  }
 catch (  NoSuchAlgorithmException e) {
    throw new KeyStoreException(e);
  }
catch (  CertificateException e) {
    throw new KeyStoreException(e);
  }
 finally {
    if (keyStoreFileInputStream != null) {
      keyStoreFileInputStream.close();
      keyStoreFileInputStream=null;
    }
  }
}
 

Example 33

From project http-client, under directory /src/main/java/com/biasedbit/http/ssl/.

Source file: BogusSslContextFactory.java

  17 
vote

public BogusSslContextFactory(){
  String algorithm=Security.getProperty("ssl.KeyManagerFactory.algorithm");
  if (algorithm == null) {
    algorithm="X509";
  }
  SSLContext tmpServerContext;
  SSLContext tmpClientContext;
  try {
    KeyStore ks=KeyStore.getInstance("JKS");
    ks.load(BogusKeyStore.asInputStream(),BogusKeyStore.getKeyStorePassword());
    KeyManagerFactory kmf=KeyManagerFactory.getInstance(algorithm);
    kmf.init(ks,BogusKeyStore.getCertificatePassword());
    tmpServerContext=SSLContext.getInstance(PROTOCOL);
    tmpServerContext.init(kmf.getKeyManagers(),BogusTrustManagerFactory.getTrustManagers(),null);
  }
 catch (  Exception e) {
    throw new Error("Failed to initialize the server-side SSLContext",e);
  }
  try {
    tmpClientContext=SSLContext.getInstance(PROTOCOL);
    tmpClientContext.init(null,BogusTrustManagerFactory.getTrustManagers(),null);
  }
 catch (  Exception e) {
    throw new Error("Failed to initialize the client-side SSLContext",e);
  }
  serverContext=tmpServerContext;
  clientContext=tmpClientContext;
}
 

Example 34

From project http-testing-harness, under directory /server-provider/src/test/java/org/sonatype/tests/http/server/jetty/impl/.

Source file: ClientSideCertTest.java

  17 
vote

private CertificateHolder getCertificate(String alias,String keystorePath,String keystorePass) throws Exception {
  FileInputStream is=null;
  Certificate cert=null;
  DSAPrivateKey key;
  try {
    is=new FileInputStream(new File(keystorePath));
    KeyStore keystore=KeyStore.getInstance("JKS");
    keystore.load(is,keystorePass == null ? null : keystorePass.toString().toCharArray());
    cert=keystore.getCertificate(alias);
    key=(DSAPrivateKey)keystore.getKey(alias,keystorePass.toCharArray());
  }
  finally {
    if (is != null) {
      is.close();
    }
  }
  return new CertificateHolder(key,cert);
}
 

Example 35

From project httpClient, under directory /httpclient/src/examples/org/apache/http/examples/client/.

Source file: ClientCustomSSL.java

  17 
vote

public final static void main(String[] args) throws Exception {
  DefaultHttpClient httpclient=new DefaultHttpClient();
  try {
    KeyStore trustStore=KeyStore.getInstance(KeyStore.getDefaultType());
    FileInputStream instream=new FileInputStream(new File("my.keystore"));
    try {
      trustStore.load(instream,"nopassword".toCharArray());
    }
  finally {
      try {
        instream.close();
      }
 catch (      Exception ignore) {
      }
    }
    SSLSocketFactory socketFactory=new SSLSocketFactory(trustStore);
    Scheme sch=new Scheme("https",443,socketFactory);
    httpclient.getConnectionManager().getSchemeRegistry().register(sch);
    HttpGet httpget=new HttpGet("https://localhost/");
    System.out.println("executing request" + httpget.getRequestLine());
    HttpResponse response=httpclient.execute(httpget);
    HttpEntity entity=response.getEntity();
    System.out.println("----------------------------------------");
    System.out.println(response.getStatusLine());
    if (entity != null) {
      System.out.println("Response content length: " + entity.getContentLength());
    }
    EntityUtils.consume(entity);
  }
  finally {
    httpclient.getConnectionManager().shutdown();
  }
}
 

Example 36

From project httpserver, under directory /src/test/java/.

Source file: SimpleSSLContext.java

  17 
vote

SimpleSSLContext(String dir) throws IOException {
  try {
    String file=dir + "/testkeys";
    char[] passphrase="passphrase".toCharArray();
    KeyStore ks=KeyStore.getInstance("JKS");
    ks.load(new FileInputStream(file),passphrase);
    KeyManagerFactory kmf=KeyManagerFactory.getInstance("SunX509");
    kmf.init(ks,passphrase);
    TrustManagerFactory tmf=TrustManagerFactory.getInstance("SunX509");
    tmf.init(ks);
    ssl=SSLContext.getInstance("TLS");
    ssl.init(kmf.getKeyManagers(),tmf.getTrustManagers(),null);
  }
 catch (  KeyManagementException e) {
    throw new RuntimeException(e.getMessage());
  }
catch (  KeyStoreException e) {
    throw new RuntimeException(e.getMessage());
  }
catch (  UnrecoverableKeyException e) {
    throw new RuntimeException(e.getMessage());
  }
catch (  CertificateException e) {
    throw new RuntimeException(e.getMessage());
  }
catch (  NoSuchAlgorithmException e) {
    throw new RuntimeException(e.getMessage());
  }
}
 

Example 37

From project ihatovgram, under directory /src/client/android/ihatovgram/lib/httpcomponents-client-4.1.3/examples/org/apache/http/examples/client/.

Source file: ClientCustomSSL.java

  17 
vote

public final static void main(String[] args) throws Exception {
  DefaultHttpClient httpclient=new DefaultHttpClient();
  try {
    KeyStore trustStore=KeyStore.getInstance(KeyStore.getDefaultType());
    FileInputStream instream=new FileInputStream(new File("my.keystore"));
    try {
      trustStore.load(instream,"nopassword".toCharArray());
    }
  finally {
      try {
        instream.close();
      }
 catch (      Exception ignore) {
      }
    }
    SSLSocketFactory socketFactory=new SSLSocketFactory(trustStore);
    Scheme sch=new Scheme("https",443,socketFactory);
    httpclient.getConnectionManager().getSchemeRegistry().register(sch);
    HttpGet httpget=new HttpGet("https://localhost/");
    System.out.println("executing request" + httpget.getRequestLine());
    HttpResponse response=httpclient.execute(httpget);
    HttpEntity entity=response.getEntity();
    System.out.println("----------------------------------------");
    System.out.println(response.getStatusLine());
    if (entity != null) {
      System.out.println("Response content length: " + entity.getContentLength());
    }
    EntityUtils.consume(entity);
  }
  finally {
    httpclient.getConnectionManager().shutdown();
  }
}
 

Example 38

From project IOCipherServer, under directory /src/info/guardianproject/iocipher/server/.

Source file: KeyStoreGenerator.java

  17 
vote

public static void generateKeyStore(File keyStoreFile,String alias,int keyLength,String password,String cn,String o,String ou,String l,String st,String c) throws Exception {
  final java.security.KeyPairGenerator rsaKeyPairGenerator=java.security.KeyPairGenerator.getInstance("RSA");
  rsaKeyPairGenerator.initialize(keyLength);
  final KeyPair rsaKeyPair=rsaKeyPairGenerator.generateKeyPair();
  Provider[] ps=Security.getProviders();
  final KeyStore ks=KeyStore.getInstance("BKS");
  ks.load(null);
  final RSAPublicKey rsaPublicKey=(RSAPublicKey)rsaKeyPair.getPublic();
  char[] pw=password.toCharArray();
  final RSAPrivateKey rsaPrivateKey=(RSAPrivateKey)rsaKeyPair.getPrivate();
  final java.security.cert.X509Certificate certificate=makeCertificate(rsaPrivateKey,rsaPublicKey,cn,o,ou,l,st,c);
  final java.security.cert.X509Certificate[] certificateChain={certificate};
  ks.setKeyEntry(alias,rsaKeyPair.getPrivate(),pw,certificateChain);
  final FileOutputStream fos=new FileOutputStream(keyStoreFile);
  ks.store(fos,pw);
  fos.close();
}
 

Example 39

From project james, under directory /protocols-library/src/main/java/org/apache/james/protocols/lib/netty/.

Source file: AbstractConfigurableAsyncServer.java

  17 
vote

/** 
 * Build the SSLEngine
 * @throws Exception
 */
private void buildSSLContext() throws Exception {
  if (useStartTLS || useSSL) {
    FileInputStream fis=null;
    try {
      KeyStore ks=KeyStore.getInstance("JKS");
      fis=new FileInputStream(fileSystem.getFile(keystore));
      ks.load(fis,secret.toCharArray());
      KeyManagerFactory kmf=KeyManagerFactory.getInstance(x509Algorithm);
      kmf.init(ks,secret.toCharArray());
      SSLContext context=SSLContext.getInstance("TLS");
      context.init(kmf.getKeyManagers(),null,null);
      if (useStartTLS) {
        encryption=Encryption.createStartTls(context,enabledCipherSuites);
      }
 else {
        encryption=Encryption.createTls(context,enabledCipherSuites);
      }
    }
  finally {
      if (fis != null) {
        fis.close();
      }
    }
  }
}
 

Example 40

From project jftp, under directory /src/main/java/com/myjavaworld/jftp/ssl/.

Source file: JFTPTrustManager.java

  17 
vote

/** 
 * Checks if the given certificate chain can be trusted.
 * @param chain
 * @return <code>true</code>, if the certificate chain is trusted.<code>false</code>, otherwise.
 */
private boolean isTrusted(X509Certificate[] chain){
  boolean trusted=false;
  try {
    KeyStore keyStore=KeyStoreManager.getServerCertificateStore();
    for (int i=chain.length - 1; i >= 0; i--) {
      if (keyStore.getCertificateAlias(chain[i]) != null) {
        trusted=true;
        break;
      }
    }
  }
 catch (  Exception e) {
    trusted=false;
  }
  return trusted;
}
 

Example 41

From project jnrpe-lib, under directory /jnrpe-lib/src/main/java/it/jnrpe/.

Source file: JNRPEListenerThread.java

  17 
vote

/** 
 * Creates an SSLServerSocketFactory.
 * @return the newly creates SSL Server Socket Factory
 * @throws KeyStoreException
 * @throws CertificateException
 * @throws IOException
 * @throws UnrecoverableKeyException
 * @throws KeyManagementException
 */
private SSLServerSocketFactory getSSLSocketFactory() throws KeyStoreException, CertificateException, IOException, UnrecoverableKeyException, KeyManagementException {
  StreamManager h=new StreamManager();
  SSLContext ctx;
  KeyManagerFactory kmf;
  try {
    InputStream ksStream=getClass().getClassLoader().getResourceAsStream(KEYSTORE_NAME);
    h.handle(ksStream);
    ctx=SSLContext.getInstance("SSLv3");
    kmf=KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    KeyStore ks=KeyStore.getInstance("JKS");
    char[] passphrase=KEYSTORE_PWD.toCharArray();
    ks.load(ksStream,passphrase);
    kmf.init(ks,passphrase);
    ctx.init(kmf.getKeyManagers(),null,new java.security.SecureRandom());
  }
 catch (  NoSuchAlgorithmException e) {
    throw new SSLException("Unable to initialize SSLSocketFactory.\n" + e.getMessage());
  }
 finally {
    h.closeAll();
  }
  return ctx.getServerSocketFactory();
}
 

Example 42

From project jPOS, under directory /jpos/src/main/java/org/jpos/iso/.

Source file: SunJSSESocketFactory.java

  17 
vote

/** 
 * Create a SSLSocket Context
 * @return the SSLContext
 * @returns null if exception occurrs
 */
private SSLContext getSSLContext() throws ISOException {
  if (password == null)   password=getPassword();
  if (keyPassword == null)   keyPassword=getKeyPassword();
  if (keyStore == null || keyStore.length() == 0) {
    keyStore=System.getProperty("user.home") + File.separator + ".keystore";
  }
  try {
    KeyStore ks=KeyStore.getInstance("JKS");
    FileInputStream fis=new FileInputStream(new File(keyStore));
    ks.load(fis,password.toCharArray());
    fis.close();
    KeyManagerFactory km=KeyManagerFactory.getInstance("SunX509");
    km.init(ks,keyPassword.toCharArray());
    KeyManager[] kma=km.getKeyManagers();
    TrustManager[] tma=getTrustManagers(ks);
    SSLContext sslc=SSLContext.getInstance("SSL");
    sslc.init(kma,tma,SecureRandom.getInstance("SHA1PRNG"));
    return sslc;
  }
 catch (  Exception e) {
    throw new ISOException(e);
  }
 finally {
    password=null;
    keyPassword=null;
  }
}
 

Example 43

From project litle-sdk-for-java, under directory /lib/apache-cxf-2.5.2/samples/jax_rs/basic_https/src/main/java/org/apache/commons/httpclient/contrib/ssl/.

Source file: AuthSSLProtocolSocketFactory.java

  17 
vote

private static KeyStore createKeyStore(final URL url,final String password) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException {
  if (url == null) {
    throw new IllegalArgumentException("Keystore url may not be null");
  }
  LOG.debug("Initializing key store");
  KeyStore keystore=KeyStore.getInstance("jks");
  InputStream is=null;
  try {
    is=url.openStream();
    keystore.load(is,password != null ? password.toCharArray() : null);
  }
  finally {
    if (is != null)     is.close();
  }
  return keystore;
}
 

Example 44

From project LRJavaLib, under directory /src/com/navnorth/learningregistry/.

Source file: LRClient.java

  17 
vote

public static HttpClient getHttpClient(String scheme){
  if (scheme.equals("https")) {
    try {
      KeyStore trustStore=KeyStore.getInstance(KeyStore.getDefaultType());
      trustStore.load(null,null);
      SSLSocketFactory sf=new SelfSignSSLSocketFactory(trustStore);
      sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
      HttpParams params=new BasicHttpParams();
      HttpProtocolParams.setVersion(params,HttpVersion.HTTP_1_1);
      HttpProtocolParams.setContentCharset(params,HTTP.UTF_8);
      SchemeRegistry registry=new SchemeRegistry();
      registry.register(new Scheme("http",PlainSocketFactory.getSocketFactory(),80));
      registry.register(new Scheme("https",sf,443));
      ClientConnectionManager ccm=new ThreadSafeClientConnManager(params,registry);
      return new DefaultHttpClient(ccm,params);
    }
 catch (    Exception e) {
      return new DefaultHttpClient();
    }
  }
 else {
    return new DefaultHttpClient();
  }
}
 

Example 45

From project masa, under directory /plugins/maven-apkbuilder-plugin/src/main/java/org/jvending/masa/plugin/apkbuilder/.

Source file: ApkBuilderMojo.java

  17 
vote

private SigningInfo loadKeyEntry(String osKeyStorePath,String storeType,char[] keyStorePassword,char[] privateKeyPassword,String alias) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException, UnrecoverableEntryException {
  try {
    KeyStore keyStore=KeyStore.getInstance(storeType != null ? storeType : KeyStore.getDefaultType());
    FileInputStream fis=new FileInputStream(osKeyStorePath);
    keyStore.load(fis,keyStorePassword);
    fis.close();
    KeyStore.PrivateKeyEntry store=(KeyStore.PrivateKeyEntry)keyStore.getEntry(alias,new KeyStore.PasswordProtection(privateKeyPassword));
    return new SigningInfo(store.getPrivateKey(),(X509Certificate)store.getCertificate());
  }
 catch (  FileNotFoundException e) {
    getLog().error("Failed to load key: alias = " + alias + ", path = "+ osKeyStorePath);
    e.printStackTrace();
  }
  return null;
}
 

Example 46

From project mina, under directory /examples/src/main/java/org/apache/mina/examples/http/.

Source file: BogusSslContextFactory.java

  17 
vote

private static SSLContext createBougusServerSslContext() throws GeneralSecurityException, IOException {
  KeyStore ks=KeyStore.getInstance("JKS");
  InputStream in=null;
  try {
    in=BogusSslContextFactory.class.getResourceAsStream(BOGUS_KEYSTORE);
    ks.load(in,BOGUS_PW);
  }
  finally {
    if (in != null) {
      try {
        in.close();
      }
 catch (      IOException ignored) {
      }
    }
  }
  KeyManagerFactory kmf=KeyManagerFactory.getInstance(KEY_MANAGER_FACTORY_ALGORITHM);
  kmf.init(ks,BOGUS_PW);
  SSLContext sslContext=SSLContext.getInstance(PROTOCOL);
  sslContext.init(kmf.getKeyManagers(),BogusTrustManagerFactory.X509_MANAGERS,null);
  return sslContext;
}
 

Example 47

From project MobiPerf, under directory /android/src/com/mobiperf/speedometer/.

Source file: Checkin.java

  17 
vote

/** 
 * Return an appropriately-configured HTTP client.
 */
private HttpClient getNewHttpClient(){
  DefaultHttpClient client;
  try {
    KeyStore trustStore=KeyStore.getInstance(KeyStore.getDefaultType());
    trustStore.load(null,null);
    SSLSocketFactory sf=new MySSLSocketFactory(trustStore);
    sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    HttpParams params=new BasicHttpParams();
    HttpProtocolParams.setVersion(params,HttpVersion.HTTP_1_1);
    HttpProtocolParams.setContentCharset(params,HTTP.UTF_8);
    HttpConnectionParams.setConnectionTimeout(params,POST_TIMEOUT_MILLISEC);
    HttpConnectionParams.setSoTimeout(params,POST_TIMEOUT_MILLISEC);
    SchemeRegistry registry=new SchemeRegistry();
    registry.register(new Scheme("http",PlainSocketFactory.getSocketFactory(),80));
    registry.register(new Scheme("https",sf,443));
    ClientConnectionManager ccm=new ThreadSafeClientConnManager(params,registry);
    client=new DefaultHttpClient(ccm,params);
  }
 catch (  Exception e) {
    Logger.w("Unable to create SSL HTTP client",e);
    client=new DefaultHttpClient();
  }
  CookieStore store=new BasicCookieStore();
  store.addCookie(authCookie);
  client.setCookieStore(store);
  return client;
}
 

Example 48

From project netty, under directory /example/src/main/java/io/netty/example/http/websocketx/sslserver/.

Source file: WebSocketSslServerSslContext.java

  17 
vote

/** 
 * Constructor for singleton
 */
private WebSocketSslServerSslContext(){
  try {
    String algorithm=Security.getProperty("ssl.KeyManagerFactory.algorithm");
    if (algorithm == null) {
      algorithm="SunX509";
    }
    SSLContext serverContext;
    try {
      String keyStoreFilePath=System.getProperty("keystore.file.path");
      String keyStoreFilePassword=System.getProperty("keystore.file.password");
      KeyStore ks=KeyStore.getInstance("JKS");
      FileInputStream fin=new FileInputStream(keyStoreFilePath);
      ks.load(fin,keyStoreFilePassword.toCharArray());
      KeyManagerFactory kmf=KeyManagerFactory.getInstance(algorithm);
      kmf.init(ks,keyStoreFilePassword.toCharArray());
      serverContext=SSLContext.getInstance(PROTOCOL);
      serverContext.init(kmf.getKeyManagers(),null,null);
    }
 catch (    Exception e) {
      throw new Error("Failed to initialize the server-side SSLContext",e);
    }
    _serverContext=serverContext;
  }
 catch (  Exception ex) {
    if (logger.isErrorEnabled()) {
      logger.error("Error initializing SslContextManager. " + ex.getMessage(),ex);
    }
    System.exit(1);
  }
}
 

Example 49

From project ODE-X, under directory /runtime/src/main/java/org/apache/ode/runtime/exec/platform/.

Source file: NodeImpl.java

  17 
vote

@PostConstruct public void init(){
  try {
    encKey=clusterConfig.getSecurity().getEncKey();
    KeyStore ks=KeyStore.getInstance("PKCS12");
    ks.load(new ByteArrayInputStream(clusterConfig.getSecurity().getEncKeyStore()),clusterConfig.getSecurity().getEncKeyStorePass().toCharArray());
    PrivateKey privateKey=(PrivateKey)ks.getKey(clusterConfig.getSecurity().getKeyAlias(),clusterConfig.getSecurity().getEncKeyPass().toCharArray());
    if (privateKey == null) {
      throw new Exception(String.format("Can't find private key alias %s in cluster config keystore",clusterConfig.getSecurity().getKeyAlias()));
    }
    java.security.cert.Certificate cert=ks.getCertificate(clusterConfig.getSecurity().getKeyAlias());
    if (cert == null) {
      throw new Exception(String.format("Can't find public key alias %s in cluster config keystore",clusterConfig.getSecurity().getKeyAlias()));
    }
    PublicKey publicKey=cert.getPublicKey();
    clusterKey=new KeyPair(publicKey,privateKey);
  }
 catch (  Exception e) {
    log.log(Level.SEVERE,"",e);
  }
}
 

Example 50

From project org.ops4j.pax.url, under directory /pax-url-aether/src/test/java/amazon/.

Source file: Util.java

  17 
vote

static void setupClientSSL() throws Exception {
  KeyStore store=KeyStore.getInstance(KeyStore.getDefaultType());
  FileInputStream storeInput=new FileInputStream(getTestKeystore());
  char[] storePass=getTestKeystorePassword().toCharArray();
  store.load(storeInput,storePass);
  TrustManagerFactory manager=TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
  manager.init(store);
  SSLContext context=SSLContext.getInstance("TLS");
  context.init(null,manager.getTrustManagers(),null);
  SSLSocketFactory factory=context.getSocketFactory();
  HttpsURLConnection.setDefaultSSLSocketFactory(factory);
  HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier(){
    public boolean verify(    String hostname,    SSLSession session){
      return true;
    }
  }
);
}
 

Example 51

From project android-rackspacecloud, under directory /src/com/rackspace/cloud/files/api/client/.

Source file: CustomHttpClient.java

  15 
vote

private SSLSocketFactory newSslSocketFactory(){
  try {
    if (trusted == null) {
      trusted=KeyStore.getInstance("BKS");
      InputStream in=context.getResources().openRawResource(R.raw.android231);
      try {
        trusted.load(in,"changeit".toCharArray());
      }
  finally {
        in.close();
      }
    }
    return new SSLSocketFactory(trusted);
  }
 catch (  Exception e) {
    throw new AssertionError(e);
  }
}
 

Example 52

From project BombusLime, under directory /src/org/bombusim/networking/.

Source file: AndroidSSLSocketFactory.java

  15 
vote

public AndroidSSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
  super(truststore);
  TrustManager tm=new X509TrustManager(){
    public void checkClientTrusted(    X509Certificate[] chain,    String authType) throws CertificateException {
    }
    public void checkServerTrusted(    X509Certificate[] chain,    String authType) throws CertificateException {
    }
    public X509Certificate[] getAcceptedIssuers(){
      return null;
    }
  }
;
  sslContext.init(null,new TrustManager[]{tm},null);
}
 

Example 53

From project cp-common-utils, under directory /src/com/clarkparsia/common/net/.

Source file: BasicX509TrustManager.java

  15 
vote

public BasicX509TrustManager(KeyStore keystore) throws NoSuchAlgorithmException, KeyStoreException {
  super();
  TrustManagerFactory factory=TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
  factory.init(keystore);
  TrustManager[] trustmanagers=factory.getTrustManagers();
  if (trustmanagers.length == 0) {
    throw new NoSuchAlgorithmException("no trust manager found");
  }
  mDefaultTrustManager=(X509TrustManager)trustmanagers[0];
}
 

Example 54

From project dreamDroid, under directory /src/net/reichholf/dreamdroid/helpers/.

Source file: EasyX509TrustManager.java

  15 
vote

/** 
 * Constructor for EasyX509TrustManager.
 */
public EasyX509TrustManager(KeyStore keystore) throws NoSuchAlgorithmException, KeyStoreException {
  super();
  TrustManagerFactory factory=TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
  factory.init(keystore);
  TrustManager[] trustmanagers=factory.getTrustManagers();
  if (trustmanagers.length == 0) {
    throw new NoSuchAlgorithmException("no trust manager found");
  }
  this.mStandardTrustManager=(X509TrustManager)trustmanagers[0];
}
 

Example 55

From project ereviewboard, under directory /org.review_board.ereviewboard.core/src/org/apache/commons/httpclient/contrib/ssl/.

Source file: EasyX509TrustManager.java

  15 
vote

/** 
 * Constructor for EasyX509TrustManager.
 */
public EasyX509TrustManager(KeyStore keystore) throws NoSuchAlgorithmException, KeyStoreException {
  super();
  TrustManagerFactory factory=TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
  factory.init(keystore);
  TrustManager[] trustmanagers=factory.getTrustManagers();
  if (trustmanagers.length == 0) {
    throw new NoSuchAlgorithmException("no trust manager found");
  }
  this.standardTrustManager=(X509TrustManager)trustmanagers[0];
}
 

Example 56

From project freemind, under directory /freemind/plugins/script/.

Source file: SignedScriptHandler.java

  15 
vote

private void initializeKeystore(char[] pPassword){
  if (mKeyStore != null)   return;
  java.io.FileInputStream fis=null;
  try {
    mKeyStore=KeyStore.getInstance(KeyStore.getDefaultType());
    fis=new java.io.FileInputStream(System.getProperty("user.home") + File.separator + ".keystore");
    mKeyStore.load(fis,pPassword);
  }
 catch (  Exception e) {
    Resources.getInstance().logException(e);
  }
 finally {
    if (fis != null) {
      try {
        fis.close();
      }
 catch (      IOException e) {
        Resources.getInstance().logException(e);
      }
    }
  }
}
 

Example 57

From project Gibberbot, under directory /src/info/guardianproject/otr/app/im/plugin/xmpp/.

Source file: ServerTrustManager.java

  15 
vote

/** 
 * Construct a trust manager for XMPP connections. Certificates are considered verified if: <ul> <li>The root certificate is in our trust store <li>The chain is valid <li>The leaf certificate contains the identity of the domain or the requested server </ul>
 * @param context - the Android context for presenting notifications
 * @param domain - the domain requested by the user
 * @param requestedServer - the connect server requested by the user
 * @param configuration - the XMPP configuration
 */
public ServerTrustManager(Context context,String domain,String requestedServer,ConnectionConfiguration configuration){
  this.context=context;
  this.configuration=configuration;
  this.domain=domain;
  this.server=requestedServer;
  if (this.server == null) {
    this.server=domain;
  }
  InputStream in=null;
  try {
    trustStore=KeyStore.getInstance(configuration.getTruststoreType());
    in=context.getResources().openRawResource(R.raw.cacerts);
    trustStore.load(in,configuration.getTruststorePassword().toCharArray());
  }
 catch (  Exception e) {
    Log.e(TAG,e.getMessage(),e);
    configuration.setVerifyRootCAEnabled(false);
  }
 finally {
    if (in != null) {
      try {
        in.close();
      }
 catch (      IOException ioe) {
      }
    }
  }
}
 

Example 58

From project Haven-and-Hearth-client-modified-by-Ender, under directory /src/haven/.

Source file: SslHelper.java

  15 
vote

public SslHelper(){
  creds=null;
  try {
    trusted=KeyStore.getInstance(KeyStore.getDefaultType());
    trusted.load(null,null);
  }
 catch (  Exception e) {
    throw (new Error(e));
  }
}
 

Example 59

From project iSpace, under directory /base/httpcrawler/src/main/java/com/villemos/ispace/httpcrawler/.

Source file: EasyX509TrustManager.java

  15 
vote

/** 
 * Constructor for EasyX509TrustManager.
 */
public EasyX509TrustManager(KeyStore keystore) throws NoSuchAlgorithmException, KeyStoreException {
  super();
  TrustManagerFactory factory=TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
  factory.init(keystore);
  TrustManager[] trustmanagers=factory.getTrustManagers();
  if (trustmanagers.length == 0) {
    throw new NoSuchAlgorithmException("no trust manager found");
  }
  this.standardTrustManager=(X509TrustManager)trustmanagers[0];
}
 

Example 60

From project Kairos, under directory /src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/.

Source file: DummyX509TrustManager.java

  15 
vote

/** 
 * Constructor for DummyX509TrustManager.
 */
public DummyX509TrustManager(KeyStore keystore) throws NoSuchAlgorithmException, KeyStoreException {
  super();
  String algo=TrustManagerFactory.getDefaultAlgorithm();
  TrustManagerFactory factory=TrustManagerFactory.getInstance(algo);
  factory.init(keystore);
  TrustManager[] trustmanagers=factory.getTrustManagers();
  if (trustmanagers.length == 0) {
    throw new NoSuchAlgorithmException(algo + " trust manager not supported");
  }
  this.standardTrustManager=(X509TrustManager)trustmanagers[0];
}
 

Example 61

From project Maimonides, under directory /src/com/codeko/apps/maimonides/dnie/.

Source file: DNIe.java

  15 
vote

private KeyStore getKeyStore() throws Exception {
  if (keyStore == null) {
    Provider p=new sun.security.pkcs11.SunPKCS11(new ByteArrayInputStream(DNIe.getConfig()));
    Security.addProvider(p);
    keyStore=KeyStore.getInstance("PKCS11",p);
    try {
      keyStore.load(null,getPin().toCharArray());
    }
 catch (    Exception e) {
      keyStore=null;
      throw e;
    }
  }
  return keyStore;
}
 

Example 62

From project maven-wagon, under directory /wagon-providers/wagon-http-shared4/src/main/java/org/apache/maven/wagon/shared/http4/.

Source file: EasyX509TrustManager.java

  15 
vote

/** 
 * Constructor for EasyX509TrustManager.
 */
public EasyX509TrustManager(KeyStore keystore) throws NoSuchAlgorithmException, KeyStoreException {
  super();
  TrustManagerFactory factory=TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
  factory.init(keystore);
  TrustManager[] trustmanagers=factory.getTrustManagers();
  if (trustmanagers.length == 0) {
    throw new NoSuchAlgorithmException("no trust manager found");
  }
  this.standardTrustManager=(X509TrustManager)trustmanagers[0];
}
 

Example 63

From project Mujina, under directory /mujina-common/src/main/java/nl/surfnet/mujina/model/.

Source file: CommonConfigurationImpl.java

  15 
vote

@Override public void setEntityID(final String newEntityId){
  try {
    final KeyStore.PasswordProtection passwordProtection=new KeyStore.PasswordProtection(keystorePassword.toCharArray());
    final KeyStore.Entry keyStoreEntry=keyStore.getEntry(this.entityId,passwordProtection);
    keyStore.setEntry(newEntityId,keyStoreEntry,passwordProtection);
    privateKeyPasswords.put(newEntityId,keystorePassword);
  }
 catch (  Exception e) {
    LOGGER.warn("Unable to update signing key in key store",e);
  }
  this.entityId=newEntityId;
}
 

Example 64

From project nutch, under directory /src/plugin/protocol-httpclient/src/java/org/apache/nutch/protocol/httpclient/.

Source file: DummyX509TrustManager.java

  15 
vote

/** 
 * Constructor for DummyX509TrustManager.
 */
public DummyX509TrustManager(KeyStore keystore) throws NoSuchAlgorithmException, KeyStoreException {
  super();
  String algo=TrustManagerFactory.getDefaultAlgorithm();
  TrustManagerFactory factory=TrustManagerFactory.getInstance(algo);
  factory.init(keystore);
  TrustManager[] trustmanagers=factory.getTrustManagers();
  if (trustmanagers.length == 0) {
    throw new NoSuchAlgorithmException(algo + " trust manager not supported");
  }
  this.standardTrustManager=(X509TrustManager)trustmanagers[0];
}
 

Example 65

From project openclaws, under directory /cat/WEB-INF/src/edu/rit/its/claws/cat/.

Source file: CatSecureSocketFactory.java

  15 
vote

/** 
 * Set up this class to begin providing instances.
 * @param ksin      An input stream to read the keystore from
 * @param _ksPass   The password for that keystore
 * @throws Exception
 */
public static void init(InputStream ksin,String _ksPass) throws Exception {
  ks=KeyStore.getInstance("jks");
  ksPass=_ksPass;
  ks.load(ksin,_ksPass.toCharArray());
  log.info("Keystore Initialized");
}
 

Example 66

From project Orweb, under directory /src/info/guardianproject/browser/.

Source file: ModSSLSocketFactory.java

  15 
vote

public ModSSLSocketFactory(String algorithm,final KeyStore keystore,final String keystorePassword,final KeyStore truststore,final SecureRandom random,final HostNameResolver nameResolver) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
  super();
  if (algorithm == null) {
    algorithm=TLS;
  }
  KeyManager[] keymanagers=null;
  if (keystore != null) {
    keymanagers=createKeyManagers(keystore,keystorePassword);
  }
  TrustManager[] trustmanagers=null;
  if (truststore != null) {
    trustmanagers=createTrustManagers(truststore);
  }
  this.sslcontext=SSLContext.getInstance(algorithm);
  this.sslcontext.init(keymanagers,trustmanagers,random);
  this.socketfactory=this.sslcontext.getSocketFactory();
  this.nameResolver=nameResolver;
}