/** 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) { } }
/** * Remove a key with the specified alias from the keystore. * * @param keyStore to remove from * @param alias of key to remove * @return true if the key alias was removed * @throws CryptoTokenOfflineException if the keystore was null * @throws KeyStoreException for keystore related errors * @throws SignServerException if the keystore did not contain a key with the specified alias */ public static boolean removeKey(final KeyStore keyStore, final String alias) throws CryptoTokenOfflineException, KeyStoreException, SignServerException { if (keyStore == null) { throw new CryptoTokenOfflineException("Token offline"); } if (!keyStore.containsAlias(alias)) { throw new SignServerException("No such alias in token: " + alias); } keyStore.deleteEntry(alias); return !keyStore.containsAlias(alias); }
/** Returns a trust store merged from the internal keystore and system keystore. */ public static KeyStore getTrustStore(Context context) throws KeyStoreException, NoSuchProviderException, NoSuchAlgorithmException, CertificateException, IOException { if (sTrustStore == null) { // load internal truststore from file sTrustStore = KeyStore.getInstance("BKS", PGP.PROVIDER); InputStream in = context.getResources().openRawResource(R.raw.truststore); sTrustStore.load(in, "changeit".toCharArray()); // load system trust store KeyStore systemStore = loadSystemTrustStore(); // copy system entries to our trust store Enumeration<String> aliases = systemStore.aliases(); while (aliases.hasMoreElements()) { String alias = aliases.nextElement(); Certificate cert = systemStore.getCertificate(alias); if (sTrustStore.containsAlias(alias)) alias = "system_" + alias; sTrustStore.setCertificateEntry(alias, cert); } } return sTrustStore; }
// check the existing aliases private void checkAlias(KeyStore obj, int range) throws KeyStoreException { for (int k = 0; k < range; k++) { if (!obj.containsAlias(ALIAS_HEAD + k)) { throw new RuntimeException("ERROR: alias (" + k + ") should exist"); } } }
/** * Takes a GFIPM entity ID or a Java key store entry alias name and deletes its entry from the * Java key store. Writes out an error messages on an exception. * * @param entityid The GFIPM entity or key store alias to be deleted. * @return true on success, false otherwise. */ public boolean deleteEntry(String entityid) { if (entityid == null) { System.err.println("ERROR: GFIPMKeystore.deleteEntry: No entityid or alias name. Aborted."); System.err.flush(); return false; } String alias = makeEntityAliasName(entityid); try { if (keyStore.containsAlias(alias)) { if (verboseOut) { System.out.println("Key store: delete entry " + alias); System.out.flush(); } keyStore.deleteEntry(alias); modifiedFlag = true; } else { if (verboseOut) { System.out.println("Key store: Entry to be delete not found with alias " + alias); } } } catch (KeyStoreException e) { System.err.println("ERROR: GFIPMKeystore.deleteEntry failed: "); System.err.println(e.toString()); System.err.flush(); return false; } return true; } // end deleteEntry
/** * 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; } }
/** * 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); } }
public boolean hasServerIdentityAlias() { try { if (!mKeyStore.containsAlias(LOCAL_IDENTITY_ALIAS)) { LogUtils.e("Key store missing identity for " + LOCAL_IDENTITY_ALIAS); return false; } } catch (KeyStoreException e) { LogUtils.e("Key store exception occurred", e); return false; } return true; }
/** * Returns the trusted cert for the specified id. * * @param id The id of the Certificate to retrieve. * @param store_password The passphrase used to unlock the keystore may be {@code null} for * keystores with no passphrase. * @return Certificate for the specified ID or null if the store does not contain the specified * certificate. * @throws KeyStoreException When the wrong keystore has been provided. * @throws IOException For errors related to processing the keystore. */ X509Certificate getTrustedCertificate(ID id, char[] store_password) throws KeyStoreException, IOException { String alias = id.toString(); synchronized (keystore_manager) { KeyStore store = keystore_manager.loadKeyStore(store_password); if (!store.containsAlias(alias)) { return null; } return (X509Certificate) store.getCertificate(alias); } }
public synchronized void storeCertificate(Certificate peerCert) { try { String alias = String.format(KeyStoreManager.REMOTE_IDENTITY_ALIAS_PATTERN, peerCert.hashCode()); if (mKeyStore.containsAlias(alias)) { LogUtils.w("Deleting existing entry for " + alias); mKeyStore.deleteEntry(alias); } LogUtils.i("Adding cert to keystore: " + alias); mKeyStore.setCertificateEntry(alias, peerCert); store(); } catch (KeyStoreException e) { LogUtils.e("Storing cert failed", e); } }
/** Creates the X509Credential from the TrustStore certificate. */ public static X509Credential loadCredentialFromTrustStore(String alias, KeyStore trustStore) throws RelyingPartyException { X509Credential credential = null; java.security.cert.X509Certificate cert = null; try { if (trustStore.containsAlias(alias)) { cert = (java.security.cert.X509Certificate) trustStore.getCertificate(alias); credential = new X509CredentialImpl(cert); } } catch (KeyStoreException e) { log.error("Error while loading credentials from trust store", e); throw new RelyingPartyException("Error while loading credentials from trust store", e); } return credential; }
public void addPrivateKey( @Nonnull @Nonempty final String sAlias, @Nonnull final Key aKey, @Nonnull final String sPassword) throws OpenAS2Exception { ValueEnforcer.notEmpty(sAlias, "Alias"); ValueEnforcer.notNull(aKey, "Key"); ValueEnforcer.notNull(sPassword, "Password"); final KeyStore aKeyStore = getKeyStore(); try { if (!aKeyStore.containsAlias(sAlias)) throw new CertificateNotFoundException(null, sAlias); final Certificate[] aCertChain = aKeyStore.getCertificateChain(sAlias); aKeyStore.setKeyEntry(sAlias, aKey, sPassword.toCharArray(), aCertChain); save(getFilename(), getPassword()); } catch (final GeneralSecurityException ex) { throw WrappedOpenAS2Exception.wrap(ex); } }
public void addCertificate( @Nonnull @Nonempty final String sAlias, @Nonnull final X509Certificate aCert, final boolean bOverwrite) throws OpenAS2Exception { ValueEnforcer.notEmpty(sAlias, "Alias"); ValueEnforcer.notNull(aCert, "Cert"); final KeyStore aKeyStore = getKeyStore(); try { if (aKeyStore.containsAlias(sAlias) && !bOverwrite) throw new CertificateExistsException(sAlias); aKeyStore.setCertificateEntry(sAlias, aCert); save(getFilename(), getPassword()); s_aLogger.info( "Added certificate alias '" + sAlias + "' of certificate '" + aCert.getSubjectDN()); } catch (final GeneralSecurityException ex) { throw WrappedOpenAS2Exception.wrap(ex); } }
/** * Returns the trusted cert chain for the specified id. * * @param id The ID of the certificate who's certificate chain is desired. * @return Certificate chain for the specified ID or null if the PSE does not contain the * specified certificate. * @throws KeyStoreException When the wrong keystore has been provided. * @throws IOException For errors related to processing the keystore. */ public X509Certificate[] getTrustedCertificateChain(ID id) throws KeyStoreException, IOException { String alias = id.toString(); synchronized (keystore_manager) { KeyStore store = keystore_manager.loadKeyStore(keystore_password); if (!store.containsAlias(alias)) { return null; } Certificate certs[] = store.getCertificateChain(alias); if (null == certs) { return null; } X509Certificate x509certs[] = new X509Certificate[certs.length]; System.arraycopy(certs, 0, x509certs, 0, certs.length); return x509certs; } }
/** Do action. */ @Override protected void doAction() { try { KeyStoreHistory history = kseFrame.getActiveKeyStoreHistory(); KeyStoreState currentState = history.getCurrentState(); KeyStoreState newState = currentState.createBasisForNextState(this); KeyStore keyStore = newState.getKeyStore(); String alias = kseFrame.getSelectedEntryAlias(); DGetAlias dGetAlias = new DGetAlias( frame, res.getString("RenameTrustedCertificateAction.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("RenameTrustedCertificateAction.RenameAliasIdentical.message"), alias), res.getString("RenameTrustedCertificateAction.RenameEntry.Title"), JOptionPane.WARNING_MESSAGE); return; } if (keyStore.containsAlias(newAlias)) { String message = MessageFormat.format( res.getString("RenameTrustedCertificateAction.OverWriteEntry.message"), newAlias); int selected = JOptionPane.showConfirmDialog( frame, message, res.getString("RenameTrustedCertificateAction.RenameEntry.Title"), JOptionPane.YES_NO_OPTION); if (selected != JOptionPane.YES_OPTION) { return; } keyStore.deleteEntry(newAlias); newState.removeEntryPassword(newAlias); } Certificate cert = keyStore.getCertificate(alias); keyStore.setCertificateEntry(newAlias, cert); keyStore.deleteEntry(alias); currentState.append(newState); kseFrame.updateControls(true); } catch (Exception ex) { DError.displayError(frame, ex); } }
/** Generate a secret key in the currently opened KeyStore. */ public void generateSecret() { try { int secretKeySize = applicationSettings.getGenerateSecretKeySize(); SecretKeyType secretKeyType = applicationSettings.getGenerateSecretKeyType(); DGenerateSecretKey dGenerateSecretKey = new DGenerateSecretKey(frame, secretKeyType, secretKeySize); dGenerateSecretKey.setLocationRelativeTo(frame); dGenerateSecretKey.setVisible(true); if (!dGenerateSecretKey.isSuccessful()) { return; } secretKeySize = dGenerateSecretKey.getSecretKeySize(); secretKeyType = dGenerateSecretKey.getSecretKeyType(); applicationSettings.setGenerateSecretKeySize(secretKeySize); applicationSettings.setGenerateSecretKeyType(secretKeyType); SecretKey secretKey = SecretKeyUtil.generateSecretKey(secretKeyType, secretKeySize); KeyStoreHistory history = kseFrame.getActiveKeyStoreHistory(); KeyStoreState currentState = history.getCurrentState(); KeyStoreState newState = currentState.createBasisForNextState(this); KeyStore keyStore = newState.getKeyStore(); DGetAlias dGetAlias = new DGetAlias( frame, res.getString("GenerateSecretKeyAction.NewSecretKeyEntryAlias.Title"), null); dGetAlias.setLocationRelativeTo(frame); dGetAlias.setVisible(true); String alias = dGetAlias.getAlias(); if (alias == null) { return; } if (keyStore.containsAlias(alias)) { String message = MessageFormat.format( res.getString("GenerateSecretKeyAction.OverWriteEntry.message"), alias); int selected = JOptionPane.showConfirmDialog( frame, message, res.getString("GenerateSecretKeyAction.NewSecretKeyEntryAlias.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("GenerateSecretKeyAction.NewSecretKeyEntryPassword.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, secretKey, password.toCharArray(), null); newState.setEntryPassword(alias, password); currentState.append(newState); kseFrame.updateControls(true); JOptionPane.showMessageDialog( frame, res.getString("GenerateSecretKeyAction.SecretKeyGenerationSuccessful.message"), res.getString("GenerateSecretKeyAction.GenerateSecretKey.Title"), JOptionPane.INFORMATION_MESSAGE); } catch (Exception ex) { DError.displayError(frame, ex); } }
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"); } }