public void checkServerTrusted(X509Certificate[] chain, String authType)
      throws CertificateException {
    calledCheckServerTrusted = true;
    if (!authType.equals("RSA") && !authType.equals("DHE_RSA"))
      throw new CertificateException("Only RSA and DHE_RSA supported, not " + authType);

    if (chain.length != 3) throw new CertificateException("Need three certificates");

    X509Certificate cert0 = chain[0];
    X509Certificate cert1 = chain[1];
    X509Certificate cert2 = chain[2];
    int failedCert = 0;
    try {
      // NOTE: cert0 is a self-signed key used only for SSL
      failedCert = 0;
      cert0.verify(cert0.getPublicKey());
      // NOTE: cert1 is the SSL key signed by the server's Martus key
      failedCert = 1;
      cert1.verify(cert2.getPublicKey());
      // NOTE: cert2 is a self-signed key of and by the server's Martus key
      failedCert = 2;
      cert2.verify(cert2.getPublicKey());
      failedCert = -1;

      PublicKey tryPublicKey = expectedPublicKey;
      if (tryPublicKey == null) {
        if (expectedPublicCode == null) throw new CertificateException("No key or code is trusted");
        String certPublicKeyString = SimpleX509TrustManager.getKeyString(cert2.getPublicKey());
        String certPublicCode = MartusCrypto.computePublicCode(certPublicKeyString);
        if (expectedPublicCode.equals(certPublicCode)) {
          tryPublicKey = cert2.getPublicKey();
        }
      }

      if (tryPublicKey == null) throw new CertificateException("Key is not trusted");
      cert1.verify(tryPublicKey);
      String keyString = SimpleX509TrustManager.getKeyString(tryPublicKey);
      setExpectedPublicKey(keyString);
    } catch (SignatureException e) {
      MartusLogger.logException(e);
      MartusLogger.log("Failed cert: " + failedCert);
      String key0 = SimpleX509TrustManager.getKeyString(cert0.getPublicKey());
      String key1 = SimpleX509TrustManager.getKeyString(cert1.getPublicKey());
      String key2 = SimpleX509TrustManager.getKeyString(cert2.getPublicKey());
      MartusLogger.log("Cert0 public: " + key0);
      if (!key0.equals(key1)) MartusLogger.log("Cert1 public: " + key1);
      MartusLogger.log("Cert2 public: " + key2);
      MartusLogger.log("Cert2 public code: " + MartusCrypto.formatAccountIdForLog(key2));
      String expectedKeyString = SimpleX509TrustManager.getKeyString(expectedPublicKey);
      MartusLogger.log(
          "Expected public code: " + MartusCrypto.formatAccountIdForLog(expectedKeyString));

      throw new CertificateException(e.toString());
    } catch (Exception e) {
      // Tests will cause this to fire
      MartusLogger.logException(e);
      throw new CertificateException(e.toString());
    }
  }
 public String getExpectedPublicKey() {
   return SimpleX509TrustManager.getKeyString(expectedPublicKey);
 }