Monday, July 4, 2011

JSON and SSL in groovy, how to ignore certificates

In the last couple of days I became more and more interested in bitmining and the first thing I noticed was the utter lack of integrated tools and hence statistics I would like to associated with my miners.

This resulted in me creating a tiny grails application to synchronzie my deepbit statistics with the current market data from mtgox to calculate at which point it becomes pointless to mine these thing. I basically hope that this pays for the 700$ for my 2x6950 radeons and associated cooling the 100+F heat we have here in California.

Now originally you could assume that this is rather straightforward. After all you got json data, which just need to be parsed.


Map jsonArray = JSON.parse(new InputStreamReader(new URL("https://mtgox.com/code/data/ticker.php").openStream()))

println jsonArray



but sadly the java ssl security manager does not agree here with us and tosses a fit..



javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at com.sun.net.ssl.internal.ssl.Alerts.getSSLException(Alerts.java:174)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1649)



Now java is kinda smart, if want's to force you install a security certificate from the server you access and authorize yourself. But sometimes you don't want this. In this case it's overkill, since we are having a readonly transaction.

So what has to be done?

you need to create your own security manager implementation. Which basically is a 3 step procedure


  1. implement an interface


    class TrustManager implements X509TrustManager {

    public java.security.cert.X509Certificate[] getAcceptedIssuers() {
    return null;
    }

    public void checkClientTrusted(
    java.security.cert.X509Certificate[] certs, String authType) {
    }

    public void checkServerTrusted(
    java.security.cert.X509Certificate[] certs, String authType) {
    }

    }




  2. register the interface and update the context configuration

    TrustManager[] trustAllCerts = new TrustManager[1]

    trustAllCerts[0] = new TrustManager()
    try {
    SSLContext sc = SSLContext.getInstance("SSL");
    sc.init(null, trustAllCerts, new java.security.SecureRandom());
    HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    } catch (Exception e) {
    }

  3. and continue like always with your json script

    Map jsonArray = JSON.parse(new InputStreamReader(new URL("https://mtgox.com/code/data/ticker.php").openStream()))


and the result should be now the current ticker for the USD to BitCoin exchange rate.


    {"ticker":{"high":15.4989,"low":13.31415,"avg":14.726503862,"vol":42862,"last":13.31415,"buy":13.331,"sell":13.35999}}



    1 comment: