package nl.xservices.plugins;

import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONException;

import javax.net.ssl.HttpsURLConnection;
import javax.security.cert.CertificateException;
import java.io.IOException;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.cert.Certificate;
import java.security.cert.CertificateEncodingException;

public class SSLCertificateChecker extends CordovaPlugin {

  private static final String ACTION_CHECK_EVENT = "check";
  private static char[] HEX_CHARS = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};

  @Override
  public boolean execute(final String action, final JSONArray args, final CallbackContext callbackContext) throws JSONException {
    if (ACTION_CHECK_EVENT.equals(action)) {
      cordova.getThreadPool().execute(new Runnable() {
        public void run() {
          try {
            final String serverURL = args.getString(0);
            final String allowedFingerprint = args.getString(1);
            final String allowedFingerprintAlt = args.getString(2);
            final String serverCertFingerprint = getFingerprint(serverURL);

            if (allowedFingerprint.equalsIgnoreCase(serverCertFingerprint) || allowedFingerprintAlt.equalsIgnoreCase(serverCertFingerprint)) {
              callbackContext.success("CONNECTION_SECURE");
            } else {
              callbackContext.error("CONNECTION_NOT_SECURE");
            }
          } catch (Exception e) {
            callbackContext.error("CONNECTION_FAILED. Details: " + e.getMessage());
          }
        }
      });
      return true;
    } else {
      callbackContext.error("sslCertificateChecker." + action + " is not a supported function. Did you mean '" + ACTION_CHECK_EVENT + "'?");
      return false;
    }
  }

  private static String getFingerprint(String httpsURL) throws IOException, NoSuchAlgorithmException, CertificateException, CertificateEncodingException {
    final HttpsURLConnection con = (HttpsURLConnection) new URL(httpsURL).openConnection();
    con.connect();
    final Certificate cert = con.getServerCertificates()[0];
    final MessageDigest md = MessageDigest.getInstance("SHA1");
    md.update(cert.getEncoded());
    return dumpHex(md.digest());
  }

  private static String dumpHex(byte[] data) {
    final int n = data.length;
    final StringBuilder sb = new StringBuilder(n * 3 - 1);
    for (int i = 0; i < n; i++) {
      if (i > 0) {
        sb.append(' ');
      }
      sb.append(HEX_CHARS[(data[i] >> 4) & 0x0F]);
      sb.append(HEX_CHARS[data[i] & 0x0F]);
    }
    return sb.toString();
  }
}

@@ -1066,16 +1066,81 @@
 ing(0);%0A
+            final Boolean checkInCertChain = args.getBoolean(1);%0A
         
@@ -1192,17 +1192,17 @@
 tString(
-1
+2
 );%0A     
@@ -1252,33 +1252,33 @@
  args.getString(
-2
+3
 );%0A            f
@@ -1272,36 +1272,32 @@
             
-final 
 String
+%5B%5D
  serverCertF
@@ -1306,16 +1306,17 @@
 gerprint
+s
  = getFi
@@ -1324,16 +1324,17 @@
 gerprint
+s
 (serverU
@@ -1338,17 +1338,217 @@
 erURL);%0A
-%0A
+            %0A            Boolean certFound = false;%0A            int certChainCheckDepth = checkInCertChain ? serverCertFingerprints.length : 1;%0A            for (int i=0; i%3CcertChainCheckDepth; i++) %7B%0A%09
         
@@ -1612,16 +1612,20 @@
 gerprint
+s%5Bi%5D
 ) %7C%7C all
@@ -1681,21 +1681,29 @@
 gerprint
+s%5Bi%5D
 )) %7B%0A
+%09   
         
@@ -1695,37 +1695,65 @@
  %7B%0A%09            
-     
+%09certFound = true;%0A%09            %09
 callbackContext.
@@ -1786,26 +1786,86 @@
 %22);%0A
-            %7D else
+%09            %09break;%0A%09            %7D%0A            %7D%0A            if (! certFound)
  %7B%0A 
@@ -1867,34 +1867,33 @@
 ) %7B%0A            
-  
+%09
 callbackContext.
@@ -2315,16 +2315,18 @@
 c String
+%5B%5D
  getFing
@@ -2332,16 +2332,17 @@
 gerprint
+s
 (String 
@@ -2582,21 +2582,24 @@
 tificate
+%5B%5D
  cert
+s
  = con.g
@@ -2624,10 +2624,67 @@
 es()
-%5B0
+;%0A    final String%5B%5D fingerprints = new String%5Bcerts.length
 %5D;%0A 
@@ -2742,24 +2742,69 @@
 ce(%22SHA1%22);%0A
+    for (int i=0; i%3Ccerts.length; i++) %7B%0A    
     md.updat
@@ -2809,16 +2809,20 @@
 ate(cert
+s%5Bi%5D
 .getEnco
@@ -2833,23 +2833,36 @@
 ));%0A    
+ 
-return 
+   fingerprints%5Bi%5D=
 dumpHex(
@@ -2875,16 +2875,47 @@
 est());%0A
+    %7D%0A    return fingerprints;%0A
   %7D%0A%0A  p

Update to check fingerprint in certificate chain