Example #1
0
  /**
   * Assigns the given key to the given alias, protecting it with the given password.
   *
   * <p>If the given key is of type <code>java.security.PrivateKey</code>, it must be accompanied by
   * a certificate chain certifying the corresponding public key.
   *
   * <p>If the given alias already exists, the keystore information associated with it is overridden
   * by the given key (and possibly certificate chain).
   *
   * @param alias the alias name
   * @param key the key to be associated with the alias
   * @param password the password to protect the key
   * @param chain the certificate chain for the corresponding public key (only required if the given
   *     key is of type <code>java.security.PrivateKey</code>).
   * @exception KeyStoreException if the given key cannot be protected, or this operation fails for
   *     some other reason
   */
  public void engineSetKeyEntry(String alias, Key key, char[] password, Certificate[] chain)
      throws KeyStoreException {
    permissionCheck();

    synchronized (entries) {
      try {
        KeyEntry entry = new KeyEntry();
        entry.date = new Date();

        if (key instanceof PrivateKey) {
          if ((key.getFormat().equals("PKCS#8")) || (key.getFormat().equals("PKCS8"))) {
            entry.protectedPrivKey = encryptPrivateKey(key.getEncoded(), password);
            entry.password = password.clone();
          } else {
            throw new KeyStoreException("Private key is not encoded as PKCS#8");
          }
        } else {
          throw new KeyStoreException("Key is not a PrivateKey");
        }

        // clone the chain
        if (chain != null) {
          if ((chain.length > 1) && !validateChain(chain)) {
            throw new KeyStoreException("Certificate chain does not validate");
          }

          entry.chain = chain.clone();
          entry.chainRefs = new long[entry.chain.length];
        }

        String lowerAlias = alias.toLowerCase();
        if (entries.get(lowerAlias) != null) {
          deletedEntries.put(lowerAlias, entries.get(lowerAlias));
        }

        entries.put(lowerAlias, entry);
        addedEntries.put(lowerAlias, entry);
      } catch (Exception nsae) {
        KeyStoreException ke = new KeyStoreException("Key protection algorithm not found: " + nsae);
        ke.initCause(nsae);
        throw ke;
      }
    }
  }