square / keywhiz

A system for distributing and managing secrets
https://square.github.io/keywhiz/
Apache License 2.0
2.62k stars 216 forks source link

How to implement using java api #100

Closed hshyamh4 closed 9 years ago

hshyamh4 commented 9 years ago

Sir, I can use curl command to retrieve my secrets using below command, curl --cert client.pem -k --trace trace.out -H "Content-Type:application/json" https://localhost:4444/automation/secrets/1

But i want to achieve this in java ,

import java.io.DataOutputStream; import java.io.IOException; import java.net.URL; import java.security.KeyManagementException; import java.security.NoSuchAlgorithmException; import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSession; import javax.net.ssl.TrustManager; import javax.net.ssl.X509TrustManager;

TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }

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

        public void checkServerTrusted(X509Certificate[] certs,
                String authType) {
        }

    } };

    SSLContext sc = SSLContext.getInstance("SSL");
    sc.init(null, trustAllCerts, null);
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

    // Create all-trusting host name verifier
    HostnameVerifier allHostsValid = new HostnameVerifier() {
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    };
    // Install the all-trusting host verifier
    HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
//    Response r = given().contentType("application/json").when()
//          .post("https://localhost:4444/automation/secrets/1");
//  System.out.println(r.getBody().toString());

    URL url = new URL("https://localhost:4444/automation/secrets/1");
    HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
    con.setRequestMethod("GET");
  //  con.setRequestProperty("User-Agent", USER_AGENT);
  //  con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
  //  con.setRequestProperty("Authorization", "Basic " + authStringEnc);
    con.setRequestProperty("Content-Type", "application/json");

    String urlParameters = "";

    // Send post request
    con.setDoOutput(true);
    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    wr.writeBytes(urlParameters);
    wr.flush();
    wr.close();

    int responseCode = con.getResponseCode();
    System.out.println("\nSending 'POST' request to URL : " + responseCode);
sul3n3t commented 9 years ago

Try using the keywhiz-client module.