private static String hexString(byte[] data) {
   StringBuffer si = new StringBuffer();
   for (int i = 0; i < data.length; i++) {
     si.append(String.format("%02x", data[i]));
     if (i < data.length - 1) si.append(":");
   }
   return si.toString();
 }
예제 #2
0
  /**
   * readPEM: Read a PEM encoded base64 stream and decode it
   *
   * @param is Base64 PEM encoded stream
   * @param hdr Header delimeter (e.g. ----------CERTIFICATE---------)
   * @param ftr Footer delimeter (e.g. ----------END CERTIFICATE---------)
   * @return decoded DER bytes
   * @throws IOException if a read error occurs
   */
  public static byte[] readPEM(InputStream is, String hdr, String ftr) throws IOException {
    logger.debug("Reading PEM hdr:" + hdr + " ftr:" + ftr);
    is.reset();
    InputStreamReader irr = new InputStreamReader(is);
    BufferedReader r = new BufferedReader(irr);

    StringBuffer buff = new StringBuffer();
    String line;
    boolean read = false;

    while ((line = r.readLine()) != null) {
      if (line.equals(hdr)) {
        read = true;
        continue;
      }
      if (line.equals(ftr)) read = false;
      if (read) buff.append(line);
    }
    return Base64.decode(buff.toString().getBytes());
  }
예제 #3
0
  /** Write certficate bytes into a PEM encoded string */
  public static String writePEM(byte[] bytes, String hdr, String ftr) throws IOException {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    Base64OutputStream b64os = new Base64OutputStream(bos);
    b64os.write(bytes);
    b64os.flush();
    b64os.close();

    ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
    InputStreamReader irr = new InputStreamReader(bis);
    BufferedReader r = new BufferedReader(irr);

    StringBuffer buff = new StringBuffer();
    String line;
    buff.append(hdr);

    while ((line = r.readLine()) != null) {
      buff.append(line + "\n");
    }
    buff.append(ftr);
    return buff.toString();
  }
예제 #4
0
 /* Cert RQ info header */
 private String buildRequestInfoHeader(String subject) {
   StringBuffer buff =
       new StringBuffer(
           "This is a Certificate Request file:\nIt should be mailed to to a CA for signature");
   buff.append("\n===============================================================");
   buff.append("\nCertificate Subject:\n\t");
   buff.append(subject);
   buff.append("\n\n");
   return buff.toString();
 }
 private String certChainMessage(final X509Certificate[] chain, CertificateException cause) {
   Throwable e = cause;
   LOGGER.log(Level.FINE, "certChainMessage for " + e);
   StringBuffer si = new StringBuffer();
   if (e.getCause() != null) {
     e = e.getCause();
     // HACK: there is no sane way to check if the error is a "trust anchor
     // not found", so we use string comparison.
     if (NO_TRUST_ANCHOR.equals(e.getMessage())) {
       si.append(master.getString(R.string.mtm_trust_anchor));
     } else si.append(e.getLocalizedMessage());
     si.append("\n");
   }
   si.append("\n");
   si.append(master.getString(R.string.mtm_connect_anyway));
   si.append("\n\n");
   si.append(master.getString(R.string.mtm_cert_details));
   for (X509Certificate c : chain) {
     certDetails(si, c);
   }
   return si.toString();
 }
  /*
   * Initializes the signerInfo and the VerifierInfo from the Certificate Pair
   */
  private void initializeCertificates() {
    X509Certificate certRoot = null;
    X509Certificate certIssuer = null;
    CertificatePair trustedCertificate;
    if (getFoundCertificate() == null) {
      CertificatePair[] certs = getRootCertificates();
      if (certs.length == 0) return;
      trustedCertificate = certs[0];
    } else {
      trustedCertificate = getFoundCertificate();
    }
    certRoot = (X509Certificate) trustedCertificate.getRoot();
    certIssuer = (X509Certificate) trustedCertificate.getIssuer();

    StringBuffer strb = new StringBuffer();
    strb.append(issuerString(certIssuer.getSubjectDN()));
    strb.append("\r\n"); // $NON-NLS-1$
    strb.append(
        NLS.bind(
            Messages.JarVerificationResult_ValidBetween,
            (new String[] {
              dateString(certIssuer.getNotBefore()), dateString(certIssuer.getNotAfter())
            })));
    strb.append(checkValidity(certIssuer));
    signerInfo = strb.toString();
    if (certIssuer != null && !certIssuer.equals(certRoot)) {
      strb = new StringBuffer();
      strb.append(issuerString(certIssuer.getIssuerDN()));
      strb.append("\r\n"); // $NON-NLS-1$
      strb.append(
          NLS.bind(
              Messages.JarVerificationResult_ValidBetween,
              (new String[] {
                dateString(certRoot.getNotBefore()), dateString(certRoot.getNotAfter())
              })));
      strb.append(checkValidity(certRoot));
      verifierInfo = strb.toString();
    }
  }
  private String hostNameMessage(X509Certificate cert, String hostname) {
    StringBuffer si = new StringBuffer();

    si.append(master.getString(R.string.mtm_hostname_mismatch, hostname));
    si.append("\n\n");
    try {
      Collection<List<?>> sans = cert.getSubjectAlternativeNames();
      if (sans == null) {
        si.append(cert.getSubjectDN());
        si.append("\n");
      } else
        for (List<?> altName : sans) {
          Object name = altName.get(1);
          if (name instanceof String) {
            si.append("[");
            si.append((Integer) altName.get(0));
            si.append("] ");
            si.append(name);
            si.append("\n");
          }
        }
    } catch (CertificateParsingException e) {
      e.printStackTrace();
      si.append("<Parsing error: ");
      si.append(e.getLocalizedMessage());
      si.append(">\n");
    }
    si.append("\n");
    si.append(master.getString(R.string.mtm_connect_anyway));
    si.append("\n\n");
    si.append(master.getString(R.string.mtm_cert_details));
    certDetails(si, cert);
    return si.toString();
  }
 private void certDetails(StringBuffer si, X509Certificate c) {
   SimpleDateFormat validityDateFormater = new SimpleDateFormat("yyyy-MM-dd");
   si.append("\n");
   si.append(c.getSubjectDN().toString());
   si.append("\n");
   si.append(validityDateFormater.format(c.getNotBefore()));
   si.append(" - ");
   si.append(validityDateFormater.format(c.getNotAfter()));
   si.append("\nSHA-256: ");
   si.append(certHash(c, "SHA-256"));
   si.append("\nSHA-1: ");
   si.append(certHash(c, "SHA-1"));
   si.append("\nSigned by: ");
   si.append(c.getIssuerDN().toString());
   si.append("\n");
 }
예제 #9
0
  /**
   * Returns an ASN.1 SEQUENCE from a stream, which might be a BER-encoded binary block or a
   * PEM-style BASE64-encoded ASCII data. In the latter case, it's de-BASE64'ed before return.
   *
   * <p>After the reading, the input stream pointer is after the BER block, or after the newline
   * character after the -----END SOMETHING----- line.
   *
   * @param is the InputStream
   * @returns byte block or null if end of stream
   * @throws IOException If any parsing error
   */
  private static byte[] readOneBlock(InputStream is) throws IOException {

    // The first character of a BLOCK.
    int c = is.read();
    if (c == -1) {
      return null;
    }
    if (c == DerValue.tag_Sequence) {
      ByteArrayOutputStream bout = new ByteArrayOutputStream(2048);
      bout.write(c);
      readBERInternal(is, bout, c);
      return bout.toByteArray();
    } else {
      // Read BASE64 encoded data, might skip info at the beginning
      char[] data = new char[2048];
      int pos = 0;

      // Step 1: Read until header is found
      int hyphen = (c == '-') ? 1 : 0; // count of consequent hyphens
      int last = (c == '-') ? -1 : c; // the char before hyphen
      while (true) {
        int next = is.read();
        if (next == -1) {
          // We accept useless data after the last block,
          // say, empty lines.
          return null;
        }
        if (next == '-') {
          hyphen++;
        } else {
          hyphen = 0;
          last = next;
        }
        if (hyphen == 5 && (last == -1 || last == '\r' || last == '\n')) {
          break;
        }
      }

      // Step 2: Read the rest of header, determine the line end
      int end;
      StringBuffer header = new StringBuffer("-----");
      while (true) {
        int next = is.read();
        if (next == -1) {
          throw new IOException("Incomplete data");
        }
        if (next == '\n') {
          end = '\n';
          break;
        }
        if (next == '\r') {
          next = is.read();
          if (next == -1) {
            throw new IOException("Incomplete data");
          }
          if (next == '\n') {
            end = '\n';
          } else {
            end = '\r';
            data[pos++] = (char) next;
          }
          break;
        }
        header.append((char) next);
      }

      // Step 3: Read the data
      while (true) {
        int next = is.read();
        if (next == -1) {
          throw new IOException("Incomplete data");
        }
        if (next != '-') {
          data[pos++] = (char) next;
          if (pos >= data.length) {
            data = Arrays.copyOf(data, data.length + 1024);
          }
        } else {
          break;
        }
      }

      // Step 4: Consume the footer
      StringBuffer footer = new StringBuffer("-");
      while (true) {
        int next = is.read();
        // Add next == '\n' for maximum safety, in case endline
        // is not consistent.
        if (next == -1 || next == end || next == '\n') {
          break;
        }
        if (next != '\r') footer.append((char) next);
      }

      checkHeaderFooter(header.toString(), footer.toString());

      return Base64.getMimeDecoder().decode(new String(data, 0, pos));
    }
  }
 private String certChainMessage(final X509Certificate[] chain, CertificateException cause) {
   Throwable e = cause;
   Log.d(TAG, "certChainMessage for " + e);
   StringBuffer si = new StringBuffer();
   if (e.getCause() != null) {
     e = e.getCause();
     si.append(e.getLocalizedMessage());
     // si.append("\n");
   }
   for (X509Certificate c : chain) {
     si.append("\n\n");
     si.append(c.getSubjectDN().toString());
     si.append("\nMD5: ");
     si.append(certHash(c, "MD5"));
     si.append("\nSHA1: ");
     si.append(certHash(c, "SHA-1"));
     si.append("\nSigned by: ");
     si.append(c.getIssuerDN().toString());
   }
   return si.toString();
 }