Java Code Examples for java.security.KeyStore#deleteEntry()

The following examples show how to use java.security.KeyStore#deleteEntry() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: CastError.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    KeyStore ks = KeyStore.getInstance("JKS");
    FileInputStream fis = new FileInputStream(
            new File(System.getProperty("test.src"),
                    "../tools/jarsigner/JarSigning.keystore"));
    ks.load(fis, "bbbbbb".toCharArray());

    PrivateKey pk = (PrivateKey) ks.getKey("c", "bbbbbb".toCharArray());
    Certificate cert = ks.getCertificate("c");

    ks = KeyStore.getInstance("Windows-MY");
    ks.load(null, null);

    ks.setKeyEntry("8143913", pk, null, new Certificate[]{cert});
    ks.deleteEntry("8143913");
}
 
Example 2
Source File: AbstractAndroidKeystoreSecretKeyWrapper.java    From Android-Vault with Apache License 2.0 5 votes vote down vote up
@Override
public synchronized void clearKey(Context context) throws GeneralSecurityException, IOException {
    mKeyPair = null;
    final KeyStore keyStore = KeyStore.getInstance(EncryptionConstants.ANDROID_KEY_STORE);
    keyStore.load(null);
    keyStore.deleteEntry(mAlias);
}
 
Example 3
Source File: CertificateController.java    From Spark with Apache License 2.0 5 votes vote down vote up
/**
* This method delete certificate with provided alias from the Truststore
* 
* @param alias Alias of the certificate to delete
* @throws KeyStoreException
* @throws IOException
* @throws NoSuchAlgorithmException
* @throws CertificateException
*/
  @Override
  public void deleteEntry(String alias) throws KeyStoreException {
      int dialogButton = JOptionPane.YES_NO_OPTION;
      int dialogValue = JOptionPane.showConfirmDialog(null, Res.getString("dialog.certificate.sure.to.delete"), null,
              dialogButton);
      if (dialogValue == JOptionPane.YES_OPTION) {
          KeyStore store = getAliasKeyStore(alias);
          
          if(store.equals(displayCaStore) || store.equals(exceptionsCaStore)){
              // adds entry do distrusted store so it will be not displayed next time
              distrustedCaStore.setCertificateEntry(alias, store.getCertificate(alias));
          }
          store.deleteEntry(alias);
          if(store.equals(trustStore) ) {
              removeCertFromExceptions(alias);
          }
          JOptionPane.showMessageDialog(null, Res.getString("dialog.certificate.has.been.deleted"));
          CertificateModel model = null;
          for (CertificateModel certModel : allCertificates) {
              if (certModel.getAlias().equals(alias)) {
                  model = certModel;
              }
          }
          exemptedCertificates.remove(model);
          trustedCertificates.remove(model);
          blackListedCertificates.remove(model);
          displayCaCertificates.remove(model);
          exemptedCacerts.remove(model);
           
          allCertificates.remove(model);
      }
      refreshCertTable();
  }
 
Example 4
Source File: TestUtils.java    From capillary with Apache License 2.0 5 votes vote down vote up
static void clearKeyStore() throws GeneralSecurityException {
  // Clear existing keystore entries.
  KeyStore keyStore = Utils.getInstance().loadKeyStore();
  Enumeration<String> aliases = keyStore.aliases();
  while (aliases.hasMoreElements()) {
    keyStore.deleteEntry(aliases.nextElement());
  }
}
 
Example 5
Source File: KeyStoreHelper.java    From andOTP with MIT License 5 votes vote down vote up
public static void wipeKeys(Context context) {
    File keyFile = new File(context.getFilesDir() + "/" + Constants.FILENAME_ENCRYPTED_KEY);
    keyFile.delete();

    try {
        final KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
        keyStore.load(null);
        if (keyStore.containsAlias(Constants.KEYSTORE_ALIAS_WRAPPING))
            keyStore.deleteEntry(Constants.KEYSTORE_ALIAS_WRAPPING);
    } catch (GeneralSecurityException | IOException e) {
        e.printStackTrace();
    }
}
 
Example 6
Source File: DeleteTrustedCertificateAction.java    From keystore-explorer with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Let the user delete the selected KeyStore entry.
 */
public void deleteSelectedEntry() {
	try {
		KeyStoreHistory history = kseFrame.getActiveKeyStoreHistory();

		KeyStoreState currentState = history.getCurrentState();
		KeyStoreState newState = currentState.createBasisForNextState(this);

		KeyStore keyStore = newState.getKeyStore();
		String alias = kseFrame.getSelectedEntryAlias();

		String message = MessageFormat.format(
				res.getString("DeleteTrustedCertificateAction.ConfirmDelete.message"), alias);
		int selected = JOptionPane.showConfirmDialog(frame, message,
				res.getString("DeleteTrustedCertificateAction.DeleteEntry.Title"), JOptionPane.YES_NO_OPTION);

		if (selected != JOptionPane.YES_OPTION) {
			return;
		}

		keyStore.deleteEntry(alias);

		currentState.append(newState);

		kseFrame.updateControls(true);
	} catch (Exception ex) {
		DError.displayError(frame, ex);
	}
}
 
Example 7
Source File: PreAndroidMSecureKeyStore.java    From android-showcase-template with Apache License 2.0 5 votes vote down vote up
@Override
public void deleteKey(String keyAlias) throws GeneralSecurityException, IOException {
    if (hasSecretKey(keyAlias)) {
        SharedPreferences.Editor editor = this.sharedPreferences.edit();
        editor.remove(keyAlias);
        editor.commit();
    } else if (hasKeyPair(keyAlias)) {
        KeyStore ks = loadKeyStore();
        ks.deleteEntry(keyAlias);
    }
}
 
Example 8
Source File: ReactNativeBiometrics.java    From react-native-biometrics with MIT License 5 votes vote down vote up
protected boolean deleteBiometricKey() {
    try {
        KeyStore keyStore = KeyStore.getInstance("AndroidKeyStore");
        keyStore.load(null);

        keyStore.deleteEntry(biometricKeyAlias);
        return true;
    } catch (Exception e) {
        return false;
    }
}
 
Example 9
Source File: Main.java    From fido2 with GNU Lesser General Public License v2.1 5 votes vote down vote up
private static void deleteaccesskey(String keystorelocation, String password, String alias) throws Exception {
    KeyStore keystore = KeyStore.getInstance("BCFKS", BC_FIPS_PROVIDER);
    keystore.load(new FileInputStream(keystorelocation), password.toCharArray());
    keystore.deleteEntry(alias);
    keystore.store(new FileOutputStream(keystorelocation), password.toCharArray());
    System.out.println("Removed access key: " + alias);
}
 
Example 10
Source File: PKCS12CertificateFactory.java    From OpenAs2App with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public void removeCertificate(String alias) throws OpenAS2Exception {
    KeyStore ks = getKeyStore();

    try {
        if (ks.getCertificate(alias) == null) {
            throw new CertificateNotFoundException(null, alias);
        }

        ks.deleteEntry(alias);
        save(getFilename(), getPassword());
    } catch (GeneralSecurityException gse) {
        throw new WrappedException(gse);
    }
}
 
Example 11
Source File: CastError.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    KeyStore ks = KeyStore.getInstance(
            new File(System.getProperty("test.src"),
                    "../tools/jarsigner/JarSigning.keystore"),
            "bbbbbb".toCharArray());

    PrivateKey pk = (PrivateKey) ks.getKey("c", "bbbbbb".toCharArray());
    Certificate cert = ks.getCertificate("c");

    ks = KeyStore.getInstance("Windows-MY");
    ks.load(null, null);

    ks.setKeyEntry("8143913", pk, null, new Certificate[]{cert});
    ks.deleteEntry("8143913");
}
 
Example 12
Source File: CipherStorageBase.java    From react-native-keychain with MIT License 5 votes vote down vote up
/** Try to extract key by alias from keystore, in case of 'known android bug' reduce retry counter. */
@Nullable
protected Key extractKey(@NonNull final KeyStore keyStore,
                         @NonNull final String safeAlias,
                         @NonNull final AtomicInteger retry)
  throws GeneralSecurityException {
  final Key key;

  // Fix for android.security.KeyStoreException: Invalid key blob
  // more info: https://stackoverflow.com/questions/36488219/android-security-keystoreexception-invalid-key-blob/36846085#36846085
  try {
    key = keyStore.getKey(safeAlias, null);
  } catch (final UnrecoverableKeyException ex) {
    // try one more time
    if (retry.getAndDecrement() > 0) {
      keyStore.deleteEntry(safeAlias);

      return null;
    }

    throw ex;
  }

  // null if the given alias does not exist or does not identify a key-related entry.
  if (null == key) {
    throw new KeyStoreAccessException("Empty key extracted!");
  }

  return key;
}
 
Example 13
Source File: DeleteMultipleEntriesAction.java    From keystore-explorer with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Let the user delete the selected KeyStore entry.
 */
public void deleteSelectedEntries() {
	String[] aliases = kseFrame.getSelectedEntryAliases();
	if (aliases.length == 0) {
		return;
	}

	try {
		KeyStoreHistory history = kseFrame.getActiveKeyStoreHistory();

		KeyStoreState currentState = history.getCurrentState();
		KeyStoreState newState = currentState.createBasisForNextState(this);

		KeyStore keyStore = newState.getKeyStore();

		int selected = JOptionPane.showConfirmDialog(frame, res.getString("DeleteMultipleEntriesAction.ConfirmDelete.message"),
				res.getString("DeleteMultipleEntriesAction.DeleteEntry.Title"), JOptionPane.YES_NO_OPTION);

		if (selected != JOptionPane.YES_OPTION) {
			return;
		}

		for (String alias : aliases) {
			keyStore.deleteEntry(alias);
			newState.removeEntryPassword(alias);
		}

		currentState.append(newState);

		kseFrame.updateControls(true);
	} catch (Exception ex) {
		DError.displayError(frame, ex);
	}
}
 
Example 14
Source File: BaseCipherStorage.java    From keystore-ultimate with Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void removeKey(String alias) {
    try {
        if (containsAlias(alias)) {
            KeyStore keyStore = getKeyStoreAndLoad();
            keyStore.deleteEntry(alias);
            storage.remove(alias);
        }
    } catch (KeyStoreException e) {
        throw new KeyStoreAccessException("Failed to access Keystore", e);
    }
}
 
Example 15
Source File: RenameKeyAction.java    From keystore-explorer with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Rename the currently selected entry
 */
public void renameSelectedEntry() {
	try {
		KeyStoreHistory history = kseFrame.getActiveKeyStoreHistory();
		KeyStoreState currentState = history.getCurrentState();

		String alias = kseFrame.getSelectedEntryAlias();

		Password password = getEntryPassword(alias, currentState);

		if (password == null) {
			return;
		}

		KeyStoreState newState = currentState.createBasisForNextState(this);

		KeyStore keyStore = newState.getKeyStore();

		Key key = keyStore.getKey(alias, password.toCharArray());

		DGetAlias dGetAlias = new DGetAlias(frame, res.getString("RenameKeyAction.NewEntryAlias.Title"), alias);
		dGetAlias.setLocationRelativeTo(frame);
		dGetAlias.setVisible(true);
		String newAlias = dGetAlias.getAlias();

		if (newAlias == null) {
			return;
		}

		if (newAlias.equalsIgnoreCase(alias)) {
			JOptionPane.showMessageDialog(frame,
					MessageFormat.format(res.getString("RenameKeyAction.RenameAliasIdentical.message"), alias),
					res.getString("RenameKeyAction.RenameEntry.Title"), JOptionPane.WARNING_MESSAGE);
			return;
		}

		if (keyStore.containsAlias(newAlias)) {
			String message = MessageFormat
					.format(res.getString("RenameKeyAction.OverWriteEntry.message"), newAlias);

			int selected = JOptionPane.showConfirmDialog(frame, message,
					res.getString("RenameKeyAction.RenameEntry.Title"), JOptionPane.YES_NO_OPTION);
			if (selected != JOptionPane.YES_OPTION) {
				return;
			}

			keyStore.deleteEntry(newAlias);
			newState.removeEntryPassword(newAlias);
		}

		keyStore.setKeyEntry(newAlias, key, password.toCharArray(), null);
		newState.setEntryPassword(newAlias, new Password(password));

		keyStore.deleteEntry(alias);
		newState.removeEntryPassword(alias);

		currentState.append(newState);

		kseFrame.updateControls(true);
	} catch (Exception ex) {
		DError.displayError(frame, ex);
	}
}
 
Example 16
Source File: ImportKeyPairAction.java    From keystore-explorer with GNU General Public License v3.0 4 votes vote down vote up
private void importKeyPairPkcs12() {
	try {
		KeyStoreHistory history = kseFrame.getActiveKeyStoreHistory();

		KeyStoreState currentState = history.getCurrentState();
		KeyStoreState newState = currentState.createBasisForNextState(this);

		KeyStore keyStore = newState.getKeyStore();

		DImportKeyPairPkcs12 dImportKeyPairPkcs12 = new DImportKeyPairPkcs12(frame);
		dImportKeyPairPkcs12.setLocationRelativeTo(frame);
		dImportKeyPairPkcs12.setVisible(true);

		PrivateKey privKey = dImportKeyPairPkcs12.getPrivateKey();
		X509Certificate[] certs = dImportKeyPairPkcs12.getCertificateChain();

		if ((privKey == null) || (certs == null)) {
			return;
		}

		X509Certificate[] x509Certs = X509CertUtil.orderX509CertChain(X509CertUtil.convertCertificates(certs));

		DGetAlias dGetAlias = new DGetAlias(frame, res.getString("ImportKeyPairAction.NewKeyPairEntryAlias.Title"),
				X509CertUtil.getCertificateAlias(x509Certs[0]));
		dGetAlias.setLocationRelativeTo(frame);
		dGetAlias.setVisible(true);
		String alias = dGetAlias.getAlias();

		if (alias == null) {
			return;
		}

		if (keyStore.containsAlias(alias)) {
			String message = MessageFormat.format(res.getString("ImportKeyPairAction.OverWriteEntry.message"),
					alias);

			int selected = JOptionPane.showConfirmDialog(frame, message,
					res.getString("ImportKeyPairAction.NewKeyPairEntryAlias.Title"), JOptionPane.YES_NO_OPTION);
			if (selected != JOptionPane.YES_OPTION) {
				return;
			}
		}

		Password password = new Password((char[])null);
		KeyStoreType type = KeyStoreType.resolveJce(keyStore.getType());

		if (type.hasEntryPasswords()) {
			DGetNewPassword dGetNewPassword = new DGetNewPassword(frame,
					res.getString("ImportKeyPairAction.NewKeyPairEntryPassword.Title"),
					applicationSettings.getPasswordQualityConfig());
			dGetNewPassword.setLocationRelativeTo(frame);
			dGetNewPassword.setVisible(true);
			password = dGetNewPassword.getPassword();

			if (password == null) {
				return;
			}
		}

		if (keyStore.containsAlias(alias)) {
			keyStore.deleteEntry(alias);
			newState.removeEntryPassword(alias);
		}

		keyStore.setKeyEntry(alias, privKey, password.toCharArray(), x509Certs);
		newState.setEntryPassword(alias, password);

		currentState.append(newState);

		kseFrame.updateControls(true);

		JOptionPane.showMessageDialog(frame, res.getString("ImportKeyPairAction.KeyPairImportSuccessful.message"),
				res.getString("ImportKeyPairAction.ImportKeyPair.Title"), JOptionPane.INFORMATION_MESSAGE);
	} catch (Exception ex) {
		DError.displayError(frame, ex);
	}
}
 
Example 17
Source File: TestKeyStoreEntry.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 4 votes vote down vote up
public void runTest(Provider p) throws Exception {
    try (FileOutputStream fos = new FileOutputStream("jceks");
            FileInputStream fis = new FileInputStream("jceks");) {

        KeyStore ks = KeyStore.getInstance("jceks", p);
        // create an empty key store
        ks.load(null, null);

        // store the secret keys
        String aliasHead = new String("secretKey");
        for (int j = 0; j < NUM_ALGOS; j++) {
            ks.setKeyEntry(aliasHead + j, sks[j], PASSWDK, null);
        }

        // write the key store out to a file
        ks.store(fos, PASSWDF);
        // wipe clean the existing key store
        for (int k = 0; k < NUM_ALGOS; k++) {
            ks.deleteEntry(aliasHead + k);
        }
        if (ks.size() != 0) {
            throw new RuntimeException("ERROR: re-initialization failed");
        }

        // reload the key store with the file
        ks.load(fis, PASSWDF);

        // check the integrity/validaty of the key store
        Key temp = null;
        String alias = null;
        if (ks.size() != NUM_ALGOS) {
            throw new RuntimeException("ERROR: wrong number of key"
                    + " entries");
        }

        for (int m = 0; m < ks.size(); m++) {
            alias = aliasHead + m;
            temp = ks.getKey(alias, PASSWDK);
            // compare the keys
            if (!temp.equals(sks[m])) {
                throw new RuntimeException("ERROR: key comparison (" + m
                        + ") failed");
            }
            // check the type of key
            if (ks.isCertificateEntry(alias) || !ks.isKeyEntry(alias)) {
                throw new RuntimeException("ERROR: type identification ("
                        + m + ") failed");
            }
        }
    }
}
 
Example 18
Source File: TestKeyStoreEntry.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
public void runTest(Provider p) throws Exception {
    try (FileOutputStream fos = new FileOutputStream("jceks");
            FileInputStream fis = new FileInputStream("jceks");) {

        KeyStore ks = KeyStore.getInstance("jceks", p);
        // create an empty key store
        ks.load(null, null);

        // store the secret keys
        String aliasHead = new String("secretKey");
        for (int j = 0; j < NUM_ALGOS; j++) {
            ks.setKeyEntry(aliasHead + j, sks[j], PASSWDK, null);
        }

        // write the key store out to a file
        ks.store(fos, PASSWDF);
        // wipe clean the existing key store
        for (int k = 0; k < NUM_ALGOS; k++) {
            ks.deleteEntry(aliasHead + k);
        }
        if (ks.size() != 0) {
            throw new RuntimeException("ERROR: re-initialization failed");
        }

        // reload the key store with the file
        ks.load(fis, PASSWDF);

        // check the integrity/validaty of the key store
        Key temp = null;
        String alias = null;
        if (ks.size() != NUM_ALGOS) {
            throw new RuntimeException("ERROR: wrong number of key"
                    + " entries");
        }

        for (int m = 0; m < ks.size(); m++) {
            alias = aliasHead + m;
            temp = ks.getKey(alias, PASSWDK);
            // compare the keys
            if (!temp.equals(sks[m])) {
                throw new RuntimeException("ERROR: key comparison (" + m
                        + ") failed");
            }
            // check the type of key
            if (ks.isCertificateEntry(alias) || !ks.isKeyEntry(alias)) {
                throw new RuntimeException("ERROR: type identification ("
                        + m + ") failed");
            }
        }
    }
}
 
Example 19
Source File: RemoveFromCertificateChainAction.java    From keystore-explorer with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Do action.
 */
@Override
protected void doAction() {
	try {
		KeyStoreHistory history = kseFrame.getActiveKeyStoreHistory();
		KeyStoreState currentState = history.getCurrentState();

		String alias = kseFrame.getSelectedEntryAlias();

		Password password = getEntryPassword(alias, currentState);

		if (password == null) {
			return;
		}

		KeyStoreState newState = currentState.createBasisForNextState(this);

		KeyStore keyStore = newState.getKeyStore();

		Key privKey = keyStore.getKey(alias, password.toCharArray());

		X509Certificate[] certChain = X509CertUtil.orderX509CertChain(X509CertUtil.convertCertificates(keyStore
				.getCertificateChain(alias)));

		if (certChain.length == 1) {
			JOptionPane.showMessageDialog(frame,
					res.getString("RemoveFromCertificateChainAction.CannotRemoveOnlyCert.message"),
					res.getString("RemoveFromCertificateChainAction.RemoveFromCertificateChain.Title"),
					JOptionPane.WARNING_MESSAGE);
			return;
		}

		// Certificate to remove is the end one in the chain
		X509Certificate[] newCertChain = new X509Certificate[certChain.length - 1];

		System.arraycopy(certChain, 0, newCertChain, 0, newCertChain.length);

		keyStore.deleteEntry(alias);

		keyStore.setKeyEntry(alias, privKey, password.toCharArray(), newCertChain);

		currentState.append(newState);

		kseFrame.updateControls(true);

		JOptionPane.showMessageDialog(frame,
				res.getString("RemoveFromCertificateChainAction.RemoveFromCertificateChainSuccessful.message"),
				res.getString("RemoveFromCertificateChainAction.RemoveFromCertificateChain.Title"),
				JOptionPane.INFORMATION_MESSAGE);
	} catch (Exception ex) {
		DError.displayError(frame, ex);
	}
}
 
Example 20
Source File: TestKeyStoreEntry.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
public void runTest(Provider p) throws Exception {
    try (FileOutputStream fos = new FileOutputStream("jceks");
            FileInputStream fis = new FileInputStream("jceks");) {

        KeyStore ks = KeyStore.getInstance("jceks", p);
        // create an empty key store
        ks.load(null, null);

        // store the secret keys
        String aliasHead = new String("secretKey");
        for (int j = 0; j < NUM_ALGOS; j++) {
            ks.setKeyEntry(aliasHead + j, sks[j], PASSWDK, null);
        }

        // write the key store out to a file
        ks.store(fos, PASSWDF);
        // wipe clean the existing key store
        for (int k = 0; k < NUM_ALGOS; k++) {
            ks.deleteEntry(aliasHead + k);
        }
        if (ks.size() != 0) {
            throw new RuntimeException("ERROR: re-initialization failed");
        }

        // reload the key store with the file
        ks.load(fis, PASSWDF);

        // check the integrity/validaty of the key store
        Key temp = null;
        String alias = null;
        if (ks.size() != NUM_ALGOS) {
            throw new RuntimeException("ERROR: wrong number of key"
                    + " entries");
        }

        for (int m = 0; m < ks.size(); m++) {
            alias = aliasHead + m;
            temp = ks.getKey(alias, PASSWDK);
            // compare the keys
            if (!temp.equals(sks[m])) {
                throw new RuntimeException("ERROR: key comparison (" + m
                        + ") failed");
            }
            // check the type of key
            if (ks.isCertificateEntry(alias) || !ks.isKeyEntry(alias)) {
                throw new RuntimeException("ERROR: type identification ("
                        + m + ") failed");
            }
        }
    }
}