private void validateWithExtendedKeyUsage() throws Exception {
    CertificateFactory cf = CertificateFactory.getInstance("X.509", "BC");

    X509Certificate rootCert =
        (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(extTrust));
    X509Certificate interCert =
        (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(extCA));
    X509Certificate finalCert =
        (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(extEE));

    List list = new ArrayList();
    list.add(rootCert);
    list.add(interCert);
    list.add(finalCert);

    CollectionCertStoreParameters ccsp = new CollectionCertStoreParameters(list);
    CertStore store = CertStore.getInstance("Collection", ccsp, "BC");
    Date validDate = new Date(rootCert.getNotBefore().getTime() + 60 * 60 * 1000);
    // validating path
    List certchain = new ArrayList();
    certchain.add(finalCert);
    certchain.add(interCert);
    CertPath cp = CertificateFactory.getInstance("X.509", "BC").generateCertPath(certchain);
    Set trust = new HashSet();
    trust.add(new TrustAnchor(rootCert, null));

    CertPathValidator cpv = CertPathValidator.getInstance("PKIX", "BC");
    PKIXParameters param = new PKIXParameters(trust);
    param.addCertStore(store);
    param.setDate(validDate);
    param.setRevocationEnabled(false);

    PKIXCertPathValidatorResult result = (PKIXCertPathValidatorResult) cpv.validate(cp, param);
  }
Exemple #2
0
  private void parseCert() {
    try {
      FileInputStream fis = new FileInputStream("e:\\rongyifu.der");
      CertificateFactory cf = CertificateFactory.getInstance("X509");
      X509Certificate c = (X509Certificate) cf.generateCertificate(fis);

      System.out.println("Certficate for " + c.getSubjectDN().getName());
      System.out.println("Generated with " + c.getSigAlgName());
      System.out.println("== " + c.getSubjectDN().toString());
      String publicKey = Base64.encode(c.getPublicKey().getEncoded());
      System.out.println("publicKey=" + publicKey);

      //		      Map<String, String> map = parseSubjectDN(c.getSubjectDN().toString());
      //		      System.out.println("map: "+map);

      //		      String notBefore =c.getNotBefore().toString();//得到开始有效日期
      //		      String notAfter = c.getNotAfter().toString();//得到截止日期
      String serialNumber = c.getSerialNumber().toString(16); // 得到序列号
      String dn = c.getIssuerDN().getName(); // 得到发行者名
      String sigAlgName = c.getSigAlgName(); // 得到签名算法
      String algorithm = c.getPublicKey().getAlgorithm(); // 得到公钥算法

      SimpleDateFormat intSDF = new SimpleDateFormat("yyyyMMdd");
      System.out.println("notBefore=" + intSDF.format(c.getNotBefore()));
      System.out.println("notAfter=" + intSDF.format(c.getNotAfter()));
      System.out.println("serialNumber=" + serialNumber);
      System.out.println("dn=" + dn);
      System.out.println("sigAlgName=" + sigAlgName);
      System.out.println("algorithm=" + algorithm);

      fis.close();
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }
    /** @see de.willuhn.datasource.GenericObject#getAttribute(java.lang.String) */
    public Object getAttribute(String arg0) throws RemoteException {

      if ("name".equals(arg0)) {
        String s = myCert.getSubject().getAttribute(Principal.COMMON_NAME);
        if (s == null || s.length() == 0) {
          s = this.cert.getSubjectDN().getName();
          if (s != null && s.length() > 40) s = s.substring(0, 39) + "...";
          return s;
        }
        return s;
      }
      if ("issuer".equals(arg0)) {
        String s = myCert.getIssuer().getAttribute(Principal.COMMON_NAME);
        if (s == null || s.length() == 0)
          s = myCert.getIssuer().getAttribute(Principal.ORGANIZATION);
        if (s == null || s.length() == 0) {
          s = this.cert.getIssuerDN().getName();
          if (s != null && s.length() > 40) s = s.substring(0, 39) + "...";
        }
        return s;
      }
      if ("serial".equals(arg0)) return cert.getSerialNumber().toString();
      if ("organization".equals(arg0))
        return myCert.getSubject().getAttribute(Principal.ORGANIZATION);
      if ("ou".equals(arg0)) return myCert.getSubject().getAttribute(Principal.ORGANIZATIONAL_UNIT);
      if ("datefrom".equals(arg0)) return cert.getNotBefore();
      if ("dateto".equals(arg0)) return cert.getNotAfter();

      return null;
    }
  // 颁发证书
  public static MadCertDo issueClientCert(
      long serialNo,
      String alias,
      String cn,
      String email,
      String title,
      Map<String, String> exts,
      char[] pwd)
      throws Exception {

    X500Name subject = X500NameUtil.createClass3EndPrincipal(cn, email, title);

    KeyPair caKeyPair = CaCertLoader.getClass3CaKeyPair();

    KeyPair endKeyPair = KeyPairUtil.generateRSAKeyPair();

    X509Certificate endCert =
        getIns().createClass3EndCert(serialNo, subject, exts, endKeyPair, caKeyPair);

    MadCertDo madCertDo = new MadCertDo();
    madCertDo.setSerialNumber(serialNo);
    madCertDo.setNotBefore(endCert.getNotBefore());
    madCertDo.setNotAfter(endCert.getNotAfter());
    madCertDo.setIssuerDN(endCert.getIssuerDN().toString());
    madCertDo.setSubjectDN(endCert.getSubjectDN().toString());
    madCertDo.setKeyFile(PKCSTransformer.getKeyFileString(endKeyPair.getPrivate(), pwd));
    madCertDo.setKeyPwd(String.valueOf(pwd));

    return madCertDo;
  }
 @Override
 public void validate(List<X509Certificate> certificateChain, RevocationData revocationData)
     throws Exception {
   for (X509Certificate certificate : certificateChain) {
     LOG.debug("certificate: " + certificate.getSubjectX500Principal());
     LOG.debug("validity: " + certificate.getNotBefore() + " - " + certificate.getNotAfter());
   }
   this.trustValidator.isTrusted(certificateChain);
 }
 private String getValidity(X509Certificate certificate) {
   SimpleDateFormat dateFormat = new SimpleDateFormat("E, d MMM yyyy HH:mm:ss");
   return new StringBuilder()
       .append("Issued On: ")
       .append(dateFormat.format(certificate.getNotBefore()))
       .append('\n')
       .append("Expires On: ")
       .append(dateFormat.format(certificate.getNotAfter()))
       .toString();
 }
  public X509CertificateShortInfo(String alias, X509Certificate cert) {
    this.alias = alias;

    if (cert.getIssuerDN() != null) issuer = cert.getIssuerDN().getName();
    if (cert.getSubjectDN() != null) subject = cert.getSubjectDN().getName();
    algorithm = cert.getSigAlgName();
    notBeforeDatetime = cert.getNotBefore();
    notAfterDatetime = cert.getNotAfter();

    updateViewStyle();
  }
  /**
   * Retrieves displayable information about the certificate with the specified index in the chain.
   *
   * @param index The index of the certificate to request information on
   * @return A list of lists of {@link CertificateInformationEntry}s.
   */
  public List<List<CertificateInformationEntry>> getCertificateInfo(final int index) {
    final List<List<CertificateInformationEntry>> res =
        new ArrayList<List<CertificateInformationEntry>>();
    final X509Certificate cert = chain[index];
    List<CertificateInformationEntry> group;

    boolean tooOld = false, tooNew = false;

    try {
      cert.checkValidity();
    } catch (CertificateExpiredException ex) {
      tooOld = true;
    } catch (CertificateNotYetValidException ex) {
      tooNew = true;
    }

    group = new ArrayList<CertificateInformationEntry>();
    group.add(
        new CertificateInformationEntry(
            "Valid from", cert.getNotBefore().toString(), tooNew, false));
    group.add(
        new CertificateInformationEntry("Valid to", cert.getNotAfter().toString(), tooOld, false));
    res.add(group);

    final boolean wrongName = index == 0 && !manager.isValidHost(cert);
    final String names = getAlternateNames(cert);
    final Map<String, String> fields = CertificateManager.getDNFieldsFromCert(cert);

    group = new ArrayList<CertificateInformationEntry>();
    addCertField(fields, group, "Common name", "CN", wrongName);

    group.add(
        new CertificateInformationEntry(
            "Alternate names", names == null ? NOTPRESENT : names, wrongName, names == null));

    addCertField(fields, group, "Organisation", "O", false);
    addCertField(fields, group, "Unit", "OU", false);
    addCertField(fields, group, "Locality", "L", false);
    addCertField(fields, group, "State", "ST", false);
    addCertField(fields, group, "Country", "C", false);
    res.add(group);

    group = new ArrayList<CertificateInformationEntry>();
    group.add(
        new CertificateInformationEntry(
            "Serial number", cert.getSerialNumber().toString(), false, false));
    group.add(new CertificateInformationEntry("Algorithm", cert.getSigAlgName(), false, false));
    group.add(
        new CertificateInformationEntry(
            "SSL version", String.valueOf(cert.getVersion()), false, false));
    res.add(group);

    return res;
  }
  /*
   * 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();
    }
  }
Exemple #10
0
 public static void sign(File input, File output) {
   JarFile inputJar = null;
   JarOutputStream outputJar = null;
   FileOutputStream outputFile = null;
   try {
     X509Certificate publicKey =
         Signer.readPublicKey(Signer.class.getResourceAsStream("/key.x509.pem"));
     PrivateKey privateKey = Signer.readPrivateKey(Signer.class.getResourceAsStream("/key.pk8"));
     long timestamp = publicKey.getNotBefore().getTime() + 3600L * 1000;
     inputJar = new JarFile(input, false);
     outputFile = new FileOutputStream(output);
     outputJar = new JarOutputStream(outputFile);
     outputJar.setLevel(9);
     Manifest manifest = Signer.addDigestsToManifest(inputJar);
     JarEntry je = new JarEntry(JarFile.MANIFEST_NAME);
     je.setTime(timestamp);
     outputJar.putNextEntry(je);
     manifest.write(outputJar);
     Signature signature = Signature.getInstance("SHA1withRSA");
     signature.initSign(privateKey);
     je = new JarEntry(Signer.CERT_SF_NAME);
     je.setTime(timestamp);
     outputJar.putNextEntry(je);
     Signer.writeSignatureFile(manifest, new SignatureOutputStream(outputJar, signature));
     je = new JarEntry(Signer.CERT_RSA_NAME);
     je.setTime(timestamp);
     outputJar.putNextEntry(je);
     Signer.writeSignatureBlock(signature, publicKey, outputJar);
     Signer.copyFiles(manifest, inputJar, outputJar, timestamp);
     outputJar.close();
     outputJar = null;
     outputFile.flush();
   } catch (Exception e) {
     e.printStackTrace();
     System.exit(1);
   } finally {
     try {
       if (inputJar != null) {
         inputJar.close();
       }
       if (outputFile != null) {
         outputFile.close();
       }
     } catch (IOException e) {
       e.printStackTrace();
       System.exit(1);
     }
   }
 }
 public static String prettyPrint(X509Certificate x509) {
   if (x509 == null) throw new IllegalArgumentException("x509 cannot be null");
   return String.format(
       FORMAT,
       x509.getVersion(),
       x509.getSerialNumber(),
       x509.getSigAlgName(),
       x509.getIssuerX500Principal().getName(),
       x509.getNotBefore(),
       x509.getNotAfter(),
       x509.getSubjectX500Principal().getName(),
       x509.getPublicKey().getAlgorithm(),
       x509.getBasicConstraints(),
       x509.getSigAlgName());
 }
 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");
 }
  private X509Certificate readCertificate(String certPath) {
    try {
      FileInputStream fr = new FileInputStream(certPath);
      CertificateFactory cf = CertificateFactory.getInstance("X509");
      X509Certificate crt = (X509Certificate) cf.generateCertificate(fr);
      logger.info("Read certificate:");
      logger.info("\tCertificate for: " + crt.getSubjectDN());
      logger.info("\tCertificate issued by: " + crt.getIssuerDN());
      logger.info("\tCertificate is valid from " + crt.getNotBefore() + " to " + crt.getNotAfter());
      logger.info("\tCertificate SN# " + crt.getSerialNumber());
      logger.info("\tGenerated with " + crt.getSigAlgName());

      return crt;
    } catch (Exception e) {
      e.printStackTrace();
    }

    return null;
  }
 /*     */ private boolean isWorthTrying(
     X509Certificate paramX509Certificate1, X509Certificate paramX509Certificate2)
       /*     */ {
   /* 220 */ boolean bool = false;
   /*     */
   /* 222 */ if (debug != null) {
     /* 223 */ debug.println(
         "PKIXCertPathValidator.isWorthTrying() checking if this trusted cert is worth trying ...");
     /*     */ }
   /*     */
   /* 227 */ if (paramX509Certificate2 == null) {
     /* 228 */ return true;
     /*     */ }
   /*     */
   /* 231 */ AdaptableX509CertSelector localAdaptableX509CertSelector =
       new AdaptableX509CertSelector();
   /*     */
   /* 235 */ localAdaptableX509CertSelector.setSubject(
       paramX509Certificate2.getIssuerX500Principal());
   /*     */
   /* 238 */ localAdaptableX509CertSelector.setValidityPeriod(
       paramX509Certificate2.getNotBefore(), paramX509Certificate2.getNotAfter());
   /*     */ try
   /*     */ {
     /* 246 */ X509CertImpl localX509CertImpl = X509CertImpl.toImpl(paramX509Certificate2);
     /* 247 */ localAdaptableX509CertSelector.parseAuthorityKeyIdentifierExtension(
         localX509CertImpl.getAuthorityKeyIdentifierExtension());
     /*     */
     /* 250 */ bool = localAdaptableX509CertSelector.match(paramX509Certificate1);
     /*     */ }
   /*     */ catch (Exception localException)
   /*     */ {
     /*     */ }
   /* 255 */ if (debug != null) {
     /* 256 */ if (bool) /* 257 */ debug.println("YES - try this trustedCert");
     /*     */ else {
       /* 259 */ debug.println("NO - don't try this trustedCert");
       /*     */ }
     /*     */ }
   /*     */
   /* 263 */ return bool;
   /*     */ }
Exemple #15
0
 /**
  * Load an X509 Cert from a file and add it to the trusted set of certificates in the key store
  *
  * @return success
  * @since 0.8.2, moved from SSLEepGet in 0.9.9
  */
 public static boolean addCert(File file, String alias, KeyStore ks) {
   InputStream fis = null;
   try {
     fis = new FileInputStream(file);
     CertificateFactory cf = CertificateFactory.getInstance("X.509");
     X509Certificate cert = (X509Certificate) cf.generateCertificate(fis);
     info(
         "Read X509 Certificate from "
             + file.getAbsolutePath()
             + " Issuer: "
             + cert.getIssuerX500Principal()
             + "; Valid From: "
             + cert.getNotBefore()
             + " To: "
             + cert.getNotAfter());
     try {
       cert.checkValidity();
     } catch (CertificateExpiredException cee) {
       error("Rejecting expired X509 Certificate: " + file.getAbsolutePath(), cee);
       return false;
     } catch (CertificateNotYetValidException cnyve) {
       error("Rejecting X509 Certificate not yet valid: " + file.getAbsolutePath(), cnyve);
       return false;
     }
     ks.setCertificateEntry(alias, cert);
     info("Now trusting X509 Certificate, Issuer: " + cert.getIssuerX500Principal());
   } catch (GeneralSecurityException gse) {
     error("Error reading X509 Certificate: " + file.getAbsolutePath(), gse);
     return false;
   } catch (IOException ioe) {
     error("Error reading X509 Certificate: " + file.getAbsolutePath(), ioe);
     return false;
   } finally {
     try {
       if (fis != null) fis.close();
     } catch (IOException foo) {
     }
   }
   return true;
 }
 private void logKeyStore(KeyStore store) throws KeyStoreException {
   LOG.trace("Certificates count: " + store.size());
   Enumeration aliases = store.aliases();
   while (aliases.hasMoreElements()) {
     String alias = (String) aliases.nextElement();
     Certificate[] certs = store.getCertificateChain(alias);
     if (certs != null) {
       LOG.debug("Certificate chain '" + alias + "':");
       for (int c = 0; c < certs.length; c++) {
         if (certs[c] instanceof X509Certificate) {
           X509Certificate cert = (X509Certificate) certs[c];
           LOG.trace(" Certificate " + (c + 1) + ":");
           LOG.trace("  Subject DN: " + cert.getSubjectDN());
           LOG.trace("  Signature Algorithm: " + cert.getSigAlgName());
           LOG.trace("  Valid from: " + cert.getNotBefore());
           LOG.trace("  Valid until: " + cert.getNotAfter());
           LOG.trace("  Issuer: " + cert.getIssuerDN());
         }
       }
     }
   }
 }
 public static String toString(X509Certificate cert, boolean htmlStyle) {
   String cn = getCN(cert);
   String startStart = DF.format(cert.getNotBefore());
   String endDate = DF.format(cert.getNotAfter());
   String subject = JavaImpl.getSubjectX500(cert);
   String issuer = JavaImpl.getIssuerX500(cert);
   Iterator crls = getCRLs(cert).iterator();
   if (subject.equals(issuer)) {
     issuer = "self-signed";
   }
   StringBuffer buf = new StringBuffer(128);
   if (htmlStyle) {
     buf.append("<strong class=\"cn\">");
   }
   buf.append(cn);
   if (htmlStyle) {
     buf.append("</strong>");
   }
   buf.append(LINE_ENDING);
   buf.append("Valid: ");
   buf.append(startStart);
   buf.append(" - ");
   buf.append(endDate);
   buf.append(LINE_ENDING);
   buf.append("s: ");
   buf.append(subject);
   buf.append(LINE_ENDING);
   buf.append("i: ");
   buf.append(issuer);
   while (crls.hasNext()) {
     buf.append(LINE_ENDING);
     buf.append("CRL: ");
     buf.append((String) crls.next());
   }
   buf.append(LINE_ENDING);
   return buf.toString();
 }
 /** @return Date -> Validate starts date */
 public Date getBeforeDate() {
   return certificate.getNotBefore();
 }
  /**
   * Appends an HTML representation of the given X509Certificate.
   *
   * @param sb StringBuilder to append to
   * @param certificate to print
   */
  private void renderX509(StringBuilder sb, X509Certificate certificate) {
    X500Principal issuer = certificate.getIssuerX500Principal();
    X500Principal subject = certificate.getSubjectX500Principal();

    sb.append("<table cellspacing='1' cellpadding='1'>\n");

    // subject
    addTitle(sb, R.getI18NString("service.gui.CERT_INFO_ISSUED_TO"));
    try {
      for (Rdn name : new LdapName(subject.getName()).getRdns()) {
        String nameType = name.getType();
        String lblKey = "service.gui.CERT_INFO_" + nameType;
        String lbl = R.getI18NString(lblKey);

        if ((lbl == null) || ("!" + lblKey + "!").equals(lbl)) lbl = nameType;

        final String value;
        Object nameValue = name.getValue();

        if (nameValue instanceof byte[]) {
          byte[] nameValueAsByteArray = (byte[]) nameValue;

          value = getHex(nameValueAsByteArray) + " (" + new String(nameValueAsByteArray) + ")";
        } else value = nameValue.toString();

        addField(sb, lbl, value);
      }
    } catch (InvalidNameException ine) {
      addField(sb, R.getI18NString("service.gui.CERT_INFO_CN"), subject.getName());
    }

    // issuer
    addTitle(sb, R.getI18NString("service.gui.CERT_INFO_ISSUED_BY"));
    try {
      for (Rdn name : new LdapName(issuer.getName()).getRdns()) {
        String nameType = name.getType();
        String lblKey = "service.gui.CERT_INFO_" + nameType;
        String lbl = R.getI18NString(lblKey);

        if ((lbl == null) || ("!" + lblKey + "!").equals(lbl)) lbl = nameType;

        final String value;
        Object nameValue = name.getValue();

        if (nameValue instanceof byte[]) {
          byte[] nameValueAsByteArray = (byte[]) nameValue;

          value = getHex(nameValueAsByteArray) + " (" + new String(nameValueAsByteArray) + ")";
        } else value = nameValue.toString();

        addField(sb, lbl, value);
      }
    } catch (InvalidNameException ine) {
      addField(sb, R.getI18NString("service.gui.CERT_INFO_CN"), issuer.getName());
    }

    // validity
    addTitle(sb, R.getI18NString("service.gui.CERT_INFO_VALIDITY"));
    addField(
        sb,
        R.getI18NString("service.gui.CERT_INFO_ISSUED_ON"),
        certificate.getNotBefore().toString());
    addField(
        sb,
        R.getI18NString("service.gui.CERT_INFO_EXPIRES_ON"),
        certificate.getNotAfter().toString());

    addTitle(sb, R.getI18NString("service.gui.CERT_INFO_FINGERPRINTS"));
    try {
      String sha1String = getThumbprint(certificate, "SHA1");
      String md5String = getThumbprint(certificate, "MD5");

      addField(sb, "SHA1:", sha1String);
      addField(sb, "MD5:", md5String);
    } catch (CertificateException e) {
      // do nothing as we cannot show this value
    }

    addTitle(sb, R.getI18NString("service.gui.CERT_INFO_CERT_DETAILS"));

    addField(
        sb,
        R.getI18NString("service.gui.CERT_INFO_SER_NUM"),
        certificate.getSerialNumber().toString());

    addField(
        sb, R.getI18NString("service.gui.CERT_INFO_VER"), String.valueOf(certificate.getVersion()));

    addField(
        sb,
        R.getI18NString("service.gui.CERT_INFO_SIGN_ALG"),
        String.valueOf(certificate.getSigAlgName()));

    addTitle(sb, R.getI18NString("service.gui.CERT_INFO_PUB_KEY_INFO"));

    addField(
        sb,
        R.getI18NString("service.gui.CERT_INFO_ALG"),
        certificate.getPublicKey().getAlgorithm());

    if (certificate.getPublicKey().getAlgorithm().equals("RSA")) {
      RSAPublicKey key = (RSAPublicKey) certificate.getPublicKey();

      addField(
          sb,
          R.getI18NString("service.gui.CERT_INFO_PUB_KEY"),
          R.getI18NString(
              "service.gui.CERT_INFO_KEY_BYTES_PRINT",
              new String[] {
                String.valueOf(key.getModulus().toByteArray().length - 1),
                key.getModulus().toString(16)
              }));

      addField(
          sb, R.getI18NString("service.gui.CERT_INFO_EXP"), key.getPublicExponent().toString());

      addField(
          sb,
          R.getI18NString("service.gui.CERT_INFO_KEY_SIZE"),
          R.getI18NString(
              "service.gui.CERT_INFO_KEY_BITS_PRINT",
              new String[] {String.valueOf(key.getModulus().bitLength())}));
    } else if (certificate.getPublicKey().getAlgorithm().equals("DSA")) {
      DSAPublicKey key = (DSAPublicKey) certificate.getPublicKey();

      addField(sb, "Y:", key.getY().toString(16));
    }

    addField(
        sb,
        R.getI18NString("service.gui.CERT_INFO_SIGN"),
        R.getI18NString(
            "service.gui.CERT_INFO_KEY_BYTES_PRINT",
            new String[] {
              String.valueOf(certificate.getSignature().length), getHex(certificate.getSignature())
            }));

    sb.append("</table>\n");
  }
  public void performTest() throws Exception {
    CertificateFactory cf = CertificateFactory.getInstance("X.509", "BC");

    // initialise CertStore
    X509Certificate rootCert =
        (X509Certificate)
            cf.generateCertificate(new ByteArrayInputStream(CertPathTest.rootCertBin));
    X509Certificate interCert =
        (X509Certificate)
            cf.generateCertificate(new ByteArrayInputStream(CertPathTest.interCertBin));
    X509Certificate finalCert =
        (X509Certificate)
            cf.generateCertificate(new ByteArrayInputStream(CertPathTest.finalCertBin));
    X509CRL rootCrl = (X509CRL) cf.generateCRL(new ByteArrayInputStream(CertPathTest.rootCrlBin));
    X509CRL interCrl = (X509CRL) cf.generateCRL(new ByteArrayInputStream(CertPathTest.interCrlBin));
    List list = new ArrayList();
    list.add(rootCert);
    list.add(interCert);
    list.add(finalCert);
    list.add(rootCrl);
    list.add(interCrl);
    CollectionCertStoreParameters ccsp = new CollectionCertStoreParameters(list);
    CertStore store = CertStore.getInstance("Collection", ccsp, "BC");
    Date validDate = new Date(rootCrl.getThisUpdate().getTime() + 60 * 60 * 1000);
    // validating path
    List certchain = new ArrayList();
    certchain.add(finalCert);
    certchain.add(interCert);
    CertPath cp = CertificateFactory.getInstance("X.509", "BC").generateCertPath(certchain);
    Set trust = new HashSet();
    trust.add(new TrustAnchor(rootCert, null));

    CertPathValidator cpv = CertPathValidator.getInstance("PKIX", "BC");
    PKIXParameters param = new PKIXParameters(trust);
    param.addCertStore(store);
    param.setDate(validDate);
    MyChecker checker = new MyChecker();
    param.addCertPathChecker(checker);

    PKIXCertPathValidatorResult result = (PKIXCertPathValidatorResult) cpv.validate(cp, param);
    PolicyNode policyTree = result.getPolicyTree();
    PublicKey subjectPublicKey = result.getPublicKey();

    if (checker.getCount() != 2) {
      fail("checker not evaluated for each certificate");
    }

    if (!subjectPublicKey.equals(finalCert.getPublicKey())) {
      fail("wrong public key returned");
    }

    //
    // invalid path containing a valid one test
    //
    try {
      // initialise CertStore
      rootCert =
          (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(AC_RAIZ_ICPBRASIL));
      interCert = (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(AC_PR));
      finalCert = (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(schefer));

      list = new ArrayList();
      list.add(rootCert);
      list.add(interCert);
      list.add(finalCert);

      ccsp = new CollectionCertStoreParameters(list);
      store = CertStore.getInstance("Collection", ccsp);
      validDate = new Date(finalCert.getNotBefore().getTime() + 60 * 60 * 1000);

      // validating path
      certchain = new ArrayList();
      certchain.add(finalCert);
      certchain.add(interCert);
      cp = CertificateFactory.getInstance("X.509", "BC").generateCertPath(certchain);
      trust = new HashSet();
      trust.add(new TrustAnchor(rootCert, null));

      cpv = CertPathValidator.getInstance("PKIX", "BC");
      param = new PKIXParameters(trust);
      param.addCertStore(store);
      param.setRevocationEnabled(false);
      param.setDate(validDate);

      result = (PKIXCertPathValidatorResult) cpv.validate(cp, param);
      policyTree = result.getPolicyTree();
      subjectPublicKey = result.getPublicKey();

      fail("Invalid path validated");
    } catch (Exception e) {
      if (!(e instanceof CertPathValidatorException
          && e.getMessage().startsWith("Could not validate certificate signature."))) {
        fail("unexpected exception", e);
      }
    }

    checkCircProcessing();
    checkPolicyProcessingAtDomainMatch();
    validateWithExtendedKeyUsage();
    testEmptyPath();
  }
Exemple #21
0
 public TimeTool getValidFrom() {
   Date val = cert.getNotBefore();
   TimeTool ret = new TimeTool(val.getTime());
   return ret;
 }