public DEPExportFormat exportDEP() {
    try {
      // prepare data structures for DEP export
      // DEP exports are grouped according to the used signature certificate (CURRENTLY NOT USED IN
      // THE DEMO)
      HashMap<String, List<ReceiptPackage>> certificateToReceiptMap = new HashMap<>();

      for (ReceiptPackage receiptPackage : receiptPackages) {
        X509Certificate signingCertificate = receiptPackage.getSigningCertificate();
        List<ReceiptPackage> receiptPackagesForSignatureCertificate =
            certificateToReceiptMap.get(signingCertificate.getSerialNumber() + "");
        if (receiptPackagesForSignatureCertificate == null) {
          receiptPackagesForSignatureCertificate = new ArrayList<>();
          certificateToReceiptMap.put(
              signingCertificate.getSerialNumber() + "", receiptPackagesForSignatureCertificate);
        }
        receiptPackagesForSignatureCertificate.add(receiptPackage);
      }

      // create data structure for export format
      DEPExportFormat depExportFormat = new DEPExportFormat();
      DEPBelegDump[] belegDump = new DEPBelegDump[certificateToReceiptMap.keySet().size()];

      // store receipts in export format
      int dumpIndex = 0;
      for (List<ReceiptPackage> signedReceipts : certificateToReceiptMap.values()) {
        belegDump[dumpIndex] = new DEPBelegDump();
        depExportFormat.setBelegPackage(belegDump);

        List<String> receiptsInJWSCompactRepresentation = new ArrayList<>();
        for (ReceiptPackage receiptPackage : signedReceipts) {
          receiptsInJWSCompactRepresentation.add(receiptPackage.getJwsCompactRepresentation());
        }
        belegDump[dumpIndex].setBelegeDaten(
            receiptsInJWSCompactRepresentation.toArray(
                new String[receiptsInJWSCompactRepresentation.size()]));

        String base64EncodedSignatureCertificate =
            CashBoxUtils.base64Encode(
                signedReceipts.get(0).getSigningCertificate().getEncoded(), false);
        belegDump[dumpIndex].setSignatureCertificate(base64EncodedSignatureCertificate);

        List<X509Certificate> base64EncodedCertificateChain =
            signedReceipts.get(0).getCertificateChain();
        String[] certificateChain = new String[base64EncodedCertificateChain.size()];
        for (int i = 0; i < base64EncodedCertificateChain.size(); i++) {
          X509Certificate base64EncodedChainCertificate = base64EncodedCertificateChain.get(i);
          certificateChain[i] =
              CashBoxUtils.base64Encode(base64EncodedChainCertificate.getEncoded(), false);
        }
        belegDump[dumpIndex].setCertificateChain(certificateChain);

        dumpIndex++;
      }
      return depExportFormat;
    } catch (CertificateEncodingException e) {
      e.printStackTrace();
    }
    return null;
  }
 private static String certHash(final X509Certificate cert, String digest) {
   try {
     MessageDigest md = MessageDigest.getInstance(digest);
     md.update(cert.getEncoded());
     return hexString(md.digest());
   } catch (java.security.cert.CertificateEncodingException e) {
     return e.getMessage();
   } catch (java.security.NoSuchAlgorithmException e) {
     return e.getMessage();
   }
 }
Example #3
0
 public void testGetVersion() {
   try {
     System.out.println(
         "* "
             + new ftPublicFunc()
                 .ftBytesToHexString(cers.getX509Certificate().getTBSCertificate()));
   } catch (CertificateEncodingException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
   }
   System.out.println("Version:" + cers.getVersion());
 }
 protected void encodePayload() throws IOException {
   ByteArrayOutputStream bout = new ByteArrayOutputStream(1024);
   byte[] enc = null;
   try {
     for (int i = 0; i < path.length; i++) {
       bout.write(path[i].getEncoded());
     }
   } catch (CertificateEncodingException cee) {
     throw new IOException(cee.toString());
   }
   payload = bout.toByteArray();
 }
 private static void appendThumbPrint(X509Certificate cert, String hash, StringBuilder sb) {
   try {
     MessageDigest md = MessageDigest.getInstance(hash);
     byte[] der = cert.getEncoded();
     md.update(der);
     byte[] digest = md.digest();
     char[] encode = Hex.encode(digest);
     appendHexSpace(encode, sb);
   } catch (NoSuchAlgorithmException e) {
     sb.append("Error calculating thumbprint: " + e.getMessage());
   } catch (CertificateEncodingException e) {
     sb.append("Error calculating thumbprint: " + e.getMessage());
   }
 }
Example #6
0
 private void writeCertList(BufferedSink sink, List<Certificate> certificates)
     throws IOException {
   try {
     sink.writeDecimalLong(certificates.size());
     sink.writeByte('\n');
     for (int i = 0, size = certificates.size(); i < size; i++) {
       byte[] bytes = certificates.get(i).getEncoded();
       String line = ByteString.of(bytes).base64();
       sink.writeUtf8(line);
       sink.writeByte('\n');
     }
   } catch (CertificateEncodingException e) {
     throw new IOException(e.getMessage());
   }
 }
  @Override
  protected RequestResult doInBackground(final Void... params) {

    this.t = null;
    RequestResult result = null;
    try {
      result = TriSigner.sign(this.signRequest, this.pk, this.certificateChain, this.comm);
    } catch (final CertificateEncodingException e) {
      Log.e(SFConstants.LOG_TAG, "Error al codificar el certificado de firma: " + e); // $NON-NLS-1$
      this.t = e;
      e.printStackTrace();
    } catch (final IOException e) {
      Log.e(SFConstants.LOG_TAG, "Error en la comunicacion con el servidor: " + e); // $NON-NLS-1$
      this.t = e;
      e.printStackTrace();
    } catch (final SAXException e) {
      Log.e(
          SFConstants.LOG_TAG,
          "Error en las respuesta devuelta por el servicio de firma: " + e); // $NON-NLS-1$
      this.t = e;
      e.printStackTrace();
    } catch (final Exception e) {

      e.printStackTrace();

      // Solo se dara este error (hasta la fecha) cuando se intente cargar el dialogo de PIN de
      // una tarjeta criptografica
      if (e.getCause() != null
          && e.getCause() instanceof AOException
          && e.getCause().getCause() instanceof ActivityNotFoundException) {
        Log.e(
            SFConstants.LOG_TAG,
            "Error al intentar cargar el dialogo de PIN de una tarjeta criptografica: "
                + e); //$NON-NLS-1$
        this.t = e;
      } else {
        Log.e(SFConstants.LOG_TAG, "Error durante la operacion de firma: " + e); // $NON-NLS-1$
        this.t = e;
      }
    } catch (final Throwable e) {
      Log.e(SFConstants.LOG_TAG, "Error grave durante la operacion de firma: " + e); // $NON-NLS-1$
      this.t = e;

      e.printStackTrace();
    }

    return result;
  }
 private void writeCertArray(Writer writer, Certificate[] certificates) throws IOException {
   if (certificates == null) {
     writer.write("-1\n");
     return;
   }
   try {
     writer.write(Integer.toString(certificates.length) + '\n');
     for (Certificate certificate : certificates) {
       byte[] bytes = certificate.getEncoded();
       String line = Base64.encodeToString(bytes, Base64.DEFAULT);
       writer.write(line + '\n');
     }
   } catch (CertificateEncodingException e) {
     throw new IOException(e.getMessage());
   }
 }
 private static void appendCertificate(X509Certificate x509Certificate, StringBuilder sb) {
   sb.append("-----BEGIN CERTIFICATE-----\n");
   try {
     String certificate = new String(Base64.encode(x509Certificate.getEncoded()));
     int i = 0;
     while (true) {
       int j = i + 76;
       if (j < certificate.length()) {
         sb.append(certificate.substring(i, j)).append("\n");
         i = j;
       } else {
         sb.append(certificate.substring(i)).append("\n");
         break;
       }
     }
   } catch (CertificateEncodingException e) {
     sb.append("Cannot encode: ").append(e.getMessage());
   }
   sb.append("-----END CERTIFICATE-----\n");
 }
  /**
   * @deprecated use addCertificates and addCRLs
   * @param certificates
   * @throws CertStoreException
   * @throws TSPException
   */
  public void setCertificatesAndCRLs(CertStore certificates)
      throws CertStoreException, TSPException {
    Collection c1 = certificates.getCertificates(null);

    for (Iterator it = c1.iterator(); it.hasNext(); ) {
      try {
        certs.add(new JcaX509CertificateHolder((X509Certificate) it.next()));
      } catch (CertificateEncodingException e) {
        throw new TSPException("cannot encode certificate: " + e.getMessage(), e);
      }
    }

    c1 = certificates.getCRLs(null);

    for (Iterator it = c1.iterator(); it.hasNext(); ) {
      try {
        crls.add(new JcaX509CRLHolder((X509CRL) it.next()));
      } catch (CRLException e) {
        throw new TSPException("cannot encode CRL: " + e.getMessage(), e);
      }
    }
  }
Example #11
0
 public static String getCertificateSHA1Fingerprint(Context mContext) {
   PackageManager pm = mContext.getPackageManager();
   String packageName = mContext.getPackageName();
   int flags = PackageManager.GET_SIGNATURES;
   PackageInfo packageInfo = null;
   try {
     packageInfo = pm.getPackageInfo(packageName, flags);
   } catch (PackageManager.NameNotFoundException e) {
     e.printStackTrace();
   }
   Signature[] signatures = packageInfo.signatures;
   byte[] cert = signatures[0].toByteArray();
   InputStream input = new ByteArrayInputStream(cert);
   CertificateFactory cf = null;
   try {
     cf = CertificateFactory.getInstance("X509");
   } catch (CertificateException e) {
     e.printStackTrace();
   }
   X509Certificate c = null;
   try {
     c = (X509Certificate) cf.generateCertificate(input);
   } catch (CertificateException e) {
     e.printStackTrace();
   }
   String hexString = null;
   try {
     MessageDigest md = MessageDigest.getInstance("SHA1");
     byte[] publicKey = md.digest(c.getEncoded());
     hexString = byte2HexFormatted(publicKey);
   } catch (NoSuchAlgorithmException e1) {
     e1.printStackTrace();
   } catch (CertificateEncodingException e) {
     e.printStackTrace();
   }
   return hexString;
 }
Example #12
0
 /*     */ private void writeObject(ObjectOutputStream paramObjectOutputStream)
     /*     */ throws IOException
       /*     */ {
   /* 524 */ paramObjectOutputStream.defaultWriteObject();
   /*     */
   /* 526 */ if ((this.certs == null) || (this.certs.length == 0)) {
     /* 527 */ paramObjectOutputStream.writeInt(0);
     /*     */ }
   /*     */ else {
     /* 530 */ paramObjectOutputStream.writeInt(this.certs.length);
     /*     */
     /* 532 */ for (int i = 0; i < this.certs.length; i++) {
       /* 533 */ Certificate localCertificate = this.certs[i];
       /*     */ try {
         /* 535 */ paramObjectOutputStream.writeUTF(localCertificate.getType());
         /* 536 */ byte[] arrayOfByte = localCertificate.getEncoded();
         /* 537 */ paramObjectOutputStream.writeInt(arrayOfByte.length);
         /* 538 */ paramObjectOutputStream.write(arrayOfByte);
         /*     */ } catch (CertificateEncodingException localCertificateEncodingException) {
         /* 540 */ throw new IOException(localCertificateEncodingException.getMessage());
         /*     */ }
       /*     */ }
     /*     */ }
   /*     */ }
Example #13
0
  public void writeObject(Object var1) throws IOException {
    String var2;
    byte[] var3;
    byte[] var4;
    if (var1 instanceof X509Certificate) {
      var2 = "CERTIFICATE";

      try {
        var3 = ((X509Certificate) var1).getEncoded();
      } catch (CertificateEncodingException var32) {
        StringBuilder var6 = (new StringBuilder()).append("Cannot encode object: ");
        String var7 = var32.toString();
        String var8 = var6.append(var7).toString();
        throw new IOException(var8);
      }

      var4 = var3;
    } else if (var1 instanceof X509CRL) {
      var2 = "X509 CRL";

      try {
        var3 = ((X509CRL) var1).getEncoded();
      } catch (CRLException var31) {
        StringBuilder var10 = (new StringBuilder()).append("Cannot encode object: ");
        String var11 = var31.toString();
        String var12 = var10.append(var11).toString();
        throw new IOException(var12);
      }

      var4 = var3;
    } else {
      if (var1 instanceof KeyPair) {
        PrivateKey var13 = ((KeyPair) var1).getPrivate();
        this.writeObject(var13);
        return;
      }

      if (var1 instanceof PrivateKey) {
        ASN1Sequence var14 = (ASN1Sequence) ASN1Object.fromByteArray(((Key) var1).getEncoded());
        PrivateKeyInfo var15 = new PrivateKeyInfo(var14);
        if (var1 instanceof RSAPrivateKey) {
          var2 = "RSA PRIVATE KEY";
          var4 = var15.getPrivateKey().getEncoded();
        } else if (var1 instanceof DSAPrivateKey) {
          var2 = "DSA PRIVATE KEY";
          DSAParameter var16 = DSAParameter.getInstance(var15.getAlgorithmId().getParameters());
          ASN1EncodableVector var17 = new ASN1EncodableVector();
          DERInteger var18 = new DERInteger(0);
          var17.add(var18);
          BigInteger var19 = var16.getP();
          DERInteger var20 = new DERInteger(var19);
          var17.add(var20);
          BigInteger var21 = var16.getQ();
          DERInteger var22 = new DERInteger(var21);
          var17.add(var22);
          BigInteger var23 = var16.getG();
          DERInteger var24 = new DERInteger(var23);
          var17.add(var24);
          BigInteger var25 = ((DSAPrivateKey) var1).getX();
          BigInteger var26 = var16.getG();
          BigInteger var27 = var16.getP();
          BigInteger var28 = var26.modPow(var25, var27);
          DERInteger var29 = new DERInteger(var28);
          var17.add(var29);
          DERInteger var30 = new DERInteger(var25);
          var17.add(var30);
          var4 = (new DERSequence(var17)).getEncoded();
        } else {
          if (!((PrivateKey) var1).getAlgorithm().equals("ECDSA")) {
            throw new IOException("Cannot identify private key");
          }

          var2 = "EC PRIVATE KEY";
          var4 = var15.getPrivateKey().getEncoded();
        }
      } else if (var1 instanceof PublicKey) {
        var2 = "PUBLIC KEY";
        var4 = ((PublicKey) var1).getEncoded();
      } else if (var1 instanceof X509AttributeCertificate) {
        var2 = "ATTRIBUTE CERTIFICATE";
        var4 = ((X509V2AttributeCertificate) var1).getEncoded();
      } else if (var1 instanceof PKCS10CertificationRequest) {
        var2 = "CERTIFICATE REQUEST";
        var4 = ((PKCS10CertificationRequest) var1).getEncoded();
      } else {
        if (!(var1 instanceof ContentInfo)) {
          throw new IOException("unknown object passed - can\'t encode.");
        }

        var2 = "PKCS7";
        var4 = ((ContentInfo) var1).getEncoded();
      }
    }

    this.writeHeader(var2);
    this.writeEncoded(var4);
    this.writeFooter(var2);
  }
Example #14
0
  public static TokenSearchResults searchTokenEntries(
      final KeyStore keyStore,
      final int startIndex,
      final int max,
      final QueryCriteria qc,
      final boolean includeData)
      throws CryptoTokenOfflineException, QueryException {
    final TokenSearchResults result;
    try {
      final ArrayList<TokenEntry> tokenEntries = new ArrayList<TokenEntry>();
      final Enumeration<String> e =
          keyStore
              .aliases(); // We assume the order is the same for every call unless entries has been
                          // added or removed

      final long maxIndex = (long) startIndex + max;
      for (int i = 0; i < maxIndex && e.hasMoreElements(); ) {
        final String keyAlias = e.nextElement();

        final String type;
        if (keyStore.entryInstanceOf(keyAlias, KeyStore.PrivateKeyEntry.class)) {
          type = TokenEntry.TYPE_PRIVATEKEY_ENTRY;
        } else if (keyStore.entryInstanceOf(keyAlias, KeyStore.SecretKeyEntry.class)) {
          type = TokenEntry.TYPE_SECRETKEY_ENTRY;
        } else if (keyStore.entryInstanceOf(keyAlias, KeyStore.TrustedCertificateEntry.class)) {
          type = TokenEntry.TYPE_TRUSTED_ENTRY;
        } else {
          type = null;
        }

        TokenEntry entry = new TokenEntry(keyAlias, type);

        if (shouldBeIncluded(entry, qc)) {
          if (i < startIndex) {
            i++;
            continue;
          }

          if (LOG.isDebugEnabled()) {
            LOG.debug("checking keyAlias: " + keyAlias);
          }

          // Add additional data
          if (includeData) {
            Map<String, String> info = new HashMap<String, String>();
            try {
              Date creationDate = keyStore.getCreationDate(keyAlias);
              entry.setCreationDate(creationDate);
            } catch (ProviderException ex) {
            } // NOPMD: We ignore if it is not supported

            if (TokenEntry.TYPE_PRIVATEKEY_ENTRY.equals(type)) {
              final Certificate[] chain = keyStore.getCertificateChain(keyAlias);
              if (chain.length > 0) {
                info.put(
                    INFO_KEY_ALGORITHM, AlgorithmTools.getKeyAlgorithm(chain[0].getPublicKey()));
                info.put(
                    INFO_KEY_SPECIFICATION,
                    AlgorithmTools.getKeySpecification(chain[0].getPublicKey()));
              }
              try {
                entry.setParsedChain(chain);
              } catch (CertificateEncodingException ex) {
                info.put("Error", ex.getMessage());
                LOG.error("Certificate could not be encoded for alias: " + keyAlias, ex);
              }
            } else if (TokenEntry.TYPE_TRUSTED_ENTRY.equals(type)) {
              Certificate certificate = keyStore.getCertificate(keyAlias);
              try {
                entry.setParsedTrustedCertificate(certificate);
              } catch (CertificateEncodingException ex) {
                info.put("Error", ex.getMessage());
                LOG.error("Certificate could not be encoded for alias: " + keyAlias, ex);
              }
            } else if (TokenEntry.TYPE_SECRETKEY_ENTRY.equals(type)) {
              try {
                KeyStore.Entry entry1 = keyStore.getEntry(keyAlias, null);
                SecretKey secretKey = ((KeyStore.SecretKeyEntry) entry1).getSecretKey();

                info.put(INFO_KEY_ALGORITHM, secretKey.getAlgorithm());
                // info.put(INFO_KEY_SPECIFICATION,
                // AlgorithmTools.getKeySpecification(chain[0].getPublicKey())); // TODO: Key
                // specification support for secret keys
              } catch (NoSuchAlgorithmException ex) {
                info.put("Error", ex.getMessage());
                LOG.error("Unable to get secret key for alias: " + keyAlias, ex);
              } catch (UnrecoverableEntryException ex) {
                info.put("Error", ex.getMessage());
                LOG.error("Unable to get secret key for alias: " + keyAlias, ex);
              }
            }
            entry.setInfo(info);
          }
          tokenEntries.add(entry);

          // Increase index
          i++;
        }
      }
      result = new TokenSearchResults(tokenEntries, e.hasMoreElements());
    } catch (KeyStoreException ex) {
      throw new CryptoTokenOfflineException(ex);
    }
    return result;
  }
  private PemObject createPemObject(Object o) throws IOException {
    String type;
    byte[] encoding;

    if (o instanceof PemObject) {
      return (PemObject) o;
    }
    if (o instanceof PemObjectGenerator) {
      return ((PemObjectGenerator) o).generate();
    }
    if (o instanceof X509Certificate) {
      type = "CERTIFICATE";
      try {
        encoding = ((X509Certificate) o).getEncoded();
      } catch (CertificateEncodingException e) {
        throw new PemGenerationException("Cannot encode object: " + e.toString());
      }
    } else if (o instanceof X509CRL) {
      type = "X509 CRL";
      try {
        encoding = ((X509CRL) o).getEncoded();
      } catch (CRLException e) {
        throw new PemGenerationException("Cannot encode object: " + e.toString());
      }
    } else if (o instanceof KeyPair) {
      return createPemObject(((KeyPair) o).getPrivate());
    } else if (o instanceof PrivateKey) {
      PrivateKeyInfo info =
          new PrivateKeyInfo((ASN1Sequence) ASN1Primitive.fromByteArray(((Key) o).getEncoded()));

      if (o instanceof RSAPrivateKey) {
        type = "RSA PRIVATE KEY";

        encoding = info.parsePrivateKey().toASN1Primitive().getEncoded();
      } else if (o instanceof DSAPrivateKey) {
        type = "DSA PRIVATE KEY";

        DSAParameter p = DSAParameter.getInstance(info.getPrivateKeyAlgorithm().getParameters());
        ASN1EncodableVector v = new ASN1EncodableVector();

        v.add(new DERInteger(0));
        v.add(new DERInteger(p.getP()));
        v.add(new DERInteger(p.getQ()));
        v.add(new DERInteger(p.getG()));

        BigInteger x = ((DSAPrivateKey) o).getX();
        BigInteger y = p.getG().modPow(x, p.getP());

        v.add(new DERInteger(y));
        v.add(new DERInteger(x));

        encoding = new DERSequence(v).getEncoded();
      } else if (((PrivateKey) o).getAlgorithm().equals("ECDSA")) {
        type = "EC PRIVATE KEY";

        encoding = info.parsePrivateKey().toASN1Primitive().getEncoded();
      } else {
        throw new IOException("Cannot identify private key");
      }
    } else if (o instanceof PublicKey) {
      type = "PUBLIC KEY";

      encoding = ((PublicKey) o).getEncoded();
    } else if (o instanceof X509AttributeCertificate) {
      type = "ATTRIBUTE CERTIFICATE";
      encoding = ((X509V2AttributeCertificate) o).getEncoded();
    } else if (o instanceof PKCS10CertificationRequest) {
      type = "CERTIFICATE REQUEST";
      encoding = ((PKCS10CertificationRequest) o).getEncoded();
    } else if (o instanceof ContentInfo) {
      type = "PKCS7";
      encoding = ((ContentInfo) o).getEncoded();
    } else {
      throw new PemGenerationException("unknown object passed - can't encode.");
    }

    return new PemObject(type, encoding);
  }
Example #16
0
        @Override
        public void handleMessage(Message msg) {
          switch (msg.what) {
            case VncConstants.DIALOG_X509_CERT:
              final X509Certificate cert = (X509Certificate) msg.obj;

              if (connection.getSshHostKey().equals("")) {
                // Show a dialog with the key signature for approval.
                DialogInterface.OnClickListener signatureNo =
                    new DialogInterface.OnClickListener() {
                      @Override
                      public void onClick(DialogInterface dialog, int which) {
                        // We were told not to continue, so stop the activity
                        closeConnection();
                        ((Activity) getContext()).finish();
                      }
                    };
                DialogInterface.OnClickListener signatureYes =
                    new DialogInterface.OnClickListener() {
                      @Override
                      public void onClick(DialogInterface dialog, int which) {
                        // We were told to go ahead with the connection, so save the key into the
                        // database.
                        String certificate = null;
                        try {
                          certificate = Base64.encodeToString(cert.getEncoded(), Base64.DEFAULT);
                        } catch (CertificateEncodingException e) {
                          e.printStackTrace();
                          showFatalMessageAndQuit("Certificate encoding could not be generated.");
                        }
                        connection.setSshHostKey(certificate);
                        connection.save(database.getWritableDatabase());
                        database.close();
                        // Indicate the certificate was accepted.
                        certificateAccepted = true;
                      }
                    };

                // Generate a sha1 signature of the certificate.
                MessageDigest sha1;
                MessageDigest md5;
                try {
                  sha1 = MessageDigest.getInstance("SHA1");
                  md5 = MessageDigest.getInstance("MD5");
                  sha1.update(cert.getEncoded());
                  Utils.showYesNoPrompt(
                      getContext(),
                      "Continue connecting to " + connection.getAddress() + "?",
                      "The x509 certificate signatures are:"
                          + "\nSHA1:  "
                          + Utils.toHexString(sha1.digest())
                          + "\nMD5:  "
                          + Utils.toHexString(md5.digest())
                          + "\nYou can ensure they are identical to the known signatures of the server certificate to prevent a man-in-the-middle attack.",
                      signatureYes,
                      signatureNo);
                } catch (NoSuchAlgorithmException e2) {
                  e2.printStackTrace();
                  showFatalMessageAndQuit(
                      "Could not generate SHA1 or MD5 signature of certificate. No SHA1/MD5 algorithm found.");
                } catch (CertificateEncodingException e) {
                  e.printStackTrace();
                  showFatalMessageAndQuit("Certificate encoding could not be generated.");
                }
              } else {
                // Compare saved with obtained certificate and quit if they don't match.
                try {
                  if (!connection
                      .getSshHostKey()
                      .equals(Base64.encodeToString(cert.getEncoded(), Base64.DEFAULT))) {
                    showFatalMessageAndQuit(
                        "ERROR: The saved x509 certificate does not match the current server certificate! "
                            + "This could be a man-in-the-middle attack. If you are aware of the key change, delete and recreate the connection.");
                  } else {
                    // In case we need to display information about the certificate, we can
                    // reconstruct it like this:
                    // CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
                    // ByteArrayInputStream in = new
                    // ByteArrayInputStream(Base64.decode(connection.getSshHostKey(),
                    // Base64.DEFAULT));
                    // X509Certificate c = (X509Certificate)certFactory.generateCertificate(in);
                    // android.util.Log.e("  Subject ", c.getSubjectDN().toString());
                    // android.util.Log.e("   Issuer  ", c.getIssuerDN().toString());
                    // The certificate matches, so we proceed.
                    certificateAccepted = true;
                  }
                } catch (CertificateEncodingException e) {
                  e.printStackTrace();
                  showFatalMessageAndQuit("Certificate encoding could not be generated.");
                }
              }
              break;
          }
        }
  public TrustLinkerResult hasTrustLink(
      X509Certificate childCertificate,
      X509Certificate certificate,
      Date validationDate,
      RevocationData revocationData) {

    LOG.debug("certificate: " + childCertificate.getSubjectX500Principal());

    String issuerName = childCertificate.getIssuerX500Principal().toString();
    CertificateAuthorityEntity certificateAuthority =
        this.entityManager.find(CertificateAuthorityEntity.class, issuerName);
    if (null == certificateAuthority) {
      LOG.debug("no data cache entry for CA: " + issuerName);
      /*
       * Cache Miss
       */
      SNMPInterceptor.increment(SnmpConstants.CACHE_MISSES, SnmpConstants.SNMP_SERVICE, 1L);

      /*
       * Lookup Root CA's trust point via parent certificates' CA entity.
       */
      String parentIssuerName = certificate.getIssuerX500Principal().toString();
      CertificateAuthorityEntity parentCertificateAuthority =
          this.entityManager.find(CertificateAuthorityEntity.class, parentIssuerName);
      if (null == parentCertificateAuthority) {
        logAudit("CA not found for " + parentIssuerName);
        LOG.error("CA not found for " + parentIssuerName + " ?!");
        return null;
      }

      // create new CA
      try {
        certificateAuthority =
            new CertificateAuthorityEntity(getCrlUrl(childCertificate), certificate);
        certificateAuthority.setTrustPoint(parentCertificateAuthority.getTrustPoint());
      } catch (CertificateEncodingException e) {
        LOG.error("certificate encoding error: " + e.getMessage(), e);
        return null;
      }
      this.entityManager.persist(certificateAuthority);
      return null;
    }
    if (Status.ACTIVE != certificateAuthority.getStatus()) {
      LOG.debug("CA revocation data cache not yet active: " + issuerName);
      /*
       * Harvester is still busy processing the first CRL.
       */
      if (null == certificateAuthority.getCrlUrl()) {
        certificateAuthority.setCrlUrl(getCrlUrl(childCertificate));
      }

      if (Status.NONE != certificateAuthority.getStatus()) {
        // none means no CRL is available so not really a cache miss
        SNMPInterceptor.increment(SnmpConstants.CACHE_MISSES, SnmpConstants.SNMP_SERVICE, 1L);
      }
      return null;
    }
    /*
     * Let's use the cached revocation data
     */
    Date thisUpdate = certificateAuthority.getThisUpdate();
    if (null == thisUpdate) {
      LOG.warn("no thisUpdate value: " + certificateAuthority.getName());
      SNMPInterceptor.increment(SnmpConstants.CACHE_MISSES, SnmpConstants.SNMP_SERVICE, 1L);
      return null;
    }
    Date nextUpdate = certificateAuthority.getNextUpdate();
    if (null == nextUpdate) {
      LOG.warn("no nextUpdate value: " + certificateAuthority.getName());
      SNMPInterceptor.increment(SnmpConstants.CACHE_MISSES, SnmpConstants.SNMP_SERVICE, 1L);
      return null;
    }
    /*
     * First check whether the cached revocation data is up-to-date.
     */
    if (thisUpdate.after(validationDate)) {
      LOG.warn("cached CRL data too recent: " + certificateAuthority.getName());
      SNMPInterceptor.increment(SnmpConstants.CACHE_MISSES, SnmpConstants.SNMP_SERVICE, 1L);
      return null;
    }
    if (validationDate.after(nextUpdate)) {
      LOG.warn("cached CRL data too old: " + certificateAuthority.getName());
      SNMPInterceptor.increment(SnmpConstants.CACHE_MISSES, SnmpConstants.SNMP_SERVICE, 1L);
      return null;
    }
    LOG.debug("using cached CRL data");
    /*
     * Cache Hit
     */
    SNMPInterceptor.increment(SnmpConstants.CACHE_HITS, SnmpConstants.SNMP_SERVICE, 1L);

    BigInteger serialNumber = childCertificate.getSerialNumber();
    RevokedCertificateEntity revokedCertificate = findRevokedCertificate(issuerName, serialNumber);
    if (null == revokedCertificate) {
      LOG.debug("certificate valid: " + childCertificate.getSubjectX500Principal());
      return new TrustLinkerResult(true);
    }
    if (revokedCertificate.getRevocationDate().after(validationDate)) {
      LOG.debug(
          "CRL OK for: " + childCertificate.getSubjectX500Principal() + " at " + validationDate);
      return new TrustLinkerResult(true);
    }
    LOG.debug("certificate invalid: " + childCertificate.getSubjectX500Principal());
    return new TrustLinkerResult(
        false,
        TrustLinkerResultReason.INVALID_REVOCATION_STATUS,
        "certificate revoked by cached CRL");
  }