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();
 }
Exemplo n.º 2
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#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]);
  }
  /** 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#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);
  }
Exemplo n.º 6
0
  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);
  }
  /** 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"));
  }
  /**
   * 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#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());
  }
Exemplo n.º 10
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");
    }
  }
Exemplo n.º 11
0
  /** 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) {
    }
  }
  public static SSLSocketFactory getSocketFactory(
      String caCrtFile, String crtFile, String keyFile, String password) throws Exception {

    char[] passwordCharArray = password == null ? new char[0] : password.toCharArray();

    Security.addProvider(new BouncyCastleProvider());
    CertificateFactory cf = CertificateFactory.getInstance("X.509");

    X509Certificate caCert =
        (X509Certificate)
            cf.generateCertificate(
                new ByteArrayInputStream(Files.readAllBytes(Paths.get(caCrtFile))));

    X509Certificate cert =
        (X509Certificate)
            cf.generateCertificate(
                new ByteArrayInputStream(Files.readAllBytes(Paths.get(crtFile))));

    File privateKeyFile = new File(keyFile);
    PEMParser pemParser = new PEMParser(new FileReader(privateKeyFile));
    PEMDecryptorProvider decProv = new JcePEMDecryptorProviderBuilder().build(passwordCharArray);
    JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider("BC");

    Object object = pemParser.readObject();
    KeyPair kp;

    if (object instanceof PEMEncryptedKeyPair) {
      kp = converter.getKeyPair(((PEMEncryptedKeyPair) object).decryptKeyPair(decProv));
    } else {
      kp = converter.getKeyPair((PEMKeyPair) object);
    }

    pemParser.close();

    KeyStore caKeyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    caKeyStore.load(null, null);
    caKeyStore.setCertificateEntry("ca-certificate", caCert);
    TrustManagerFactory trustManagerFactory =
        TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(caKeyStore);

    KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
    keyStore.load(null, null);
    keyStore.setCertificateEntry("certificate", cert);
    keyStore.setKeyEntry(
        "private-key",
        kp.getPrivate(),
        passwordCharArray,
        new java.security.cert.Certificate[] {cert});
    KeyManagerFactory keyManagerFactory =
        KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    keyManagerFactory.init(keyStore, passwordCharArray);

    SSLContext context = SSLContext.getInstance("TLSv1");
    context.init(keyManagerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null);

    return context.getSocketFactory();
  }
Exemplo n.º 13
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
    }
  }
Exemplo n.º 14
0
  private DockerCertificates(final Builder builder) throws DockerCertificateException {
    if ((builder.caCertPath == null)
        || (builder.clientCertPath == null)
        || (builder.clientKeyPath == null)) {
      throw new DockerCertificateException(
          "caCertPath, clientCertPath, and clientKeyPath must all be specified");
    }

    try {
      final CertificateFactory cf = CertificateFactory.getInstance("X.509");
      final Certificate caCert = cf.generateCertificate(Files.newInputStream(builder.caCertPath));
      final Certificate clientCert =
          cf.generateCertificate(Files.newInputStream(builder.clientCertPath));

      final PEMKeyPair clientKeyPair =
          (PEMKeyPair)
              new PEMParser(
                      Files.newBufferedReader(builder.clientKeyPath, Charset.defaultCharset()))
                  .readObject();

      final PKCS8EncodedKeySpec spec =
          new PKCS8EncodedKeySpec(clientKeyPair.getPrivateKeyInfo().getEncoded());
      final KeyFactory kf = KeyFactory.getInstance("RSA");
      final PrivateKey clientKey = kf.generatePrivate(spec);

      final KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
      trustStore.load(null, null);
      trustStore.setEntry("ca", new KeyStore.TrustedCertificateEntry(caCert), null);

      final KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
      keyStore.load(null, null);
      keyStore.setCertificateEntry("client", clientCert);
      keyStore.setKeyEntry("key", clientKey, KEY_STORE_PASSWORD, new Certificate[] {clientCert});

      this.sslContext =
          SSLContexts.custom()
              .loadTrustMaterial(trustStore)
              .loadKeyMaterial(keyStore, KEY_STORE_PASSWORD)
              .useTLS()
              .build();
    } catch (CertificateException
        | IOException
        | NoSuchAlgorithmException
        | InvalidKeySpecException
        | KeyStoreException
        | UnrecoverableKeyException
        | KeyManagementException e) {
      throw new DockerCertificateException(e);
    }
  }
Exemplo n.º 15
0
  @Test
  public void testDisplayName() throws Exception {
    CertificateFactory cf = CertificateFactory.getInstance("X.509");

    X509Certificate clientCert =
        (X509Certificate)
            cf.generateCertificate(getClass().getResourceAsStream("startssl-client.crt"));
    assertEquals("Andreas Schildbach", X509Utils.getDisplayNameFromCertificate(clientCert, false));

    X509Certificate comodoCert =
        (X509Certificate)
            cf.generateCertificate(getClass().getResourceAsStream("comodo-smime.crt"));
    assertEquals(
        "*****@*****.**", X509Utils.getDisplayNameFromCertificate(comodoCert, true));
  }
Exemplo n.º 16
0
 /**
  * 获取CA证书信息
  *
  * @param cafile CA证书文件
  * @return Certificate
  * @throws CertificateException
  * @throws IOException
  */
 public static Certificate getCertificate(File cafile) throws CertificateException, IOException {
   CertificateFactory cf = CertificateFactory.getInstance("X.509");
   FileInputStream in = new FileInputStream(cafile);
   Certificate cert = cf.generateCertificate(in);
   in.close();
   return cert;
 }
Exemplo n.º 17
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;
    }
  }
Exemplo n.º 18
0
  /**
   * 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());
  }
Exemplo n.º 19
0
  /**
   * 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
Exemplo n.º 20
0
  /**
   * @param certBuf
   * @return certificate chain
   * @throws CertificateException
   * @throws IOException
   */
  public static X509Certificate[] readCertificateChain(byte[] certBuf)
      throws CertificateException, IOException {
    BufferedInputStream istream = new BufferedInputStream(new ByteArrayInputStream(certBuf));
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    ArrayList<Certificate> certs = new ArrayList<Certificate>();
    while (istream.available() > 0) {
      Certificate cert = cf.generateCertificate(istream);
      // log.debug("found: " + cert);
      certs.add(cert);
    }
    istream.close();

    X509Certificate[] chain = new X509Certificate[certs.size()];
    Iterator<Certificate> i = certs.iterator();
    int c = 0;
    while (i.hasNext()) {
      X509Certificate x509 = (X509Certificate) i.next();
      chain[c++] = x509;
      try {
        x509.checkValidity();
        log.debug("X509 certificate is valid");
      } catch (CertificateExpiredException exp) {
        log.debug("X509 certificate is expired");
        // nothing to be done here
      } catch (CertificateException ex) {
        throw new RuntimeException("certificate byte array is not valid", ex);
      }
    }
    return chain;
  }
Exemplo n.º 21
0
  /**
   * 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());
  }
Exemplo n.º 22
0
 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];
 }
Exemplo n.º 23
0
  /**
   * 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);
    }
  }
Exemplo n.º 24
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);
    }
  }
Exemplo n.º 25
0
  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");
      }
    }
  }
Exemplo n.º 26
0
  /**
   * 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;
  }
  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());
  }
Exemplo n.º 28
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();
    }
  }
Exemplo n.º 29
0
 private List<X509Certificate> findCerts(File folder, String username) {
   List<X509Certificate> list = new ArrayList<X509Certificate>();
   File userFolder = new File(folder, X509Utils.CERTS + File.separator + username);
   if (!userFolder.exists()) {
     return list;
   }
   File[] certs =
       userFolder.listFiles(
           new FilenameFilter() {
             @Override
             public boolean accept(File dir, String name) {
               return name.toLowerCase().endsWith(".cer") || name.toLowerCase().endsWith(".crt");
             }
           });
   try {
     CertificateFactory factory = CertificateFactory.getInstance("X.509");
     for (File cert : certs) {
       BufferedInputStream is = new BufferedInputStream(new FileInputStream(cert));
       X509Certificate x509 = (X509Certificate) factory.generateCertificate(is);
       is.close();
       list.add(x509);
     }
   } catch (Exception e) {
     Utils.showException(GitblitAuthority.this, e);
   }
   return list;
 }
Exemplo n.º 30
0
  @Test
  public void testHandleInternal() throws CertificateException {
    final CertificateFactory cf = CertificateFactory.getInstance("X.509");
    U2FReceiverInterface receiver = mock(U2FReceiverInterface.class);
    Module actor = mock(Module.class);
    String version = "U2F_V2";
    byte[] clientParam =
        BaseEncoding.base64Url().decode("MUmwdr0pxe9YsU-P78JNG7s0CNpL8Q41kM7vLWxh6_I=");
    byte[] appParam =
        BaseEncoding.base64Url().decode("shPs6qCuWEVuIMbYe7LP6YJTAsuNm52zDg8ivpfq3P8=");
    byte[] encodedRandom =
        BaseEncoding.base64()
            .decode(
                "2KmIHW8wLzt/eW0Awry1NvfYV9pJVYhERjKwCzkSPG7KYFZScRV8h1z02DELcVhkEDAYFemMKLe+lPQFF2iyqaEsbCBYqLVx82FU8uuktcE+ZFAXyMjprN1jOoARJNRHvd1+nBYkn/plZFUW1X236U1izs0c7xf/4VWPuwI/m5BSyBmY/YKaIQdpGwToCYdcD/5NjaI76mTlHDWNt4f9Ug==");
    byte[] encodedKey =
        BaseEncoding.base64()
            .decode(
                "MIIQ3gIBATEPMA0GCWCGSAFlAwQCAQUAMIILggYJKoZIhvcNAQcBoIILcwSCC28wggtrBgsqhkiG9w0BCRABF6CCC1owggtWAgEAMYIBZzCCAWMCAQAwSzBAMSIwIAYDVQQDExlJQUlLIFRlc3QgSW50ZXJtZWRpYXRlIENBMQ0wCwYDVQQKEwRJQUlLMQswCQYDVQQGEwJBVAIHARTz1EoFiDANBgkqhkiG9w0BAQEFAASCAQAJhWfH6gMHOJFUBKA5FZ9HaVFq4CRkriSH0VyQh2KBA2p/UyKOcMDfeQBcjPAWoipFGDptaR8trt+Lb3m/IVRGnZmfPXEQG6amq3LLV95Yf5BTm07wvo5WiTk2E37PcOpDVMuDfxHjrkg51HszvgKmdOcY4RZRqMvkvwFg60oF5tkE9g0Ye8jUU1Gw3I3xg7mJFJVMGmGgSPGD/HcJWD02BnDg7cLx51720WEXQJoXvCRKMoLhiZmQMBj0ZS0hv2vrgRKtP2T46GV9IkG7CGnxI/XZEYMC9dcImfExc+8uLIH2VkReGEirOeIAjnkWDCMPpNT0SiHzbetN3cYymUAtMIIJ1gYJKoZIhvcNAQcBMB4GCWCGSAFlAwQBLjARBAz5c22QMgAC6l3t8LMCAQyAggmndke4BF6HQ9gq1QFgpcrQSDjHzn5AXnjZ9cz91ELCypw83gytkTATgKEVRJ6WLIEVFPfVV3H6rnXcHFYkIYX4OnicuxblmIJt8SdGvS+TZdn5BaVJEedLcqgyQ5cXIOpUgmqTd5Bm2GVqDIxBOXb1lxKAXJY89SPENR84cPW+f64Cdb/Ogpbj0QkXjuEdLHJpEISj+Y9M97ofg/1qpKmeRQrxrYbdMedpyvwXIscszFDU1zl97DY2WhXX1mb8nD+lCxbQGjkTdSIi1WgLCsLRL4xV6nkQ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BglghkgBZQMEAgEFAKBpMBgGCSqGSIb3DQEJAzELBgkqhkiG9w0BBwEwHAYJKoZIhvcNAQkFMQ8XDTE1MTIwMzEyMjMzOFowLwYJKoZIhvcNAQkEMSIEIP4e/ZL5mxGSoXVk2ctkTtAgdxyGKSIB5eNiscVgPNHiMA0GCSqGSIb3DQEBAQUABIIBAJxFPi7OZ4FUK673XueLow4TB/Ji+7wtq6lfcJFregY96adYxHOMWlpvyNLzyIWJxV1SczHVatti4BGMWiGM1OJU4IXRzuojGVRzmL9CcDsUU1amokYqS//98SnzDMW4obNLqq0xKtawrSo/Hl1/eVbBYilLmtPaMszQ+cl0xQ5ReTybeKC08O6pTfwLx47YiretEoVwgpagVC2tdGN/UqM/KX+saox5NJIzhx+8UP5BdG35mMCa71fs5dxKQKYTxaKHK3w+Sq7mwKaxopgioJ4x4w9fq8+qdEYQWUaBTJiIVfBbJXdVkPD4xOnUFIbfxHqXn9DQHhAqQb0Ex3zt4Fo=");
    X509Certificate encodedCert =
        (X509Certificate)
            cf.generateCertificate(
                new ByteArrayInputStream(
                    BaseEncoding.base64()
                        .decode(
                            "MIICqDCCAZACIHCy6N/T8VQ8XOlp3EBkT9D1uw3uXMpuaIuwyYVtYdPRMA0GCSqGSIb3DQEBCwUAMIHMMQswCQYDVQQGEwJBVDENMAsGA1UEBxMER3JhejEmMCQGA1UEChMdR3JheiBVbml2ZXJzaXR5IG9mIFRlY2hub2xvZ3kxSDBGBgNVBAsTP0luc3RpdHV0ZSBmb3IgQXBwbGllZCBJbmZvcm1hdGlvbiBQcm9jZXNzaW5nIGFuZCBDb21tdW5pY2F0aW9uczESMBAGA1UEBBMJVGV1ZmwgRW5jMQ4wDAYDVQQqEwVQZXRlcjEYMBYGA1UEAxMPUGV0ZXIgVGV1ZmwgRW5jMB4XDTEzMDkwOTEwMzcxMloXDTIzMDkwOTEwMzcxMlowEzERMA8GA1UEAxMIU2t5VHJ1c3QwWTATBgcqhkjOPQIBBggqhkjOPQMBBwNCAAR+XOmSfxB8SU3A4PUmFB89awcIGnXLxBpnqHxltHLQg6evGeVhSmLqUDXYXKljHRpkITruRMVxlPZGREoTKFK8MA0GCSqGSIb3DQEBCwUAA4IBAQDC/ICTEa4sNE9paFCU8FJJ2o1eZ6Zzarx5jWtk6rd1KtB/jzQVvR/V4wq+3ItbEufdKh3HhHA2K9uEZm+Mu7t8FUaXFKAyksU2/PzI3kFUVsSoE7XiSuhyivUbT9xdWNTc4ZLJecrq5weJwkhoqLpW1ec1jGaFEpGMPlVGMJC8ANRGkc3ddeckAck8cdItR8wQ5ltEpiTklyoleIeTzu2kThl7mKc8CkqIiXcudNnKqY1USJ+Ns5jjLDStyy7+mLw45Y5p8U71Wmx2DEIkH/ExDWedMXIXdKvHD8BgTsbKNf70zZspwqMnDqThgi3Oio4VRWvKuszhmP++UZHoQobo")));
    byte[] hashToBeSigned =
        BaseEncoding.base64()
            .decode(
                "ALIT7OqgrlhFbiDG2Huyz+mCUwLLjZudsw4PIr6X6tz/MUmwdr0pxe9YsU+P78JNG7s0CNpL8Q41kM7vLWxh6/LYqYgdbzAvO395bQDCvLU299hX2klViERGMrALORI8bspgVlJxFXyHXPTYMQtxWGQQMBgV6Ywot76U9AUXaLKpoSxsIFiotXHzYVTy66S1wT5kUBfIyOms3WM6gBEk1Ee93X6cFiSf+mVkVRbVfbfpTWLOzRzvF//hVY+7Aj+bkFLIGZj9gpohB2kbBOgJh1wP/k2NojvqZOUcNY23h/1SBH5c6ZJ/EHxJTcDg9SYUHz1rBwgadcvEGmeofGW0ctCDp68Z5WFKYupQNdhcqWMdGmQhOu5ExXGU9kZEShMoUrw=");
    byte[] signedHash =
        BaseEncoding.base64()
            .decode(
                "MEUCICF+1fY8V/y5/kUw35/mnlSbZzs236wH3wsZQSfSiKnvAiEAyF/md0WTjq53G+t1h8HPaJlYmhoSP8Wej8R6bTUoFxw=");
    byte[] registrationData =
        BaseEncoding.base64Url()
            .decode(
                "BQR-XOmSfxB8SU3A4PUmFB89awcIG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VRIn42zmOMsNK3LLv6YvDjljmnxTvVabHYMQiQf8TENZ50xchd0q8cPwGBOxso1_vTNmynCoycOpOGCLc6KjhVFa8q6zOGY_75RkehChugwRQIgIX7V9jxX_Ln-RTDfn-aeVJtnOzbfrAffCxlBJ9KIqe8CIQDIX-Z3RZOOrncb63WHwc9omViaGhI_xZ6PxHptNSgXHA==");
    String u2fRawRequest =
        JsonUtils.toJson(new RegisterInternalRequest(appParam, clientParam, version));

    when(receiver.forwardRequest(
            argThat(new PayloadMatcher(PayloadGenerateU2FKeyRequest.class)), eq(actor)))
        .thenReturn(createGenerateKeyResponse(encodedRandom, encodedKey, encodedCert));
    when(receiver.forwardRequest(argThat(new PayloadMatcher(PayloadSignRequest.class)), eq(actor)))
        .thenReturn(createSignResponse(signedHash));

    RegisterInternalResponse response =
        JsonUtils.fromJson(
            new RegisterInternalHandler(crysilForwarder).handle(u2fRawRequest, actor, receiver),
            RegisterInternalResponse.class);

    verify(crysilForwarder)
        .executeGenerateWrappedKey(
            eq(clientParam), eq(appParam), isNull(byte[].class), eq(actor), eq(receiver));
    verify(crysilForwarder)
        .executeSignatureRequest(eq(encodedKey), eq(hashToBeSigned), eq(actor), eq(receiver));

    assertThat(response.getRegistrationData(), is(registrationData));
  }