private static Key getPublicKey(String certificatePath, FilterConfig filterConfig)
     throws ServletException {
   Certificate certificate = null;
   InputStream is = null;
   try {
     if (certificatePath != null) certificatePath = certificatePath.replace('\\', '/');
     certificatePath = getCertificatePath(certificatePath);
     File certFile = new File(certificatePath);
     if (certFile.isAbsolute()) is = new FileInputStream(certificatePath);
     else is = filterConfig.getServletContext().getResourceAsStream(EMBEDDED_CERT_LOC);
     BufferedInputStream bufferedInputStream = new BufferedInputStream(is);
     CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
     while (bufferedInputStream.available() > 0) {
       certificate = certificateFactory.generateCertificate(bufferedInputStream);
     }
   } catch (FileNotFoundException fnfe) {
     throw new ServletException("File not found " + certificatePath);
   } catch (Throwable t) {
     throw new ServletException("Error while retrieving public key from certificate");
   } finally {
     if (is != null) {
       try {
         is.close();
       } catch (Exception e) {
         // Ignore exception silently here
       }
     }
   }
   return certificate.getPublicKey();
 }
  public void testEmptyPath() throws Exception {
    CertificateFactory cf = CertificateFactory.getInstance("X.509", "BC");
    X509Certificate rootCert =
        (X509Certificate)
            cf.generateCertificate(new ByteArrayInputStream(CertPathTest.rootCertBin));

    List list = new ArrayList();
    list.add(rootCert);
    CollectionCertStoreParameters ccsp = new CollectionCertStoreParameters(list);
    CertStore store = CertStore.getInstance("Collection", ccsp, "BC");

    List certchain = new ArrayList();
    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);
    MyChecker checker = new MyChecker();
    param.addCertPathChecker(checker);

    try {
      cpv.validate(cp, param);
    } catch (CertPathValidatorException e) {
      if (!"Certification path is empty.".equals(e.getMessage())) {
        fail("message mismatch");
      }
    }
  }
  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);
  }
  @Override
  public void invoke(Request request, Response response) throws IOException, ServletException {

    /*
     * mod_header converts the '\n' into ' ' so we have to rebuild the client
     * certificate
     */
    String strcert0 = mygetHeader(request, "ssl_client_cert");
    if (strcert0 != null && strcert0.length() > 28) {
      String strcert1 = strcert0.replace(' ', '\n');
      String strcert2 = strcert1.substring(28, strcert1.length() - 26);
      String strcert3 = "-----BEGIN CERTIFICATE-----\n";
      String strcert4 = strcert3.concat(strcert2);
      String strcerts = strcert4.concat("\n-----END CERTIFICATE-----\n");
      // ByteArrayInputStream bais = new
      // ByteArrayInputStream(strcerts.getBytes("UTF-8"));
      ByteArrayInputStream bais =
          new ByteArrayInputStream(strcerts.getBytes(Charset.defaultCharset()));
      X509Certificate jsseCerts[] = null;
      String providerName = (String) request.getConnector().getProperty("clientCertProvider");
      try {
        CertificateFactory cf;
        if (providerName == null) {
          cf = CertificateFactory.getInstance("X.509");
        } else {
          cf = CertificateFactory.getInstance("X.509", providerName);
        }
        X509Certificate cert = (X509Certificate) cf.generateCertificate(bais);
        jsseCerts = new X509Certificate[1];
        jsseCerts[0] = cert;
      } catch (java.security.cert.CertificateException e) {
        log.warn(sm.getString("sslValve.certError", strcerts), e);
      } catch (NoSuchProviderException e) {
        log.error(sm.getString("sslValve.invalidProvider", providerName), e);
      }
      request.setAttribute(Globals.CERTIFICATES_ATTR, jsseCerts);
    }
    strcert0 = mygetHeader(request, "ssl_cipher");
    if (strcert0 != null) {
      request.setAttribute(Globals.CIPHER_SUITE_ATTR, strcert0);
    }
    strcert0 = mygetHeader(request, "ssl_session_id");
    if (strcert0 != null) {
      request.setAttribute(Globals.SSL_SESSION_ID_ATTR, strcert0);
      request.setAttribute(Globals.SSL_SESSION_ID_TOMCAT_ATTR, strcert0);
    }
    strcert0 = mygetHeader(request, "ssl_cipher_usekeysize");
    if (strcert0 != null) {
      request.setAttribute(Globals.KEY_SIZE_ATTR, Integer.valueOf(strcert0));
    }
    getNext().invoke(request, response);
  }
Exemple #5
0
  private void testExceptions() throws Exception {
    byte[] enc = {(byte) 0, (byte) 2, (byte) 3, (byte) 4, (byte) 5};
    MyCertPath mc = new MyCertPath(enc);
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    ByteArrayInputStream is;
    byte[] arr;

    ObjectOutputStream oOut = new ObjectOutputStream(os);
    oOut.writeObject(mc);
    oOut.flush();
    oOut.close();

    try {
      CertificateFactory cFac = CertificateFactory.getInstance("X.509", "BC");
      arr = os.toByteArray();
      is = new ByteArrayInputStream(arr);
      cFac.generateCertPath(is);
    } catch (CertificateException e) {
      // ignore okay
    }

    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    List certCol = new ArrayList();

    certCol.add(cf.generateCertificate(new ByteArrayInputStream(certA)));
    certCol.add(cf.generateCertificate(new ByteArrayInputStream(certB)));
    certCol.add(cf.generateCertificate(new ByteArrayInputStream(certC)));
    certCol.add(cf.generateCertificate(new ByteArrayInputStream(certD)));

    CertPathBuilder pathBuilder = CertPathBuilder.getInstance("PKIX", "BC");
    X509CertSelector select = new X509CertSelector();
    select.setSubject(((X509Certificate) certCol.get(0)).getSubjectX500Principal().getEncoded());

    Set trustanchors = new HashSet();
    trustanchors.add(
        new TrustAnchor(
            (X509Certificate) cf.generateCertificate(new ByteArrayInputStream(rootCertBin)), null));

    CertStore certStore =
        CertStore.getInstance("Collection", new CollectionCertStoreParameters(certCol));

    PKIXBuilderParameters params = new PKIXBuilderParameters(trustanchors, select);
    params.addCertStore(certStore);

    try {
      CertPathBuilderResult result = pathBuilder.build(params);
      CertPath path = result.getCertPath();
      fail("found cert path in circular set");
    } catch (CertPathBuilderException e) {
      // expected
    }
  }
 /**
  * Handles server certificate validation. Flags for validity and certificate chain verification
  * decides this functions behavior.
  *
  * <p>Implements X509TrustManager.
  */
 public void checkServerTrusted(X509Certificate[] chain, String authType)
     throws CertificateException {
   try {
     Set<TrustAnchor> trust = new HashSet<TrustAnchor>();
     // All CAs must in an *installed* CA path be valid as trust
     // anchors
     Enumeration<String> aliases = trust_store.aliases();
     while (aliases.hasMoreElements()) {
       String alias = aliases.nextElement();
       if (trust_store.isCertificateEntry(alias)) {
         trust.add(new TrustAnchor((X509Certificate) trust_store.getCertificate(alias), null));
       }
     }
     CertPathValidator cpv = CertPathValidator.getInstance("PKIX");
     PKIXParameters param = new PKIXParameters(trust);
     param.setDate(new Date());
     param.setRevocationEnabled(enable_revocation_test);
     List<X509Certificate> certchain = new ArrayList<X509Certificate>();
     for (X509Certificate cert : chain) {
       if (!cert.getSubjectX500Principal().equals(cert.getIssuerX500Principal())) {
         certchain.add(cert);
       }
     }
     CertPath cp = CertificateFactory.getInstance("X.509").generateCertPath(certchain);
     cpv.validate(cp, param);
   } catch (GeneralSecurityException e) {
     if (!allow_invalidcert) {
       throw new CertificateException(e);
     }
   }
 }
  /** java.security.KeyStore#size() */
  public void test_size() throws Exception {
    // Test for method int java.security.KeyStore.size()

    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    X509Certificate cert[] = new X509Certificate[2];
    cert[0] = (X509Certificate) cf.generateCertificate(certArray);
    cert[1] = (X509Certificate) cf.generateCertificate(certArray2);
    KeyStore keyTest = KeyStore.getInstance(KeyStore.getDefaultType());

    try {
      keyTest.size();
      fail();
    } catch (KeyStoreException expected) {
    }

    keyTest.load(null, null);
    // alias 1
    keyTest.setCertificateEntry("alias1", cert[0]);

    // alias 2
    keyTest.setKeyEntry("alias2", getPrivateKey(), pssWord, cert);

    // alias 3
    keyTest.setCertificateEntry("alias3", cert[1]);

    assertEquals("the size of the keyStore is not 3", 3, keyTest.size());
  }
  /**
   * java.security.KeyStore#setKeyEntry(java.lang.String, java.security.Key, char[],
   * java.security.cert.Certificate[])
   */
  public void
      test_setKeyEntryLjava_lang_StringLjava_security_Key$C$Ljava_security_cert_Certificate()
          throws Exception {

    // Test for method void
    // java.security.KeyStore.setKeyEntry(java.lang.String,
    // java.security.Key, char[], java.security.cert.Certificate[])

    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    X509Certificate cert[] = new X509Certificate[2];
    cert[0] = (X509Certificate) cf.generateCertificate(certArray);
    cert[1] = (X509Certificate) cf.generateCertificate(certArray2);
    KeyStore keyTest = KeyStore.getInstance(KeyStore.getDefaultType());

    try {
      keyTest.setKeyEntry("alias3", getPrivateKey(), pssWord, cert);
      fail();
    } catch (KeyStoreException expected) {
    }

    keyTest.load(null, null);

    keyTest.setKeyEntry("alias3", getPrivateKey(), pssWord, cert);
    assertTrue(
        "the entry specified by the alias alias3 is not a keyEntry", keyTest.isKeyEntry("alias3"));

    try {
      keyTest.setKeyEntry("alias4", getPrivateKey(), pssWord, new Certificate[] {});
      fail();
    } catch (IllegalArgumentException expected) {
    }
  }
  /**
   * java.security.KeyStore#setCertificateEntry(java.lang.String, java.security.cert.Certificate)
   */
  public void test_setCertificateEntryLjava_lang_StringLjava_security_cert_Certificate()
      throws Exception {
    // Test for method void
    // java.security.KeyStore.setCertificateEntry(java.lang.String,
    // java.security.cert.Certificate)
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    X509Certificate cert = (X509Certificate) cf.generateCertificate(certArray);
    KeyStore keyTest = KeyStore.getInstance(KeyStore.getDefaultType());

    try {
      keyTest.setCertificateEntry("alias", cert);
      fail();
    } catch (KeyStoreException expected) {
    }

    keyTest.load(null, null);

    PublicKey pub = cert.getPublicKey();
    keyTest.setCertificateEntry("alias1", cert);
    assertTrue(
        "the entry specified by the alias alias1 is not a certificate",
        keyTest.isCertificateEntry("alias1"));
    Certificate resultCert = keyTest.getCertificate("alias1");
    assertEquals(
        "the public key of the certificate from getCertificate() "
            + "did not equal the original certificate",
        pub,
        resultCert.getPublicKey());
  }
Exemple #10
0
  public static boolean verifySign(String certName, String base64Sign, String src) {
    boolean b = false;
    try {
      InputStream is = new FileInputStream(certName);
      CertificateFactory cf = CertificateFactory.getInstance("x509");
      Certificate cerCert = cf.generateCertificate(is);
      PublicKey publicKey = cerCert.getPublicKey();

      BASE64Decoder de = new BASE64Decoder();
      String tmp = base64Sign.replaceAll(" ", "+");
      byte[] byteSign = de.decodeBuffer(tmp);
      byte[] oldMD5 = rsaDecrypt(publicKey, byteSign);
      byte[] newMD5 = UnionPayMd5.MD5(src);
      if (oldMD5.length == newMD5.length) {
        int i = 0;
        for (i = 0; i < oldMD5.length; i++) {
          if (oldMD5[i] == newMD5[i]) {
            System.out.println("123");
            continue;
          } else {
            break;
          }
        }
        if (i == oldMD5.length) {
          b = true;
        }
      }
      return b;
    } catch (Exception e) {
      e.printStackTrace();
      return b;
    }
  }
  @Override
  public Component preview() {
    final Label commonNameLabel = new Label("certCommonName", new Model<String>());
    final ByteArrayInputStream certificateStream = new ByteArrayInputStream(uploadedBytes);
    try {
      final X509Certificate certificate =
          (X509Certificate)
              CertificateFactory.getInstance("X.509").generateCertificate(certificateStream);

      final StringBuilder commonNameBuilder = new StringBuilder("cn=");

      final LdapName ldapName = new LdapName(certificate.getIssuerDN().getName());

      for (Rdn rdn : ldapName.getRdns()) {
        if ("CN".equalsIgnoreCase(rdn.getType())) {
          commonNameBuilder.append(
              rdn.getValue() == null ? StringUtils.EMPTY : rdn.getValue().toString());
        }
      }
      commonNameLabel.setDefaultModelObject(commonNameBuilder.toString());
    } catch (Exception e) {
      LOG.error("Error evaluating certificate file", e);
      throw new IllegalArgumentException("Error evaluating certificate file", e);
    } finally {
      IOUtils.closeQuietly(certificateStream);
    }
    return this.add(commonNameLabel);
  }
  /**
   * Parse a PKIPATH format CertPath from an InputStream. Return an unmodifiable List of the
   * certificates.
   *
   * @param is the <code>InputStream</code> to read the data from
   * @return an unmodifiable List of the certificates
   * @exception CertificateException if an exception occurs
   */
  private static List<X509Certificate> parsePKIPATH(InputStream is) throws CertificateException {
    List<X509Certificate> certList = null;
    CertificateFactory certFac = null;

    if (is == null) {
      throw new CertificateException("input stream is null");
    }

    try {
      DerInputStream dis = new DerInputStream(readAllBytes(is));
      DerValue[] seq = dis.getSequence(3);
      if (seq.length == 0) {
        return Collections.<X509Certificate>emptyList();
      }

      certFac = CertificateFactory.getInstance("X.509");
      certList = new ArrayList<X509Certificate>(seq.length);

      // append certs in reverse order (target to trust anchor)
      for (int i = seq.length - 1; i >= 0; i--) {
        certList.add(
            (X509Certificate)
                certFac.generateCertificate(new ByteArrayInputStream(seq[i].toByteArray())));
      }

      return Collections.unmodifiableList(certList);

    } catch (IOException ioe) {
      throw new CertificateException("IOException parsing PkiPath data: " + ioe, ioe);
    }
  }
Exemple #13
0
  public static void main(String args[]) throws Exception {
    // 参数
    String cacert = args[0];
    String lfcert = args[1];
    // CA "Xu Yingxiao"的证书
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    FileInputStream in1 = new FileInputStream(cacert);
    java.security.cert.Certificate cac = cf.generateCertificate(in1);
    in1.close();
    // 用户"Liu Fang"的签名证书
    FileInputStream in2 = new FileInputStream(lfcert);
    java.security.cert.Certificate lfc = cf.generateCertificate(in2);
    in2.close();

    PublicKey pbk = cac.getPublicKey();
    boolean pass = false;
    try {
      lfc.verify(pbk);
      pass = true;
    } catch (Exception e) {
      pass = false;
      System.out.println(e);
    }
    if (pass) {
      System.out.println("The Certificate is signed by the CA Xu Yingxiao");
    } else {
      System.out.println("!!!The Certificate is not signed by the CA Xu Yingxiao");
    }
  }
  /**
   * HttpUrlConnection 方式,支持指定load-der.crt证书验证,此种方式Android官方建议
   *
   * @throws CertificateException
   * @throws IOException
   * @throws KeyStoreException
   * @throws NoSuchAlgorithmException
   * @throws KeyManagementException
   */
  public void initSSL()
      throws CertificateException, IOException, KeyStoreException, NoSuchAlgorithmException,
          KeyManagementException {
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    InputStream in = getAssets().open("load-der.crt");
    Certificate ca = cf.generateCertificate(in);

    KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
    keystore.load(null, null);
    keystore.setCertificateEntry("ca", ca);

    String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
    TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
    tmf.init(keystore);

    // Create an SSLContext that uses our TrustManager
    SSLContext context = SSLContext.getInstance("TLS");
    context.init(null, tmf.getTrustManagers(), null);
    URL url = new URL("https://trade3.guosen.com.cn/mtrade/check_version");
    HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
    urlConnection.setSSLSocketFactory(context.getSocketFactory());
    InputStream input = urlConnection.getInputStream();

    BufferedReader reader = new BufferedReader(new InputStreamReader(input, "UTF-8"));
    StringBuffer result = new StringBuffer();
    String line = "";
    while ((line = reader.readLine()) != null) {
      result.append(line);
    }
    Log.e("TTTT", result.toString());
  }
  /**
   * Gets a KeyStore containing the Certificate
   *
   * @param cert InputStream of the Certificate
   * @return KeyStore
   */
  public static KeyStore getKeystoreOfCA(InputStream cert) {

    // Load CAs from an InputStream
    InputStream caInput = null;
    Certificate ca = null;
    try {
      CertificateFactory cf = CertificateFactory.getInstance("X.509");
      caInput = new BufferedInputStream(cert);
      ca = cf.generateCertificate(caInput);
    } catch (CertificateException e1) {
      e1.printStackTrace();
    } finally {
      try {
        if (caInput != null) {
          caInput.close();
        }
      } catch (IOException e) {
        e.printStackTrace();
      }
    }

    // Create a KeyStore containing our trusted CAs
    String keyStoreType = KeyStore.getDefaultType();
    KeyStore keyStore = null;
    try {
      keyStore = KeyStore.getInstance(keyStoreType);
      keyStore.load(null, null);
      keyStore.setCertificateEntry("ca", ca);
    } catch (Exception e) {
      e.printStackTrace();
    }
    return keyStore;
  }
Exemple #16
0
  /**
   * Callback method from _scanKeychain. If a trusted certificate is found, this method will be
   * called.
   */
  private void createTrustedCertEntry(
      String alias, long keychainItemRef, long creationDate, byte[] derStream) {
    TrustedCertEntry tce = new TrustedCertEntry();

    try {
      CertificateFactory cf = CertificateFactory.getInstance("X.509");
      InputStream input = new ByteArrayInputStream(derStream);
      X509Certificate cert = (X509Certificate) cf.generateCertificate(input);
      input.close();
      tce.cert = cert;
      tce.certRef = keychainItemRef;

      // Make a creation date.
      if (creationDate != 0) tce.date = new Date(creationDate);
      else tce.date = new Date();

      int uniqueVal = 1;
      String originalAlias = alias;

      while (entries.containsKey(alias.toLowerCase())) {
        alias = originalAlias + " " + uniqueVal;
        uniqueVal++;
      }

      entries.put(alias.toLowerCase(), tce);
    } catch (Exception e) {
      // The certificate will be skipped.
      System.err.println("KeychainStore Ignored Exception: " + e);
    }
  }
  /** Load the collection of CRLs. */
  protected Collection<? extends CRL> getCRLs(String crlf)
      throws IOException, CRLException, CertificateException {

    File crlFile = new File(crlf);
    if (!crlFile.isAbsolute()) {
      crlFile = new File(System.getProperty("catalina.base"), crlf);
    }
    Collection<? extends CRL> crls = null;
    InputStream is = null;
    try {
      CertificateFactory cf = CertificateFactory.getInstance("X.509");
      is = new FileInputStream(crlFile);
      crls = cf.generateCRLs(is);
    } catch (IOException iex) {
      throw iex;
    } catch (CRLException crle) {
      throw crle;
    } catch (CertificateException ce) {
      throw ce;
    } finally {
      if (is != null) {
        try {
          is.close();
        } catch (Exception ex) {
        }
      }
    }

    return crls;
  }
 private X509CRL decode(byte[] encoded) throws CertificateException, IOException, CRLException {
   InputStream inStream = new ByteArrayInputStream(encoded);
   CertificateFactory cf = CertificateFactory.getInstance("X.509"); // $NON-NLS-1$
   X509CRL crl = (X509CRL) cf.generateCRL(inStream);
   inStream.close();
   return crl;
 }
  public void addNewKey(String alias, Iterator<FileItem> uploadedFilesIterator) throws Exception {
    PrivateKey privateKey = null;
    Certificate[] certs = null;
    while (uploadedFilesIterator.hasNext()) {
      FileItem fileItem = uploadedFilesIterator.next();
      if (!fileItem.isFormField()) {
        if ("keyFile".equals(fileItem.getFieldName())) {
          KeyFactory kf = KeyFactory.getInstance("RSA");
          privateKey = kf.generatePrivate(new PKCS8EncodedKeySpec(fileItem.get()));
        }
        if ("certFile".equals(fileItem.getFieldName())) {
          CertificateFactory cf = CertificateFactory.getInstance("X.509");
          certs = cf.generateCertificates(fileItem.getInputStream()).toArray(new Certificate[] {});
        }
      }
    }

    if (privateKey == null || certs == null) {
      throw new WebApplicationException(
          Response.ok("<pre>Can't find input file.</pre>", MediaType.TEXT_HTML).build());
    }

    keystore.setKeyEntry(alias, privateKey, keyStorePassword.toCharArray(), certs);
    save();
  }
  /**
   * Adds a new entry to the Java key store, using the GFIPM entity id as the key store alias and
   * using the filename for source of the trusted certificate. Writes out an error messages on an
   * exception.
   *
   * @param entityid The GFIPM entity to be added
   * @param filename The file from where the trusted certificate should be read.
   * @return true on success, false otherwise.
   */
  public boolean addNewEntryFromFile(String entityid, String filename) {
    String alias = makeEntityAliasName(entityid);
    if (alias == null) {
      System.err.println("ERROR: GFIPMKeystore.addNewEntryFromFile: No alias name. Aborted.");
      System.err.flush();
      return false;
    }

    try {

      // Source:
      // http://download.oracle.com/javase/1.5.0/docs/api/java/security/cert/X509Certificate.html
      InputStream inStream = new FileInputStream(filename);
      CertificateFactory cf = CertificateFactory.getInstance("X.509");
      X509Certificate cert = (X509Certificate) cf.generateCertificate(inStream);
      inStream.close();

      if (verboseOut) {
        System.out.println("Key Store: add new entry " + alias);
        System.out.flush();
      }
      keyStore.setCertificateEntry(alias, cert);
      modifiedFlag = true;

    } catch (Exception e) {
      System.err.println("ERROR: GFIPMKeystore.addNewEntryFromFile failed: ");
      System.err.println(e.toString());
      System.err.flush();
      return false;
    }

    return true;
  } // end addNewEntryFromFile
  /** java.security.KeyStore#containsAlias(java.lang.String) */
  public void test_containsAliasLjava_lang_String() throws Exception {
    // Test for method boolean
    // java.security.KeyStore.containsAlias(java.lang.String)
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    X509Certificate cert[] = new X509Certificate[2];
    cert[0] = (X509Certificate) cf.generateCertificate(certArray);
    cert[1] = (X509Certificate) cf.generateCertificate(certArray2);
    KeyStore keyTest = KeyStore.getInstance(KeyStore.getDefaultType());

    try {
      keyTest.containsAlias("alias1");
      fail();
    } catch (KeyStoreException expected) {
    }

    keyTest.load(null, null);

    // alias 1
    keyTest.setCertificateEntry("alias1", cert[0]);

    // alias 2
    keyTest.setCertificateEntry("alias2", cert[0]);

    assertTrue("alias1 does not exist", keyTest.containsAlias("alias1"));
    assertTrue("alias2 does not exist", keyTest.containsAlias("alias2"));
    assertFalse("alias3 exists", keyTest.containsAlias("alias3"));

    try {
      keyTest.containsAlias(null);
      fail();
    } catch (NullPointerException expected) {
    }
  }
 MyX509TrustManager() throws java.security.GeneralSecurityException {
   TrustManagerFactory tmf = TrustManagerFactory.getInstance("PKIX");
   KeyStore ks = KeyStore.getInstance("JKS");
   CertificateFactory cf = CertificateFactory.getInstance("X.509");
   try {
     ks.load(null, null);
     File cacert = new File(cafile);
     if (!cacert.exists() || !cacert.canRead()) return;
     InputStream caStream = new FileInputStream(cafile);
     X509Certificate ca = (X509Certificate) cf.generateCertificate(caStream);
     ks.setCertificateEntry("CA", ca);
     PKIXBuilderParameters params = new PKIXBuilderParameters(ks, new X509CertSelector());
     File crlcert = new File(crlfile);
     if (!crlcert.exists() || !crlcert.canRead()) {
       params.setRevocationEnabled(false);
     } else {
       InputStream crlStream = new FileInputStream(crlfile);
       Collection<? extends CRL> crls = cf.generateCRLs(crlStream);
       CertStoreParameters csp = new CollectionCertStoreParameters(crls);
       CertStore store = CertStore.getInstance("Collection", csp);
       params.addCertStore(store);
       params.setRevocationEnabled(true);
     }
     tmf.init(new CertPathTrustManagerParameters(params));
   } catch (java.io.FileNotFoundException e) {
     vlog.error(e.toString());
   } catch (java.io.IOException e) {
     vlog.error(e.toString());
   }
   tm = (X509TrustManager) tmf.getTrustManagers()[0];
 }
  @SuppressWarnings("unchecked")
  private X509Certificate[] parseX509CertificateChain(InputStream is) throws CertificateException {
    X509Certificate[] certificateChain;
    CertificateFactory cf;
    Collection certificateChainCollection;
    Iterator chainIterator;

    certificateChain = null;
    cf = null;
    certificateChainCollection = null;
    chainIterator = null;

    // Instantiate X509 certificate factory
    cf = CertificateFactory.getInstance("X509");

    // Parse X509 certificate chain
    certificateChainCollection = cf.generateCertificates(is);

    // Instantiate array to hold X509 certificate chain
    certificateChain = new X509Certificate[certificateChainCollection.size()];

    // Get iterator over X509 certificate chain
    chainIterator = certificateChainCollection.iterator();

    // Work through each X509 certificate in certificate chain collection
    for (int i = 0; i < certificateChain.length; i++) {
      // Copy next X509 certificate from collection to array
      certificateChain[i] = (X509Certificate) chainIterator.next();
    }

    return certificateChain;
  }
  /** java.security.KeyStore#getCertificate(java.lang.String) */
  public void test_getCertificateLjava_lang_String() throws Exception {
    // Test for method java.security.cert.Certificate
    // java.security.KeyStore.getCertificate(java.lang.String)
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    X509Certificate cert[] = new X509Certificate[2];
    cert[0] = (X509Certificate) cf.generateCertificate(certArray);
    cert[1] = (X509Certificate) cf.generateCertificate(certArray2);
    KeyStore keyTest = KeyStore.getInstance(KeyStore.getDefaultType());

    try {
      keyTest.getCertificate("anAlias");
      fail();
    } catch (KeyStoreException expected) {
    }

    keyTest.load(null, null);

    // alias 1
    PublicKey pub = cert[0].getPublicKey();
    keyTest.setCertificateEntry("alias1", cert[0]);

    Certificate certRes = keyTest.getCertificate("alias1");
    assertEquals(
        "the public key of the certificate from getCertificate() "
            + "did not equal the original certificate",
        pub,
        certRes.getPublicKey());

    // alias 2
    keyTest.setCertificateEntry("alias2", cert[0]);

    // testing for a certificate chain
    Certificate cert2 = keyTest.getCertificate("alias2");
    assertEquals("the certificate for alias2 is supposed to exist", cert2, cert[0]);
  }
  private void checkPolicyProcessingAtDomainMatch() throws Exception {
    CertificateFactory cf = CertificateFactory.getInstance("X.509", "BC");

    X509Certificate root =
        (X509Certificate)
            cf.generateCertificate(this.getClass().getResourceAsStream("qvRooCa3.crt"));
    X509Certificate ca1 =
        (X509Certificate)
            cf.generateCertificate(this.getClass().getResourceAsStream("suvaRoot1.crt"));
    X509Certificate ca2 =
        (X509Certificate)
            cf.generateCertificate(this.getClass().getResourceAsStream("suvaEmail1.crt"));
    X509Certificate ee =
        (X509Certificate) cf.generateCertificate(this.getClass().getResourceAsStream("suvaEE.crt"));

    List certchain = new ArrayList();
    certchain.add(ee);
    certchain.add(ca2);
    certchain.add(ca1);

    Set trust = new HashSet();
    trust.add(new TrustAnchor(root, null));

    CertPathValidator cpv = CertPathValidator.getInstance("PKIX", "BC");
    PKIXParameters param = new PKIXParameters(trust);
    param.setRevocationEnabled(false);
    param.setDate(new Date(0x156445410b4L)); // around 1st August 2016

    CertPath cp = cf.generateCertPath(certchain);

    MyChecker checker = new MyChecker();
    param.addCertPathChecker(checker);

    PKIXCertPathValidatorResult result = (PKIXCertPathValidatorResult) cpv.validate(cp, param);
  }
  /** java.security.KeyStore#getCertificateAlias(java.security.cert.Certificate) */
  public void test_getCertificateAliasLjava_security_cert_Certificate() throws Exception {
    // Test for method java.lang.String
    // java.security.KeyStore.getCertificateAlias(java.security.cert.Certificate)
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    X509Certificate cert[] = new X509Certificate[2];
    cert[0] = (X509Certificate) cf.generateCertificate(certArray);
    cert[1] = (X509Certificate) cf.generateCertificate(certArray2);
    KeyStore keyTest = KeyStore.getInstance(KeyStore.getDefaultType());
    keyTest.load(null, null);

    // certificate entry
    keyTest.setCertificateEntry("alias1", cert[1]);
    String alias = keyTest.getCertificateAlias(cert[1]);
    assertEquals(
        "certificate entry - the alias returned for this certificate was wrong", "alias1", alias);

    // key entry

    keyTest.setKeyEntry("alias2", getPrivateKey(), pssWord, cert);
    alias = keyTest.getCertificateAlias(cert[0]);
    assertEquals("key entry - the alias returned for this certificate was wrong", "alias2", alias);

    // testing case with a nonexistent certificate
    X509Certificate cert2 = (X509Certificate) cf.generateCertificate(certArray3);
    String aliasNull = keyTest.getCertificateAlias(cert2);
    assertNull("the alias returned for the nonexist certificate was NOT null", aliasNull);
  }
  /** java.security.KeyStore#getKey(java.lang.String, char[]) */
  public void test_getKeyLjava_lang_String$C() throws Exception {

    // Test for method java.security.Key
    // java.security.KeyStore.getKey(java.lang.String, char[])
    // creatCertificate();
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    X509Certificate cert[] = new X509Certificate[2];
    cert[0] = (X509Certificate) cf.generateCertificate(certArray);
    cert[1] = (X509Certificate) cf.generateCertificate(certArray2);
    KeyStore keyTest = KeyStore.getInstance(KeyStore.getDefaultType());
    keyTest.load(null, null);

    keyTest.setKeyEntry("alias2", getPrivateKey(), pssWord, cert);
    PrivateKey returnedKey = (PrivateKey) keyTest.getKey("alias2", pssWord);
    byte[] retB = returnedKey.getEncoded();
    byte[] priB = getPrivateKey().getEncoded();
    assertTrue(Arrays.equals(retB, priB));
    assertEquals(getPrivateKey().getAlgorithm(), returnedKey.getAlgorithm());
    assertEquals(getPrivateKey().getFormat(), returnedKey.getFormat());

    try {
      keyTest.getKey("alias2", "wrong".toCharArray());
      fail();
    } catch (UnrecoverableKeyException expected) {
    }

    keyTest.setCertificateEntry("alias1", cert[1]);
    assertNull(
        "the private key returned from getKey for a certificate entry is not null",
        keyTest.getKey("alias1", pssWord));
  }
  /** java.security.KeyStore#isKeyEntry(java.lang.String) */
  public void test_isKeyEntryLjava_lang_String() throws Exception {
    // Test for method boolean
    // java.security.KeyStore.isKeyEntry(java.lang.String)
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    X509Certificate cert[] = new X509Certificate[2];
    cert[0] = (X509Certificate) cf.generateCertificate(certArray);
    cert[1] = (X509Certificate) cf.generateCertificate(certArray2);
    KeyStore keyTest = KeyStore.getInstance(KeyStore.getDefaultType());

    try {
      keyTest.isKeyEntry("alias");
      fail();
    } catch (KeyStoreException expected) {
    }

    keyTest.load(null, null);
    // alias 1
    keyTest.setCertificateEntry("alias1", cert[0]);

    // alias 2
    keyTest.setKeyEntry("alias2", getPrivateKey(), pssWord, cert);

    assertTrue("isKeyEntry method returns false for a certificate", keyTest.isKeyEntry("alias2"));
    assertFalse("isKeyEntry method returns true for noncertificate", keyTest.isKeyEntry("alias1"));
  }
Exemple #29
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();
    }
  }
  public static void main(String[] args) throws Exception {
    // create the keys
    KeyPair pair = Utils.generateRSAKeyPair();

    // create the input stream
    ByteArrayOutputStream bOut = new ByteArrayOutputStream();

    if (outputFormat.equals(DER)) {
      bOut.write(X509V1CreateExample.generateV1Certificate(pair).getEncoded());
    } else if (outputFormat.equals(PEM)) {
      PEMWriter pemWriter = new PEMWriter(new OutputStreamWriter(bOut));
      pemWriter.writeObject(X509V1CreateExample.generateV1Certificate(pair));
      pemWriter.close();
    }

    bOut.close();

    // Print the contents of bOut

    System.out.println(outputFormat.equals(DER) ? "DER-format:" : "PEM-format:");

    System.out.println(Utils.toString(bOut.toByteArray()));

    InputStream in = new ByteArrayInputStream(bOut.toByteArray());

    // create the certificate factory
    CertificateFactory fact = CertificateFactory.getInstance("X.509", "BC");

    // read the certificate
    X509Certificate x509Cert = (X509Certificate) fact.generateCertificate(in);

    System.out.println("issuer: " + x509Cert.getIssuerX500Principal());
  }