コード例 #1
0
  /** 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"));
  }
コード例 #2
0
ファイル: KeyStoreFile.java プロジェクト: jlcsmith/ddf
 public boolean isKey(String alias) {
   try {
     return keyStore.isKeyEntry(alias);
   } catch (KeyStoreException e) {
     throw new CertificateGeneratorException("Could not determine if alias is a key", e);
   }
 }
コード例 #3
0
  /**
   * Writes out the details of all the key store entries. This makes for a long output. For
   * debugging purposes.
   */
  public void printKeyStoreContents() {
    try {
      String alias = null;
      KeyStore.TrustedCertificateEntry entry = null;

      for (Enumeration<String> aliases = keyStore.aliases(); aliases.hasMoreElements(); ) {
        alias = aliases.nextElement();
        System.out.println("");
        if (alias.startsWith(aliasPrefix)) {
          System.out.print(" * ===== ");
        } else {
          System.out.print("   ===== ");
        }
        System.out.println(alias);
        if (keyStore.isKeyEntry(alias)) {
          System.out.println("   is a KeyEntry                       (details hidden)");
          continue;
        } else if (keyStore.isCertificateEntry(alias)) {
          entry = (TrustedCertificateEntry) keyStore.getEntry(alias, null);
          System.out.println(entry.toString());
        }
        System.out.flush();
      } // end for

      System.out.println("");
      System.out.print("Number of entries in key store: ");
      System.out.println(keyStore.size());
      System.out.flush();

    } catch (Exception e) {
      System.err.println("ERROR: GFIPMKeystore.printKeyStoreContents failed: ");
      System.err.println(e.toString());
      System.err.flush();
    }
  } // end printKeyStoreContents
コード例 #4
0
  /**
   * 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) {
    }
  }
コード例 #5
0
  /** Gets the initialized key managers. */
  protected KeyManager[] getKeyManagers(
      String keystoreType, String keystoreProvider, String algorithm, String keyAlias)
      throws Exception {

    KeyManager[] kms = null;

    String keystorePass = getKeystorePassword();

    KeyStore ks = getKeystore(keystoreType, keystoreProvider, keystorePass);
    if (keyAlias != null && !ks.isKeyEntry(keyAlias)) {
      throw new IOException(sm.getString("jsse.alias_no_key_entry", keyAlias));
    }

    KeyManagerFactory kmf = KeyManagerFactory.getInstance(algorithm);
    String keyPass = endpoint.getKeyPass();
    if (keyPass == null) {
      keyPass = keystorePass;
    }
    kmf.init(ks, keyPass.toCharArray());

    kms = kmf.getKeyManagers();
    if (keyAlias != null) {
      String alias = keyAlias;
      if (JSSESocketFactory.defaultKeystoreType.equals(keystoreType)) {
        alias = alias.toLowerCase(Locale.ENGLISH);
      }
      for (int i = 0; i < kms.length; i++) {
        kms[i] = new JSSEKeyManager((X509KeyManager) kms[i], alias);
      }
    }

    return kms;
  }
コード例 #6
0
ファイル: PSEConfig.java プロジェクト: maxymania/jxta-jxse
  /**
   * Returns the private key for the specified ID.
   *
   * @param id The ID of the requested private key.
   * @param key_password The passphrase associated with the private key or {@code null} if the key
   *     has no passphrase.
   * @return PrivateKey for the specified ID.
   * @throws KeyStoreException When the wrong keystore has been provided.
   * @throws IOException For errors related to processing the keystore.
   */
  public PrivateKey getKey(ID id, char[] key_password) throws KeyStoreException, IOException {

    String alias = id.toString();

    try {
      synchronized (keystore_manager) {
        KeyStore store = keystore_manager.loadKeyStore(keystore_password);

        if (!store.containsAlias(alias) || !store.isKeyEntry(alias)) {
          return null;
        }

        return (PrivateKey) store.getKey(alias, key_password);
      }

    } catch (NoSuchAlgorithmException failed) {

      Logging.logCheckedSevere(LOG, "Something failed\n", failed);

      KeyStoreException failure = new KeyStoreException("Something Failed");

      failure.initCause(failed);
      throw failure;

    } catch (UnrecoverableKeyException failed) {

      Logging.logCheckedSevere(LOG, "Key passphrase failure\n", failed);

      KeyStoreException failure = new KeyStoreException("Key passphrase failure");
      failure.initCause(failed);
      throw failure;
    }
  }
コード例 #7
0
  /** Gets the initialized key managers. */
  protected KeyManager[] getKeyManagers(String algorithm, String keyAlias) throws Exception {

    KeyManager[] kms = null;

    String keystorePass = getKeystorePassword();

    KeyStore ks = getKeystore(keystorePass);
    if (keyAlias != null && !ks.isKeyEntry(keyAlias)) {
      throw new IOException(sm.getString("jsse.alias_no_key_entry", keyAlias));
    }

    KeyManagerFactory kmf = KeyManagerFactory.getInstance(algorithm);
    kmf.init(ks, keystorePass.toCharArray());

    kms = kmf.getKeyManagers();
    if (keyAlias != null) {
      // START SJSAS 6266949
      /*
      if (JSSESocketFactory.defaultKeystoreType.equals(keystoreType)) {
          keyAlias = keyAlias.toLowerCase();
      }
      */
      // END SJSAS 6266949

      for (int i = 0; i < kms.length; i++) {
        kms[i] = new JSSEKeyManager((X509KeyManager) kms[i], keyAlias);
      }
    }

    return kms;
  }
コード例 #8
0
ファイル: JmeterKeyStore.java プロジェクト: zioda/Lab7ORW
  /**
   * Process the input stream and try to read the keys from the store
   *
   * @param is {@link InputStream} from which the store should be loaded
   * @param pword the password used to check the integrity of the store
   * @throws IOException if there is a problem decoding or reading the store. A bad password might
   *     be the cause for this, or an empty store
   * @throws CertificateException if any of the certificated in the store can not be loaded
   * @throws NoSuchAlgorithmException if the algorithm to check the integrity of the store can not
   *     be found
   * @throws KeyStoreException if the store has not been initialized (should not happen here)
   * @throws UnrecoverableKeyException if the key can not be recovered from the store (should not
   *     happen here, either)
   */
  public void load(InputStream is, String pword)
      throws NoSuchAlgorithmException, CertificateException, IOException, KeyStoreException,
          UnrecoverableKeyException {
    char pw[] = pword == null ? null : pword.toCharArray();
    store.load(is, pw);

    ArrayList<String> v_names = new ArrayList<String>();
    this.privateKeyByAlias = new HashMap<String, PrivateKey>();
    this.certsByAlias = new HashMap<String, X509Certificate[]>();

    if (null != is) { // No point checking an empty keystore
      PrivateKey _key = null;
      int index = 0;
      Enumeration<String> aliases = store.aliases();
      while (aliases.hasMoreElements()) {
        String alias = aliases.nextElement();
        if (store.isKeyEntry(alias)) {
          if (index >= startIndex && index <= endIndex) {
            _key = (PrivateKey) store.getKey(alias, pw);
            if (null == _key) {
              throw new IOException("No key found for alias: " + alias); // Should not happen
            }
            Certificate[] chain = store.getCertificateChain(alias);
            if (null == chain) {
              throw new IOException("No certificate chain found for alias: " + alias);
            }
            v_names.add(alias);
            X509Certificate[] x509certs = new X509Certificate[chain.length];
            for (int i = 0; i < x509certs.length; i++) {
              x509certs[i] = (X509Certificate) chain[i];
            }

            privateKeyByAlias.put(alias, _key);
            certsByAlias.put(alias, x509certs);
          }
          index++;
        }
      }

      if (null == _key) {
        throw new IOException("No key(s) found");
      }
      if (index <= endIndex - startIndex) {
        LOG.warn(
            "Did not find all requested aliases. Start="
                + startIndex
                + ", end="
                + endIndex
                + ", found="
                + certsByAlias.size());
      }
    }

    /*
     * Note: if is == null, the arrays will be empty
     */
    this.names = v_names.toArray(new String[v_names.size()]);
  }
コード例 #9
0
  public static void main(String[] args) throws Exception {
    if (args.length < 1) {
      System.err.println("usage: java PKCS12Import {pkcs12file} [newjksfile]");
      System.exit(1);
    }

    File fileIn = new File(args[0]);
    File fileOut;
    if (args.length > 1) {
      fileOut = new File(args[1]);
    } else {
      fileOut = new File("newstore.jks");
    }

    if (!fileIn.canRead()) {
      System.err.println("Unable to access input keystore: " + fileIn.getPath());
      System.exit(2);
    }

    if (fileOut.exists() && !fileOut.canWrite()) {
      System.err.println("Output file is not writable: " + fileOut.getPath());
      System.exit(2);
    }

    KeyStore kspkcs12 = KeyStore.getInstance("pkcs12");
    KeyStore ksjks = KeyStore.getInstance("jks");

    LineNumberReader in = new LineNumberReader(new InputStreamReader(System.in));
    System.out.print("Enter input keystore passphrase: ");
    char[] inphrase = in.readLine().toCharArray();
    System.out.print("Enter output keystore passphrase: ");
    char[] outphrase = in.readLine().toCharArray();

    kspkcs12.load(new FileInputStream(fileIn), inphrase);

    ksjks.load((fileOut.exists()) ? new FileInputStream(fileOut) : null, outphrase);

    Enumeration eAliases = kspkcs12.aliases();
    int n = 0;
    while (eAliases.hasMoreElements()) {
      String strAlias = (String) eAliases.nextElement();
      System.err.println("Alias " + n++ + ": " + strAlias);

      if (kspkcs12.isKeyEntry(strAlias)) {
        System.err.println("Adding key for alias " + strAlias);
        Key key = kspkcs12.getKey(strAlias, inphrase);

        Certificate[] chain = kspkcs12.getCertificateChain(strAlias);

        ksjks.setKeyEntry(strAlias, key, outphrase, chain);
      }
    }

    OutputStream out = new FileOutputStream(fileOut);
    ksjks.store(out, outphrase);
    out.close();
  }
コード例 #10
0
ファイル: PSEConfig.java プロジェクト: maxymania/jxta-jxse
  /**
   * Returns <tt>true</tt> if the specified id is associated with a private key.
   *
   * @param id The ID of the requested private key.
   * @param store_password The passphrase used to unlock the keystore may be {@code null} for
   *     keystores with no passphrase.
   * @return <tt>true</tt> if a private key with the specified ID is present otherwise
   *     <tt>false</tt>
   * @throws KeyStoreException When the wrong keystore has been provided.
   * @throws IOException For errors related to processing the keystore.
   */
  public boolean isKey(ID id, char[] store_password) throws KeyStoreException, IOException {
    String alias = id.toString();

    synchronized (keystore_manager) {
      KeyStore store = keystore_manager.loadKeyStore(store_password);

      return store.containsAlias(alias) & store.isKeyEntry(alias);
    }
  }
コード例 #11
0
  /** java.security.KeyStore#load(java.io.InputStream, char[]) */
  public void test_loadLjava_io_InputStream$C() throws Exception {
    // Test for method void java.security.KeyStore.load(java.io.InputStream,
    // char[])
    byte[] keyStore = creatCertificate();
    KeyStore keyTest = KeyStore.getInstance(KeyStore.getDefaultType());
    InputStream in = new ByteArrayInputStream(keyStore);
    keyTest.load(in, pssWord);
    in.close();
    assertTrue("alias1 is not a certificate", keyTest.isCertificateEntry("alias1"));
    assertTrue("alias2 is not a keyEntry", keyTest.isKeyEntry("alias2"));
    assertTrue("alias3 is not a certificate", keyTest.isCertificateEntry("alias3"));

    // test with null password
    keyTest = KeyStore.getInstance(KeyStore.getDefaultType());
    in = new ByteArrayInputStream(keyStore);
    keyTest.load(in, null);
    in.close();
    assertTrue("alias1 is not a certificate", keyTest.isCertificateEntry("alias1"));
    assertTrue("alias2 is not a keyEntry", keyTest.isKeyEntry("alias2"));
    assertTrue("alias3 is not a certificate", keyTest.isCertificateEntry("alias3"));
  }
コード例 #12
0
 void assertPrivateKs(File file, String pass, String alias) throws Exception {
   KeyStore ks = loadKeyStore("jceks", file, alias);
   List aliases = ListUtil.fromIterator(new EnumerationIterator(ks.aliases()));
   assertEquals(2, aliases.size());
   Certificate cert = ks.getCertificate(alias + ".crt");
   assertNotNull(cert);
   assertEquals("X.509", cert.getType());
   assertTrue(ks.isKeyEntry(alias + ".key"));
   assertTrue(ks.isCertificateEntry(alias + ".crt"));
   Key key = ks.getKey(alias + ".key", pass.toCharArray());
   assertNotNull(key);
   assertEquals("RSA", key.getAlgorithm());
 }
コード例 #13
0
  /**
   * Writes out the certificates of all the key store entries. For debugging purposes.
   *
   * @param certformat If "rawcert", writes out the text information (long) about the certificates.
   *     If "enccert" [default], writes out the certificates in base64 (short).
   */
  public void printKeyStoreCertificates(String certformat) {
    try {
      String alias = null;
      Certificate cert;

      for (Enumeration<String> aliases = keyStore.aliases(); aliases.hasMoreElements(); ) {
        alias = aliases.nextElement();
        System.out.println("");
        if (alias.startsWith(aliasPrefix)) {
          System.out.print(" * ===== ");
        } else {
          System.out.print("   ===== ");
        }
        System.out.println(alias);
        // entry = (TrustedCertificateEntry) keyStore.getEntry(alias, null);
        System.out.print("   Creation Date:    ");
        System.out.println(keyStore.getCreationDate(alias));
        System.out.print("   Certificate type: ");
        cert = keyStore.getCertificate(alias);
        System.out.print(cert.getType());
        if (keyStore.isKeyEntry(alias)) {
          System.out.println("                          (details hidden)");
          continue;
        } else {
          System.out.println("");
        }

        if (keyStore.isCertificateEntry(alias)) {
          if ((certformat != null) && (certformat.equals("rawcert"))) {
            System.out.println(cert.toString());
          } else // enccert, encoded certificate
          {
            // String encoded = javax.xml.bind.DatatypeConverter.printBase64Binary(data);
            // byte[] decoded = javax.xml.bind.DatatypeConverter.parseBase64Binary(encoded);
            System.out.println(DatatypeConverter.printBase64Binary(cert.getEncoded()));
          }
        }
        System.out.flush();
      } // end for

      System.out.println("");
      System.out.print("Number of entries in key store: ");
      System.out.println(keyStore.size());
      System.out.flush();

    } catch (Exception e) {
      System.err.println("ERROR: GFIPMKeystore.printKeyStoreContents failed: ");
      System.err.println(e.toString());
      System.err.flush();
    }
  } // end printKeyStoreCertificates
コード例 #14
0
ファイル: GenericXMLSignature.java プロジェクト: joselo/sri
  private static String getAlias(KeyStore keyStore) throws IOException {
    String alias = null;

    try {
      Enumeration nombres = keyStore.aliases();
      while (nombres.hasMoreElements()) {
        String tmpAlias = (String) nombres.nextElement();
        if (keyStore.isKeyEntry(tmpAlias)) {
          alias = tmpAlias;
        }
      }
    } catch (KeyStoreException e) {
      throw new IOException("Error: " + e.getMessage());
    }
    return alias;
  }
コード例 #15
0
ファイル: PSEConfig.java プロジェクト: maxymania/jxta-jxse
  /**
   * Adds a private key to the PSE using the specified ID. The key replaces any existing certificate
   * or private key stored at this ID. The key is stored using the provided key passphrase.
   *
   * @param id The ID under which the certificate chain and private key will be stored.
   * @param certchain The certificate chain matching the private key.
   * @param key The private key to be stored in the kestore.
   * @param key_password The passphrase associated with the private key or {@code null} if the key
   *     has no passphrase.
   * @throws KeyStoreException When the wrong keystore key has been provided.
   * @throws IOException For errors related to processing the keystore.
   */
  public void setKey(ID id, Certificate[] certchain, PrivateKey key, char[] key_password)
      throws KeyStoreException, IOException {

    String alias = id.toString();

    synchronized (keystore_manager) {
      KeyStore store = keystore_manager.loadKeyStore(keystore_password);

      // Remove any existing entry.
      if (store.isKeyEntry(alias)) store.deleteEntry(alias);

      store.setKeyEntry(alias, key, key_password, certchain);

      keystore_manager.saveKeyStore(store, keystore_password);
    }
  }
コード例 #16
0
  public SilverCryptKeysAsymetric(FileInputStream filep12, String pwd) {
    // CHARGEMENT DU FICHIER PKCS#12
    KeyStore ks = null;
    char[] password = null;
    Security.addProvider(new BouncyCastleProvider());
    try {
      ks = KeyStore.getInstance("PKCS12");
      // Password pour le fichier filep12
      password = pwd.toCharArray();
      if (filep12 != null) {
        ks.load(filep12, password);
      } else {
        System.out.println("Erreur: fichier .p12" + "introuvable");
      }

    } catch (Exception e) {
      System.out.println(
          "Erreur: fichier .p12" + " n'est pas un fichier pkcs#12 valide ou passphrase incorrect");
      return;
    }

    // RECUPERATION DU COUPLE CLE PRIVEE/PUBLIQUE ET DU CERTIFICAT PUBLIQUE
    try {
      Enumeration<String> en = ks.aliases();
      String alias = "";
      List<String> vectaliases = new ArrayList<String>();

      while (en.hasMoreElements()) {
        vectaliases.add(en.nextElement());
      }
      String[] aliases = (vectaliases.toArray(new String[vectaliases.size()]));
      for (String aliase : aliases) {
        if (ks.isKeyEntry(aliase)) {
          alias = aliase;
          break;
        }
      }
      privatekey = (PrivateKey) ks.getKey(alias, password);
      cert = (X509Certificate) ks.getCertificate(alias);
      publickey = ks.getCertificate(alias).getPublicKey();
    } catch (Exception e) {
      SilverTrace.error(
          "util", "SilverCryptKeysAsymetric.Error", "root.MSG_GEN_PARAM_VALUE", "In init", e);
      return;
    }
  }
コード例 #17
0
 private static PrivateKey findPrivateKey(KeyStore keyStore, char[] keystorePassword)
     throws KeyStoreException, UnrecoverableKeyException, NoSuchAlgorithmException {
   Enumeration<String> aliases = keyStore.aliases();
   PrivateKey key = null;
   while (aliases.hasMoreElements()) {
     String alias = aliases.nextElement();
     if (keyStore.isKeyEntry(alias)) {
       // assume only one key
       key = (PrivateKey) keyStore.getKey(alias, keystorePassword);
       break;
     }
   }
   if (key == null) {
     throw new KeyStoreException("Could not find private key in keystore");
   }
   return key;
 }
コード例 #18
0
  @GET
  @Produces({MediaType.APPLICATION_JSON})
  public Response getKeyList(@Context UriInfo uriInfo) throws Exception {
    List<SslKeyStoreEntry> result = new ArrayList<SslKeyStoreEntry>(keystore.size());

    Enumeration<String> e = keystore.aliases();
    while (e.hasMoreElements()) {
      String alias = e.nextElement();
      SslKeyStoreEntry sslKeyStoreEntry =
          DtoFactory.getInstance()
              .createDto(SslKeyStoreEntry.class)
              .withAlias(alias)
              .withType(keystore.isKeyEntry(alias) ? "Key" : "Certificate");
      result.add(sslKeyStoreEntry);
    }
    return Response.ok().entity(result).type(MediaType.APPLICATION_JSON).build();
  }
コード例 #19
0
  public void main(Provider p) throws Exception {

    /*
     * Use Solaris SPARC 11.2 or later to avoid an intermittent failure
     * when running SunPKCS11-Solaris (8044554)
     */
    if (p.getName().equals("SunPKCS11-Solaris")
        && System.getProperty("os.name").equals("SunOS")
        && System.getProperty("os.arch").equals("sparcv9")
        && System.getProperty("os.version").compareTo("5.11") <= 0
        && getDistro().compareTo("11.2") < 0) {

      System.out.println(
          "SunPKCS11-Solaris provider requires " + "Solaris SPARC 11.2 or later, skipping");
      return;
    }

    long start = System.currentTimeMillis();
    provider = p;
    data = new byte[2048];
    new Random().nextBytes(data);
    KeyStore ks = getKeyStore();
    KeyFactory kf = KeyFactory.getInstance("RSA", provider);
    for (Enumeration e = ks.aliases(); e.hasMoreElements(); ) {
      String alias = (String) e.nextElement();
      if (ks.isKeyEntry(alias)) {
        System.out.println("* Key " + alias + "...");
        PrivateKey privateKey = (PrivateKey) ks.getKey(alias, password);
        PublicKey publicKey = ks.getCertificate(alias).getPublicKey();
        privateKey = (PrivateKey) kf.translateKey(privateKey);
        publicKey = (PublicKey) kf.translateKey(publicKey);
        test(privateKey, publicKey);
      }
    }
    long stop = System.currentTimeMillis();
    System.out.println("All tests passed (" + (stop - start) + " ms).");
  }
コード例 #20
0
ファイル: PSEConfig.java プロジェクト: maxymania/jxta-jxse
  /**
   * Returns the list of root certificates for which there is an associated local private key.
   *
   * @param store_password The passphrase used to unlock the keystore may be {@code null} for
   *     keystores with no passphrase.
   * @return an array of the available keys. May be an empty array.
   * @throws KeyStoreException When the wrong keystore has been provided.
   * @throws IOException For errors related to processing the keystore.
   */
  ID[] getKeysList(char[] store_password) throws KeyStoreException, IOException {
    List<ID> keyedRootsList = new ArrayList<ID>();

    synchronized (keystore_manager) {
      KeyStore store = keystore_manager.loadKeyStore(store_password);

      Enumeration<String> eachAlias = store.aliases();

      while (eachAlias.hasMoreElements()) {
        String anAlias = eachAlias.nextElement();

        if (store.isKeyEntry(anAlias)) {
          try {
            URI id = new URI(anAlias);

            keyedRootsList.add(IDFactory.fromURI(id));
          } catch (URISyntaxException badID) { // ignored
          }
        }
      }

      return keyedRootsList.toArray(new ID[keyedRootsList.size()]);
    }
  }
コード例 #21
0
ファイル: RSACoder.java プロジェクト: yminggithub/ryf_mms2
  public static String getPrivate(String path, String pwd) {
    try {
      KeyStore ks = KeyStore.getInstance("PKCS12");
      FileInputStream is = new FileInputStream(path);
      ks.load(is, pwd.toCharArray());
      is.close();
      System.out.println("keystore type=" + ks.getType());
      Enumeration enuma = ks.aliases();
      String keyAlias = null;
      if (enuma.hasMoreElements()) {
        keyAlias = (String) enuma.nextElement();
        System.out.println("alias=[" + keyAlias + "]");
      }

      System.out.println("is key entry=" + ks.isKeyEntry(keyAlias));
      BASE64Encoder enc = new BASE64Encoder();
      PrivateKey privatekey = (PrivateKey) ks.getKey(keyAlias, pwd.toCharArray());
      System.out.println("private key = " + enc.encode(privatekey.getEncoded()));
      return enc.encode(privatekey.getEncoded());
    } catch (Exception e) {
      e.printStackTrace();
      return null;
    }
  }
コード例 #22
0
  private String[] _getStrsAliasSourceToKpr(KeyStore kstOpenToSource) {
    String strMethod = "_getStrsAliasSourceToKpr(kstOpenToSource)";

    String[] strsAliasSourceAll = UtilKstAbs.s_getStrsAlias(super._frmOwner_, kstOpenToSource);

    if (strsAliasSourceAll == null) {
      MySystem.s_printOutError(this, strMethod, "nil strsAliasSourceAll");
      return null;
    }

    if (strsAliasSourceAll.length < 1) {
      MySystem.s_printOutWarning(this, strMethod, "strsAliasSourceAll.length < 1");

      String strBody = "No aliases found in " + UtilKstBks.f_s_strKeystoreType + " keystore:";

      strBody += "\n" + "  ";
      strBody += super._strPathAbsKstSource_;

      OPAbstract.s_showDialogWarning(super._frmOwner_, strBody);

      return null;
    }

    Vector<String> vec = new Vector<String>();

    try {
      for (int i = 0; i < strsAliasSourceAll.length; i++) {
        if (!kstOpenToSource.isKeyEntry(strsAliasSourceAll[i])) continue;

        Certificate[] certs = kstOpenToSource.getCertificateChain(strsAliasSourceAll[i]);

        if (certs == null) continue;

        if (certs.length < 1) continue;

        vec.addElement(strsAliasSourceAll[i]);
      }
    } catch (KeyStoreException excKeystore) {
      excKeystore.printStackTrace();
      MySystem.s_printOutError(this, strMethod, "excKeystore caught");

      // show dialog
      String strBody =
          "Got keystore Exception while reading " + UtilKstBks.f_s_strKeystoreType + " keystore:";

      strBody += "\n" + "  ";
      strBody += super._strPathAbsKstSource_;

      OPAbstract.s_showDialogWarning(super._frmOwner_, strBody);
    }

    // --

    if (vec.size() < 1) {
      MySystem.s_printOutWarning(this, strMethod, "vec.size() < 1");

      // show dialog
      String strBody =
          "No aliases pointing to keypair found in "
              + UtilKstBks.f_s_strKeystoreType
              + " keystore:";

      strBody += "\n" + "  ";
      strBody += super._strPathAbsKstSource_;

      OPAbstract.s_showDialogWarning(super._frmOwner_, strBody);

      return null;
    }

    // ---

    String[] strsAliasSourceToKpr = new String[vec.size()];

    for (int i = 0; i < vec.size(); i++) strsAliasSourceToKpr[i] = (String) vec.elementAt(i);

    return strsAliasSourceToKpr;
  }
コード例 #23
0
 private void loadKeyAndTrustStore() throws Exception {
   if (keyStorePassword != null) {
     if (keyStoreProvider != null) {
       if (keyStoreProviderArgument != null) {
         ClassLoader loader = Thread.currentThread().getContextClassLoader();
         Class clazz = loader.loadClass(keyStoreProvider);
         Class[] ctorSig = {String.class};
         Constructor ctor = clazz.getConstructor(ctorSig);
         Object[] ctorArgs = {keyStoreProviderArgument};
         Provider provider = (Provider) ctor.newInstance(ctorArgs);
         keyStore = KeyStore.getInstance(keyStoreType, provider);
       } else keyStore = KeyStore.getInstance(keyStoreType, keyStoreProvider);
     } else keyStore = KeyStore.getInstance(keyStoreType);
     InputStream is = null;
     if ((!"PKCS11".equalsIgnoreCase(keyStoreType)
             || !"PKCS11IMPLKS".equalsIgnoreCase(keyStoreType))
         && keyStoreURL != null) {
       is = keyStoreURL.openStream();
     }
     keyStore.load(is, keyStorePassword);
     if (keyStoreAlias != null && !keyStore.isKeyEntry(keyStoreAlias)) {
       throw new IOException(
           "Cannot find key entry with alias " + keyStoreAlias + " in the keyStore");
     }
     String algorithm = null;
     if (keyMgrFactoryAlgorithm != null) algorithm = keyMgrFactoryAlgorithm;
     else algorithm = KeyManagerFactory.getDefaultAlgorithm();
     if (keyMgrFactoryProvider != null)
       keyMgr = KeyManagerFactory.getInstance(algorithm, keyMgrFactoryProvider);
     else keyMgr = KeyManagerFactory.getInstance(algorithm);
     keyMgr.init(keyStore, keyStorePassword);
     keyManagers = keyMgr.getKeyManagers();
     for (int i = 0; i < keyManagers.length; i++) {
       keyManagers[i] =
           new SecurityKeyManager((X509KeyManager) keyManagers[i], keyStoreAlias, clientAlias);
     }
   }
   if (trustStorePassword != null) {
     if (trustStoreProvider != null) {
       if (trustStoreProviderArgument != null) {
         ClassLoader loader = Thread.currentThread().getContextClassLoader();
         Class clazz = loader.loadClass(trustStoreProvider);
         Class[] ctorSig = {String.class};
         Constructor ctor = clazz.getConstructor(ctorSig);
         Object[] ctorArgs = {trustStoreProviderArgument};
         Provider provider = (Provider) ctor.newInstance(ctorArgs);
         trustStore = KeyStore.getInstance(trustStoreType, provider);
       } else trustStore = KeyStore.getInstance(trustStoreType, trustStoreProvider);
     } else trustStore = KeyStore.getInstance(trustStoreType);
     InputStream is = null;
     if ((!"PKCS11".equalsIgnoreCase(trustStoreType)
             || !"PKCS11IMPLKS".equalsIgnoreCase(trustStoreType))
         && trustStoreURL != null) {
       is = trustStoreURL.openStream();
     }
     trustStore.load(is, trustStorePassword);
     String algorithm = null;
     if (trustMgrFactoryAlgorithm != null) algorithm = trustMgrFactoryAlgorithm;
     else algorithm = TrustManagerFactory.getDefaultAlgorithm();
     if (trustMgrFactoryProvider != null)
       trustMgr = TrustManagerFactory.getInstance(algorithm, trustStoreProvider);
     else trustMgr = TrustManagerFactory.getInstance(algorithm);
     trustMgr.init(trustStore);
   } else if (keyStore != null) {
     trustStore = keyStore;
     String algorithm = null;
     if (trustMgrFactoryAlgorithm != null) algorithm = trustMgrFactoryAlgorithm;
     else algorithm = TrustManagerFactory.getDefaultAlgorithm();
     trustMgr = TrustManagerFactory.getInstance(algorithm);
     trustMgr.init(trustStore);
   }
 }
コード例 #24
0
  private void importCertificate() throws Exception {
    File f;
    FileInputStream fis;
    X509Certificate[] certificateChain;
    Certificate endEntityCertificate;
    String endEntityCertificateSubjectKeyIdentifier;
    KeyStore ks;
    Key privateKey;

    f = null;
    fis = null;
    certificateChain = null;
    endEntityCertificate = null;
    endEntityCertificateSubjectKeyIdentifier = null;
    ks = null;
    privateKey = null;

    f = new File(getCertificateFilename());

    // Ensure we can read file containing certificate
    if (f.canRead() == false) {
      System.out.println("certificate file " + f.getName() + " not found");

      return;
    }

    try {
      fis = new FileInputStream(f);

      // Parse X509 certificate chain
      certificateChain = parseX509CertificateChain(fis);

    } finally {
      if (fis != null) {
        fis.close();
      }
    }

    // Ensure certificate chain is not empty
    if (certificateChain.length < 1) {
      // Certificate chain is empty
      System.out.println("certificate chain is empty");

      return;
    }

    // Get end entity certificate
    endEntityCertificate = certificateChain[0];

    // Generate end entity certificate subject key identifier
    endEntityCertificateSubjectKeyIdentifier = generateSubjectKeyIdentifier(endEntityCertificate);

    // Initialiase key store
    ks = KeyStore.getInstance("Luna", "LunaJCAProvider");
    ks.load(null, null);

    // Is this a certificate request reply?
    if (ks.isKeyEntry(endEntityCertificateSubjectKeyIdentifier) == true) {
      // This is a certificate request reply, get private key
      privateKey = ks.getKey(endEntityCertificateSubjectKeyIdentifier, null);

      // Update certificate chain associated with this private key
      ks.setKeyEntry(endEntityCertificateSubjectKeyIdentifier, privateKey, null, certificateChain);

      System.out.println(
          "imported certificate request reply " + endEntityCertificateSubjectKeyIdentifier + " OK");
    } else {
      // No associated private key, treat as trusted certificate
      ks.setCertificateEntry(endEntityCertificateSubjectKeyIdentifier, endEntityCertificate);

      System.out.println(
          "imported trusted certificate " + endEntityCertificateSubjectKeyIdentifier + " OK");
    }
  }
コード例 #25
0
  /**
   * Performs test signatures for the specified keys or for all if "all" specified.
   *
   * @param keyStore Loaded keystore to read keys from
   * @param alias Alias of key to test or "all" to test all
   * @param authCode Key password (if used, ie for JKS only)
   * @param signatureProvider Provider for creating the signature
   * @return The results for each key found
   * @throws CryptoTokenOfflineException In case the key could not be used
   */
  public static Collection<KeyTestResult> testKey(
      KeyStore keyStore, String alias, char[] authCode, String signatureProvider)
      throws CryptoTokenOfflineException {
    if (LOG.isDebugEnabled()) {
      LOG.debug("testKey for alias: " + alias);
    }

    final Collection<KeyTestResult> result = new LinkedList<KeyTestResult>();

    try {
      final Enumeration<String> e = keyStore.aliases();
      while (e.hasMoreElements()) {
        final String keyAlias = e.nextElement();
        if (alias.equalsIgnoreCase(ICryptoToken.ALL_KEYS) || alias.equals(keyAlias)) {
          if (LOG.isDebugEnabled()) {
            LOG.debug("checking keyAlias: " + keyAlias);
          }

          if (keyStore.isKeyEntry(keyAlias)) {
            String status;
            String publicKeyHash = null;
            boolean success = false;
            try {
              final PrivateKey privateKey = (PrivateKey) keyStore.getKey(keyAlias, authCode);
              final Certificate entryCert = keyStore.getCertificate(keyAlias);
              if (entryCert != null) {
                final PublicKey publicKey = entryCert.getPublicKey();
                publicKeyHash = createKeyHash(publicKey);
                testSignAndVerify(privateKey, publicKey, signatureProvider);
                success = true;
                status = "";
              } else {
                status = "Not testing keys with alias " + keyAlias + ". No certificate exists.";
              }
            } catch (ClassCastException ce) {
              status = "Not testing keys with alias " + keyAlias + ". Not a private key.";
            } catch (InvalidKeyException ex) {
              LOG.error("Error testing key: " + keyAlias, ex);
              status = ex.getMessage();
            } catch (KeyStoreException ex) {
              LOG.error("Error testing key: " + keyAlias, ex);
              status = ex.getMessage();
            } catch (NoSuchAlgorithmException ex) {
              LOG.error("Error testing key: " + keyAlias, ex);
              status = ex.getMessage();
            } catch (NoSuchProviderException ex) {
              LOG.error("Error testing key: " + keyAlias, ex);
              status = ex.getMessage();
            } catch (SignatureException ex) {
              LOG.error("Error testing key: " + keyAlias, ex);
              status = ex.getMessage();
            } catch (UnrecoverableKeyException ex) {
              LOG.error("Error testing key: " + keyAlias, ex);
              status = ex.getMessage();
            }
            result.add(new KeyTestResult(keyAlias, success, status, publicKeyHash));
          }
        }
      }
    } catch (KeyStoreException ex) {
      throw new CryptoTokenOfflineException(ex);
    }

    if (LOG.isDebugEnabled()) {
      LOG.debug("<testKey");
    }
    return result;
  }
コード例 #26
0
ファイル: ReadP12Test.java プロジェクト: FauxFaux/jdk9-jdk
  private void readTest(String inKeyStore) throws Exception {

    KeyStore inputKeyStore;

    // Initialize KeyStore
    String dir = System.getProperty("test.src", ".");
    String keystorePath = dir + File.separator + "certs" + File.separator + "readP12";
    inputKeyStore = KeyStore.getInstance(IN_KEYSTORE_TYPE);
    // KeyStore have encoded by Base64.getMimeEncoder().encode(),need decode
    // first.
    byte[] input = Files.readAllBytes(Paths.get(keystorePath, inKeyStore));
    ByteArrayInputStream arrayIn = new ByteArrayInputStream(Base64.getMimeDecoder().decode(input));
    inputKeyStore.load(arrayIn, IN_STORE_PASS.toCharArray());
    out.println("Initialize KeyStore : " + inKeyStore + " success");

    out.println("getProvider : " + inputKeyStore.getProvider());
    out.println("getType : " + inputKeyStore.getType());
    out.println("getDefaultType : " + KeyStore.getDefaultType());

    int idx = 0;
    Enumeration<String> e = inputKeyStore.aliases();
    String alias;
    while (e.hasMoreElements()) {
      alias = e.nextElement();
      out.println("Alias " + idx + " : " + alias);
      if (inputKeyStore.containsAlias(alias) == false) {
        throw new RuntimeException("Alias not found");
      }

      out.println("getCreationDate : " + inputKeyStore.getCreationDate(alias));

      X509Certificate cert = (X509Certificate) inputKeyStore.getCertificate(alias);
      out.println("getCertificate : " + cert.getSubjectDN());
      String retAlias = inputKeyStore.getCertificateAlias(cert);
      if (!retAlias.equals(alias)) {
        throw new RuntimeException("Alias mismatch");
      }
      out.println("getCertificateAlias : " + retAlias);

      Certificate[] certs = inputKeyStore.getCertificateChain(alias);
      for (int i = 0; i < certs.length; i++) {
        out.println(
            "getCertificateChain " + i + " : " + ((X509Certificate) certs[i]).getSubjectDN());
      }

      boolean isCertEntry = inputKeyStore.isCertificateEntry(alias);
      // test KeyStore only contain key pair entries.
      if (isCertEntry == true) {
        throw new RuntimeException(
            "inputKeystore should not be certEntry because test keystore only contain key pair entries.");
      }

      boolean isKeyEntry = inputKeyStore.isKeyEntry(alias);
      if (isKeyEntry) {
        Key key = inputKeyStore.getKey(alias, IN_STORE_PASS.toCharArray());
        out.println("Key : " + key.toString());
      } else {
        throw new RuntimeException("Entry type unknown\n");
      }
      idx++;
    }

    int size = inputKeyStore.size();
    if (idx != size) {
      throw new RuntimeException("Size not match");
    }
  }