Beispiel #1
0
 private KeyStore createKeyStore(@Nullable String path)
     throws IOException, KeyStoreException, NoSuchAlgorithmException, CertificateException {
   String keyStoreType = KeyStore.getDefaultType();
   char[] defaultPassword = "******".toCharArray();
   if (path != null) {
     // If the user provided path, only try to load the keystore at that path.
     KeyStore keyStore = KeyStore.getInstance(keyStoreType);
     FileInputStream is = new FileInputStream(path);
     keyStore.load(is, defaultPassword);
     return keyStore;
   }
   try {
     // Check if we are on Android.
     Class version = Class.forName("android.os.Build$VERSION");
     // Build.VERSION_CODES.ICE_CREAM_SANDWICH is 14.
     if (version.getDeclaredField("SDK_INT").getInt(version) >= 14) {
       // After ICS, Android provided this nice method for loading the keystore,
       // so we don't have to specify the location explicitly.
       KeyStore keystore = KeyStore.getInstance("AndroidCAStore");
       keystore.load(null, null);
       return keystore;
     } else {
       keyStoreType = "BKS";
       path =
           System.getProperty("java.home")
               + "/etc/security/cacerts.bks".replace('/', File.separatorChar);
     }
   } catch (ClassNotFoundException e) {
     // NOP. android.os.Build is not present, so we are not on Android. Fall through.
   } catch (NoSuchFieldException e) {
     throw new RuntimeException(e); // Should never happen.
   } catch (IllegalAccessException e) {
     throw new RuntimeException(e); // Should never happen.
   }
   if (path == null) {
     path = System.getProperty("javax.net.ssl.trustStore");
   }
   if (path == null) {
     // Try this default system location for Linux/Windows/OSX.
     path =
         System.getProperty("java.home")
             + "/lib/security/cacerts".replace('/', File.separatorChar);
   }
   try {
     KeyStore keyStore = KeyStore.getInstance(keyStoreType);
     FileInputStream is = new FileInputStream(path);
     keyStore.load(is, defaultPassword);
     return keyStore;
   } catch (FileNotFoundException e) {
     // If we failed to find a system trust store, load our own fallback trust store. This can fail
     // on Android
     // but we should never reach it there.
     KeyStore keyStore = KeyStore.getInstance("JKS");
     InputStream is = getClass().getResourceAsStream("cacerts");
     keyStore.load(is, defaultPassword);
     return keyStore;
   }
 }
 static KeyStore getKeyStore() throws Exception {
   InputStream in = new FileInputStream(new File(BASE, "rsakeys.ks"));
   KeyStore ks = KeyStore.getInstance("JKS");
   ks.load(in, password);
   in.close();
   return ks;
 }
Beispiel #3
0
  public boolean createSelfSignedKeystore(
      String cn,
      String keystoreFile,
      String keystorePassword,
      String privateKeyPassword,
      String privateKeyAlias) {
    KeyStore ks = null;

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

      KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DSA");
      keyGen.initialize(1024, new SecureRandom());
      KeyPair keypair = keyGen.generateKeyPair();
      PrivateKey privkey = keypair.getPrivate();
      PublicKey pubkey = keypair.getPublic();

      Hashtable<DERObjectIdentifier, String> attrs = new Hashtable<DERObjectIdentifier, String>();
      Vector<DERObjectIdentifier> ordering = new Vector<DERObjectIdentifier>();
      ordering.add(X509Name.CN);
      attrs.put(X509Name.CN, cn);
      X509Name issuerDN = new X509Name(ordering, attrs);
      X509Name subjectDN = new X509Name(ordering, attrs);

      Date validFrom = new Date();
      validFrom.setTime(validFrom.getTime() - (10 * 60 * 1000));
      Date validTo = new Date();
      validTo.setTime(validTo.getTime() + (20 * (24 * 60 * 60 * 1000)));

      X509V3CertificateGenerator x509 = new X509V3CertificateGenerator();
      x509.setSignatureAlgorithm("SHA1withDSA");
      x509.setIssuerDN(issuerDN);
      x509.setSubjectDN(subjectDN);
      x509.setPublicKey(pubkey);
      x509.setNotBefore(validFrom);
      x509.setNotAfter(validTo);
      x509.setSerialNumber(new BigInteger(128, new Random()));

      X509Certificate[] cert = new X509Certificate[1];
      cert[0] = x509.generate(privkey, "BC");
      java.security.cert.Certificate[] chain = new java.security.cert.Certificate[1];
      chain[0] = cert[0];

      ks.setKeyEntry(privateKeyAlias, privkey, privateKeyPassword.toCharArray(), cert);
      ks.setKeyEntry(privateKeyAlias, privkey, privateKeyPassword.toCharArray(), chain);
      ks.store(new FileOutputStream(keystoreFile), keystorePassword.toCharArray());

      String IDP_RFC_CERT = "WEB-INF/guanxi_idp/keystore/guanxi_idp_cert.txt";

      PEMWriter pemWriter = new PEMWriter(new FileWriter(servletContext.getRealPath(IDP_RFC_CERT)));
      pemWriter.writeObject(cert[0]);
      pemWriter.close();

      return true;
    } catch (Exception se) {
      return false;
    }
  }
Beispiel #4
0
 private static KeyStore readKeyStore(String name) throws Exception {
   File file = new File(PATH, name);
   InputStream in = new FileInputStream(file);
   KeyStore ks = KeyStore.getInstance("JKS");
   ks.load(in, passwd);
   in.close();
   return ks;
 }
Beispiel #5
0
 /**
  * Creates an empty keystore
  *
  * @throws Exception
  */
 private void createKeystore() throws Exception {
   if (keystore == null) {
     Security.addProvider(bouncyCastleProvider);
     keystore =
         KeyStore.getInstance(Configuration.getSSLClientKeyStoreType(), bouncyCastleProvider);
     keystore.load(null, KEYSTORE_PASSWORD.toCharArray());
   }
 }
  public static HttpClient getCertifiedHttpClient() throws IDPTokenManagerException {
    HttpClient client = null;
    InputStream inStream = null;
    try {
      if (Constants.SERVER_PROTOCOL.equalsIgnoreCase("https://")) {
        KeyStore localTrustStore = KeyStore.getInstance("BKS");
        inStream =
            IdentityProxy.getInstance()
                .getContext()
                .getResources()
                .openRawResource(R.raw.emm_truststore);
        localTrustStore.load(inStream, Constants.TRUSTSTORE_PASSWORD.toCharArray());

        SchemeRegistry schemeRegistry = new SchemeRegistry();
        schemeRegistry.register(
            new Scheme("http", PlainSocketFactory.getSocketFactory(), Constants.HTTP));
        SSLSocketFactory sslSocketFactory = new SSLSocketFactory(localTrustStore);
        sslSocketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        schemeRegistry.register(new Scheme("https", sslSocketFactory, Constants.HTTPS));
        HttpParams params = new BasicHttpParams();
        ClientConnectionManager connectionManager =
            new ThreadSafeClientConnManager(params, schemeRegistry);

        client = new DefaultHttpClient(connectionManager, params);

      } else {
        client = new DefaultHttpClient();
      }

    } catch (KeyStoreException e) {
      String errorMsg = "Error occurred while accessing keystore.";
      Log.e(TAG, errorMsg);
      throw new IDPTokenManagerException(errorMsg, e);
    } catch (CertificateException e) {
      String errorMsg = "Error occurred while loading certificate.";
      Log.e(TAG, errorMsg);
      throw new IDPTokenManagerException(errorMsg, e);
    } catch (NoSuchAlgorithmException e) {
      String errorMsg = "Error occurred while due to mismatch of defined algorithm.";
      Log.e(TAG, errorMsg);
      throw new IDPTokenManagerException(errorMsg, e);
    } catch (UnrecoverableKeyException e) {
      String errorMsg = "Error occurred while accessing keystore.";
      Log.e(TAG, errorMsg);
      throw new IDPTokenManagerException(errorMsg, e);
    } catch (KeyManagementException e) {
      String errorMsg = "Error occurred while accessing keystore.";
      Log.e(TAG, errorMsg);
      throw new IDPTokenManagerException(errorMsg, e);
    } catch (IOException e) {
      String errorMsg = "Error occurred while loading trust store. ";
      Log.e(TAG, errorMsg);
      throw new IDPTokenManagerException(errorMsg, e);
    } finally {
      StreamHandlerUtil.closeInputStream(inStream, TAG);
    }
    return client;
  }
  /*
   * Define the client side of the test.
   *
   * If the server prematurely exits, serverReady will be set to true
   * to avoid infinite hangs.
   */
  void doClientSide() throws Exception {

    /*
     * Wait for server to get started.
     */
    while (!serverReady) {
      Thread.sleep(50);
    }

    /*
     * See if an unknown keystore actually gets checked ok.
     */
    System.out.println("==============");
    System.out.println("Starting test0");
    KeyStore uks = KeyStore.getInstance("JKS");
    SSLContext ctx = SSLContext.getInstance("TLS");
    KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");

    uks.load(new FileInputStream(unknownFilename), cpasswd);
    kmf.init(uks, cpasswd);

    TrustManager[] tms = new TrustManager[] {new MyJavaxX509TrustManager()};

    ctx.init(kmf.getKeyManagers(), tms, null);

    SSLSocketFactory sslsf = (SSLSocketFactory) ctx.getSocketFactory();

    System.out.println("Trying first socket " + serverPort);
    SSLSocket sslSocket = (SSLSocket) sslsf.createSocket("localhost", serverPort);

    doTest(sslSocket);

    /*
     * Now try the other way.
     */
    com.sun.net.ssl.SSLContext ctx1 = com.sun.net.ssl.SSLContext.getInstance("TLS");
    com.sun.net.ssl.KeyManagerFactory kmf1 =
        com.sun.net.ssl.KeyManagerFactory.getInstance("SunX509");
    kmf1.init(uks, cpasswd);

    com.sun.net.ssl.TrustManager[] tms1 =
        new com.sun.net.ssl.TrustManager[] {new MyComX509TrustManager()};

    ctx1.init(kmf1.getKeyManagers(), tms1, null);

    sslsf = (SSLSocketFactory) ctx1.getSocketFactory();

    System.out.println("Trying second socket " + serverPort1);
    sslSocket = (SSLSocket) sslsf.createSocket("localhost", serverPort1);

    doTest(sslSocket);
    System.out.println("Completed test1");
  }
  public static void main(String args[]) {

    int port = 6502;
    SSLServerSocket server;

    try {
      // get the keystore into memory
      KeyStore ks = KeyStore.getInstance("JKS");
      ks.load(new FileInputStream(keyStore), keyStorePass);

      // initialize the key manager factory with the keystore data
      KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
      kmf.init(ks, keyStorePass);

      // initialize the SSLContext engine
      // may throw NoSuchProvider or NoSuchAlgorithm exception
      // TLS - Transport Layer Security most generic

      SSLContext sslContext = SSLContext.getInstance("TLS");

      // Inititialize context with given KeyManagers, TrustManagers,
      // SecureRandom defaults taken if null

      sslContext.init(kmf.getKeyManagers(), null, null);

      // Get ServerSocketFactory from the context object
      ServerSocketFactory ssf = sslContext.getServerSocketFactory();
      //  Now like programming with normal server sockets
      ServerSocket serverSocket = ssf.createServerSocket(port);

      System.out.println("Accepting secure connections");

      Socket client = serverSocket.accept();
      System.out.println("Got connection");

      BufferedWriter out = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
      BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
      String username = in.readLine();
      String password = in.readLine();

      if (username.equals("Josh") && password.equals("GoBucs")) {
        out.write("Greeting Client");
      } else {
        out.write("Sorry, you are not authorized");
      }
      out.flush();
      in.close();
      out.close();
    } catch (Exception e) {
      System.out.println("Exception thrown " + e);
    }
  }
  static {
    try {
      KeyStore ks = KeyStore.getInstance("JKS");
      KeyStore ts = KeyStore.getInstance("JKS");

      char[] passphrase = "passphrase".toCharArray();

      ks.load(new FileInputStream(keyFilename), passphrase);
      ts.load(new FileInputStream(trustFilename), passphrase);

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

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

      SSLContext sslCtx = SSLContext.getInstance("TLS");
      sslCtx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
      sslc = sslCtx;
    } catch (Exception e) {
      loadException = e;
    }
  }
Beispiel #10
0
 private void createClientKeyStore() throws Exception {
   clientCertKeystore = KeyStore.getInstance(Configuration.getSSLClientKeyStoreType());
   String clientCertPath = Configuration.getSSLClientCertPath();
   FileInputStream fileInputStream = null;
   if (clientCertPath != null) {
     try {
       fileInputStream = new FileInputStream(clientCertPath);
     } catch (IOException ioe) {
       logger.error("\n----\nCertificate not found: " + clientCertPath + "\n----");
     }
   }
   String password = Configuration.getSSLClientCertPassword();
   char[] passphrase = password == null ? null : password.toCharArray();
   clientCertKeystore.load(fileInputStream, passphrase);
 }
Beispiel #11
0
  /*
   * If this is a secure server, we now setup the SSLContext we'll
   * use for creating the SSLEngines throughout the lifetime of
   * this process.
   */
  private void createSSLContext() throws Exception {

    char[] passphrase = "passphrase".toCharArray();

    KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(new FileInputStream("testkeys"), passphrase);

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

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

    sslContext = SSLContext.getInstance("TLS");
    sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
  }
Beispiel #12
0
 private static void loadKeyStore(File keyStoreFile) {
   try {
     FileInputStream fileInputStream = null;
     try {
       fileInputStream = new FileInputStream(KEY_STORE_FILENAME);
       logger.trace("Loading key store from file [" + keyStoreFile + "]");
       keystore = KeyStore.getInstance(KeyStore.getDefaultType());
       keystore.load(fileInputStream, KEY_STORE_PASSWORD.toCharArray());
     } finally {
       if (fileInputStream != null) {
         fileInputStream.close();
       }
     }
   } catch (Exception e) {
     throw new RuntimeException(
         "Exception while loading KeyStore from " + keyStoreFile.getAbsolutePath(), e);
   }
 }
Beispiel #13
0
  /**
   * Initialisation if a supplied key is defined in the properties. This supplied key must be in a
   * keystore which can be generated using the keystoreGenerator file in demos. The keystore must be
   * on the classpath to find it.
   *
   * @throws KeyStoreException
   * @throws Exception
   * @throws IOException
   * @throws NoSuchAlgorithmException
   * @throws CertificateException
   * @throws UnrecoverableKeyException
   */
  private void initConfiguredKey() throws Exception {
    InputStream inputStream = null;
    // must not use default keystore type - as does not support secret keys
    KeyStore store = KeyStore.getInstance("JCEKS");

    SecretKey tempKey = null;
    try {
      // load in keystore using this thread's classloader
      inputStream =
          Thread.currentThread().getContextClassLoader().getResourceAsStream(keyStoreName);
      if (inputStream == null) inputStream = new FileInputStream(keyStoreName);
      // we can't find a keystore here -
      if (inputStream == null) {
        throw new Exception(
            "Unable to load keystore " + keyStoreName + " ensure file is on classpath");
      }
      // we have located a file lets load the keystore
      try {
        store.load(inputStream, storePassword.toCharArray());
        // loaded keystore - get the key
        tempKey = (SecretKey) store.getKey(alias, keyPassword.toCharArray());
      } catch (IOException e) {
        throw new Exception("Unable to load keystore " + keyStoreName + ": " + e);
      } catch (NoSuchAlgorithmException e) {
        throw new Exception("No Such algorithm " + keyStoreName + ": " + e);
      } catch (CertificateException e) {
        throw new Exception("Certificate exception " + keyStoreName + ": " + e);
      }

      if (tempKey == null)
        throw new Exception("Unable to retrieve key '" + alias + "' from keystore " + keyStoreName);
      // set the key here
      setSecretKey(tempKey);

      if (symAlgorithm.equals(DEFAULT_SYM_ALGO)) symAlgorithm = tempKey.getAlgorithm();

      // set the fact we are using a supplied key
      suppliedKey = true;
      queue_down = queue_up = false;
    } finally {
      Util.close(inputStream);
    }
  }
Beispiel #14
0
  private void initialize() throws Exception {
    String trustFilename =
        System.getProperty("test.src", "./") + "/" + pathToStores + "/" + trustStoreFile;
    char[] passphrase = "passphrase".toCharArray();

    KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(new FileInputStream(trustFilename), passphrase);

    for (Enumeration e = ks.aliases(); e.hasMoreElements(); ) {
      String alias = (String) e.nextElement();
      if (ks.isCertificateEntry(alias)) {
        certChain[0] = (X509Certificate) ks.getCertificate(alias);
        break;
      }
    }

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

    trustManager = (X509TrustManager) (tmf.getTrustManagers())[0];
  }
 public boolean load(String storeName, String storeType, String passwd) throws DigiDocException {
   FileInputStream fis = null;
   try {
     if (m_logger.isDebugEnabled())
       m_logger.debug("Load store: " + storeName + " type: " + storeType);
     m_keyStore = KeyStore.getInstance(storeType);
     if (m_keyStore != null) {
       m_keyStore.load(fis = new FileInputStream(storeName), passwd.toCharArray());
       return true;
     }
   } catch (Exception ex) {
     m_logger.error("Error loading store: " + storeName + " - " + ex);
   } finally {
     if (fis != null) {
       try {
         fis.close();
         fis = null;
       } catch (Exception ex2) {
         m_logger.error("Error closing pkcs12: " + storeName + " - " + ex2);
       }
     }
   }
   return false;
 }
Beispiel #16
0
  private KeyStore getKeyStore(JolokiaServerConfig pConfig)
      throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException,
          InvalidKeySpecException, InvalidKeyException, NoSuchProviderException,
          SignatureException {
    char[] password = pConfig.getKeystorePassword();
    String keystoreFile = pConfig.getKeystore();
    KeyStore keystore = KeyStore.getInstance(pConfig.getKeyStoreType());
    if (keystoreFile != null) {
      // Load everything from a keystore which must include CA (if useClientSslAuthenticatin is
      // used) and
      // server cert/key
      loadKeyStoreFromFile(keystore, keystoreFile, password);
    } else {
      // Load keys from PEM files
      keystore.load(null);
      updateKeyStoreFromPEM(keystore, pConfig);

      // If no server cert is configured, then use a self-signed server certificate
      if (pConfig.getServerCert() == null) {
        KeyStoreUtil.updateWithSelfSignedServerCertificate(keystore);
      }
    }
    return keystore;
  }
Beispiel #17
0
 private KeyStore createKeyStore()
     throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException {
   KeyStore keystore = KeyStore.getInstance("JKS");
   keystore.load(null);
   return keystore;
 }
 KeyStore loadKeyStore(String type, File file, String passwd) throws Exception {
   KeyStore ks = KeyStore.getInstance(type);
   FileInputStream fis = new FileInputStream(file);
   ks.load(fis, passwd.toCharArray());
   return ks;
 }
Beispiel #19
0
  /**
   * Create KeyStore and add a self-signed X.509 Certificate
   *
   * @param dname the X.509 Distinguished Name, eg "CN=www.google.co.uk, O=\"Google Inc\",
   *     L=\"Mountain View\", S=California, C=US"
   * @param keyAlgorithmName the key algorithm, eg "RSA"
   */
  private static KeyStore generateCertificate(
      String alias,
      char[] keyStorePassword,
      KeyAlgorithmName keyAlgorithmName,
      String dname,
      String... sanDomains)
      throws GeneralSecurityException, IOException {

    CertAndKeyGen certAndKeyGen =
        new CertAndKeyGen(
            keyAlgorithmName.name(), keyAlgorithmName.signatureAlgorithmName, "SunCertificates");
    certAndKeyGen.generate(keyAlgorithmName.keySize);

    PrivateKey privateKey = certAndKeyGen.getPrivateKey();
    X509CertInfo info = new X509CertInfo();
    Date from = new Date();
    Date to = new Date(from.getTime() + TimeUnit.DAYS.toMillis(360));
    CertificateValidity interval = new CertificateValidity(from, to);
    BigInteger sn = new BigInteger(64, new SecureRandom());
    X500Name owner = new X500Name(dname);

    info.set(X509CertInfo.VALIDITY, interval);
    info.set(X509CertInfo.SERIAL_NUMBER, new CertificateSerialNumber(sn));
    info.set(X509CertInfo.SUBJECT, new CertificateSubjectName(owner));
    info.set(X509CertInfo.ISSUER, new CertificateIssuerName(owner));
    info.set(X509CertInfo.KEY, new CertificateX509Key(certAndKeyGen.getPublicKey()));
    info.set(X509CertInfo.VERSION, new CertificateVersion(CertificateVersion.V3));
    info.set(
        X509CertInfo.ALGORITHM_ID,
        new CertificateAlgorithmId(new AlgorithmId(AlgorithmId.md5WithRSAEncryption_oid)));

    // add subject alternative names
    GeneralNames generalNames = new GeneralNames();
    for (String sanDomain : sanDomains) {
      generalNames.add(new GeneralName(new DNSName(sanDomain)));
    }
    if (generalNames.size() > 0) {
      CertificateExtensions certificateExtensions =
          (CertificateExtensions) info.get(X509CertInfo.EXTENSIONS);
      if (certificateExtensions == null) certificateExtensions = new CertificateExtensions();
      certificateExtensions.set(
          SubjectAlternativeNameExtension.NAME, new SubjectAlternativeNameExtension(generalNames));
      info.set(X509CertInfo.EXTENSIONS, certificateExtensions);
    }

    // Sign the certificate to identify the algorithm that's used.
    X509CertImpl x509Certificate = new X509CertImpl(info);
    x509Certificate.sign(privateKey, keyAlgorithmName.signatureAlgorithmName);

    // update the algorithm, and resign.
    info.set(
        CertificateAlgorithmId.NAME + "." + CertificateAlgorithmId.ALGORITHM,
        x509Certificate.get(X509CertImpl.SIG_ALG));
    x509Certificate = new X509CertImpl(info);
    x509Certificate.sign(privateKey, keyAlgorithmName.signatureAlgorithmName);

    // add to new key store
    KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    keyStore.load(null, keyStorePassword);
    keyStore.setKeyEntry(
        alias, privateKey, keyStorePassword, new X509Certificate[] {x509Certificate});

    return keyStore;
  }
  /*
   * Define the server side of the test.
   *
   * If the server prematurely exits, serverReady will be set to true
   * to avoid infinite hangs.
   */
  void doServerSide() throws Exception {
    KeyStore ks = KeyStore.getInstance("JKS");
    com.sun.net.ssl.SSLContext ctx = com.sun.net.ssl.SSLContext.getInstance("TLS");
    com.sun.net.ssl.KeyManagerFactory kmf =
        com.sun.net.ssl.KeyManagerFactory.getInstance("SunX509");

    ks.load(new FileInputStream(keyFilename), cpasswd);
    kmf.init(ks, cpasswd);

    com.sun.net.ssl.TrustManager[] tms =
        new com.sun.net.ssl.TrustManager[] {new MyComX509TrustManager()};

    ctx.init(kmf.getKeyManagers(), tms, null);

    SSLServerSocketFactory sslssf = (SSLServerSocketFactory) ctx.getServerSocketFactory();

    SSLServerSocket sslServerSocket = (SSLServerSocket) sslssf.createServerSocket(serverPort);
    serverPort = sslServerSocket.getLocalPort();

    sslServerSocket.setNeedClientAuth(true);

    /*
     * Create using the other type.
     */
    SSLContext ctx1 = SSLContext.getInstance("TLS");
    KeyManagerFactory kmf1 = KeyManagerFactory.getInstance("SunX509");

    TrustManager[] tms1 = new TrustManager[] {new MyJavaxX509TrustManager()};

    kmf1.init(ks, cpasswd);

    ctx1.init(kmf1.getKeyManagers(), tms1, null);

    sslssf = (SSLServerSocketFactory) ctx1.getServerSocketFactory();

    SSLServerSocket sslServerSocket1 = (SSLServerSocket) sslssf.createServerSocket(serverPort1);
    serverPort1 = sslServerSocket1.getLocalPort();
    sslServerSocket1.setNeedClientAuth(true);

    /*
     * Signal Client, we're ready for his connect.
     */
    serverReady = true;

    SSLSocket sslSocket = (SSLSocket) sslServerSocket.accept();
    sslServerSocket.close();
    serverReady = false;

    InputStream sslIS = sslSocket.getInputStream();
    OutputStream sslOS = sslSocket.getOutputStream();

    sslIS.read();
    sslOS.write(85);
    sslOS.flush();
    sslSocket.close();

    sslSocket = (SSLSocket) sslServerSocket1.accept();
    sslIS = sslSocket.getInputStream();
    sslOS = sslSocket.getOutputStream();

    sslIS.read();
    sslOS.write(85);
    sslOS.flush();
    sslSocket.close();

    System.out.println("Server exiting!");
    System.out.flush();
  }
Beispiel #21
0
  public static synchronized void setGlobalSSLAuth(
      String keypath, String keypassword, String trustpath, String trustpassword) {
    // load the stores if defined
    try {
      if (trustpath != null && trustpassword != null) {
        truststore = KeyStore.getInstance(KeyStore.getDefaultType());
        try (FileInputStream instream = new FileInputStream(new File(trustpath))) {
          truststore.load(instream, trustpassword.toCharArray());
        }
      } else truststore = null;
      if (keypath != null && keypassword != null) {
        keystore = KeyStore.getInstance(KeyStore.getDefaultType());
        try (FileInputStream instream = new FileInputStream(new File(keypath))) {
          keystore.load(instream, keypassword.toCharArray());
        }
      } else keystore = null;
    } catch (IOException | NoSuchAlgorithmException | CertificateException | KeyStoreException ex) {
      log.error("Illegal -D keystore parameters: " + ex.getMessage());
      truststore = null;
      keystore = null;
    }
    try {
      // set up the context
      SSLContext scxt = null;
      if (IGNORECERTS) {
        scxt = SSLContext.getInstance("TLS");
        TrustManager[] trust_mgr =
            new TrustManager[] {
              new X509TrustManager() {
                public X509Certificate[] getAcceptedIssuers() {
                  return null;
                }

                public void checkClientTrusted(X509Certificate[] certs, String t) {}

                public void checkServerTrusted(X509Certificate[] certs, String t) {}
              }
            };
        scxt.init(
            null, // key manager
            trust_mgr, // trust manager
            new SecureRandom()); // random number generator
      } else {
        SSLContextBuilder sslbuilder = SSLContexts.custom();
        TrustStrategy strat = new LooseTrustStrategy();
        if (truststore != null) sslbuilder.loadTrustMaterial(truststore, strat);
        else sslbuilder.loadTrustMaterial(strat);
        sslbuilder.loadTrustMaterial(truststore, new LooseTrustStrategy());
        if (keystore != null) sslbuilder.loadKeyMaterial(keystore, keypassword.toCharArray());
        scxt = sslbuilder.build();
      }
      globalsslfactory = new SSLConnectionSocketFactory(scxt, new NoopHostnameVerifier());

      RegistryBuilder rb = RegistryBuilder.<ConnectionSocketFactory>create();
      rb.register("https", globalsslfactory);
      sslregistry = rb.build();
    } catch (KeyStoreException
        | NoSuchAlgorithmException
        | KeyManagementException
        | UnrecoverableEntryException e) {
      log.error("Failed to set key/trust store(s): " + e.getMessage());
      sslregistry = null;
      globalsslfactory = null;
    }
  }
Beispiel #22
0
  public void signJar(Jar jar) {
    if (digestNames == null || digestNames.length == 0)
      error("Need at least one digest algorithm name, none are specified");

    if (keystoreFile == null || !keystoreFile.getAbsoluteFile().exists()) {
      error("No such keystore file: " + keystoreFile);
      return;
    }

    if (alias == null) {
      error("Private key alias not set for signing");
      return;
    }

    MessageDigest digestAlgorithms[] = new MessageDigest[digestNames.length];

    getAlgorithms(digestNames, digestAlgorithms);

    try {
      Manifest manifest = jar.getManifest();
      manifest.getMainAttributes().putValue("Signed-By", "Bnd");

      // Create a new manifest that contains the
      // Name parts with the specified digests

      ByteArrayOutputStream o = new ByteArrayOutputStream();
      manifest.write(o);
      doManifest(jar, digestNames, digestAlgorithms, o);
      o.flush();
      byte newManifestBytes[] = o.toByteArray();
      jar.putResource("META-INF/MANIFEST.MF", new EmbeddedResource(newManifestBytes, 0));

      // Use the bytes from the new manifest to create
      // a signature file

      byte[] signatureFileBytes = doSignatureFile(digestNames, digestAlgorithms, newManifestBytes);
      jar.putResource("META-INF/BND.SF", new EmbeddedResource(signatureFileBytes, 0));

      // Now we must create an RSA signature
      // this requires the private key from the keystore

      KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());

      KeyStore.PrivateKeyEntry privateKeyEntry = null;

      java.io.FileInputStream keystoreInputStream = null;
      try {
        keystoreInputStream = new java.io.FileInputStream(keystoreFile);
        char[] pw = password == null ? new char[0] : password.toCharArray();

        keystore.load(keystoreInputStream, pw);
        keystoreInputStream.close();
        privateKeyEntry =
            (PrivateKeyEntry) keystore.getEntry(alias, new KeyStore.PasswordProtection(pw));
      } catch (Exception e) {
        error(
            "No able to load the private key from the give keystore("
                + keystoreFile.getAbsolutePath()
                + ") with alias "
                + alias
                + " : "
                + e);
        return;
      } finally {
        IO.close(keystoreInputStream);
      }
      PrivateKey privateKey = privateKeyEntry.getPrivateKey();

      Signature signature = Signature.getInstance("MD5withRSA");
      signature.initSign(privateKey);

      signature.update(signatureFileBytes);

      signature.sign();

      // TODO, place the SF in a PCKS#7 structure ...
      // no standard class for this? The following
      // is an idea but we will to have do ASN.1 BER
      // encoding ...

      ByteArrayOutputStream tmpStream = new ByteArrayOutputStream();
      jar.putResource("META-INF/BND.RSA", new EmbeddedResource(tmpStream.toByteArray(), 0));
    } catch (Exception e) {
      error("During signing: " + e);
    }
  }