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

The following examples show how to use java.security.KeyStore#containsAlias() . 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: CertificateUtility.java    From blackduck-alert with Apache License 2.0 6 votes vote down vote up
public synchronized void removeCertificate(String certificateAlias) throws AlertException {
    logger.debug("Removing certificate by alias from trust store.");
    if (StringUtils.isBlank(certificateAlias)) {
        throw new AlertException("The alias cannot be blank");
    }

    try {
        File trustStore = getAndValidateTrustStoreFile();
        KeyStore keyStore = getAsKeyStore(trustStore, getTrustStorePassword(), getTrustStoreType());
        if (keyStore.containsAlias(certificateAlias)) {
            keyStore.deleteEntry(certificateAlias);
            try (OutputStream stream = new BufferedOutputStream(new FileOutputStream(trustStore))) {
                keyStore.store(stream, getTrustStorePassword());
            }
        }
    } catch (IOException | CertificateException | NoSuchAlgorithmException | KeyStoreException e) {
        throw new AlertException("There was a problem removing the certificate.", e);
    }
}
 
Example 2
Source File: AbstractAndroidKeystoreSecretKeyWrapper.java    From Android-Vault with Apache License 2.0 6 votes vote down vote up
private KeyPair getKeyPair() throws GeneralSecurityException, IOException {
    synchronized (mAlias) {
        if (mKeyPair == null) {
            final KeyStore keyStore = KeyStore.getInstance(EncryptionConstants.ANDROID_KEY_STORE);
            keyStore.load(null);
            if (!keyStore.containsAlias(mAlias)) {
                generateKeyPair(mContext, mAlias);
            }
            // Even if we just generated the key, always read it back to ensure we
            // can read it successfully.
            final KeyStore.PrivateKeyEntry entry = (KeyStore.PrivateKeyEntry) keyStore.getEntry(mAlias, null);
            mKeyPair = new KeyPair(entry.getCertificate().getPublicKey(), entry.getPrivateKey());
        }
    }
    return mKeyPair;
}
 
Example 3
Source File: KeyGenHelper.java    From privacy-friendly-food-tracker with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Generates a rsa key pair if it not exists.
 *
 * @param context the application context
 */
public static void generateKey(Context context) throws Exception {
    KeyStore keyStore;
    keyStore = KeyStore.getInstance(AndroidKeyStore);
    keyStore.load(null, null);

    // Generate the RSA key pairs for encryption
    if (!keyStore.containsAlias(KEY_ALIAS)) {
        Calendar start = Calendar.getInstance();
        Calendar end = Calendar.getInstance();
        end.add(Calendar.YEAR, 30);

        KeyPairGeneratorSpec spec = new KeyPairGeneratorSpec.Builder(context)
                .setAlias(KEY_ALIAS)
                .setSubject(new X500Principal("CN=" + KEY_ALIAS))
                .setSerialNumber(BigInteger.TEN)
                .setStartDate(start.getTime())
                .setEndDate(end.getTime())
                .build();
        KeyPairGenerator kpg = KeyPairGenerator.getInstance(KeyProperties.KEY_ALGORITHM_RSA, AndroidKeyStore);
        kpg.initialize(spec);
        kpg.generateKeyPair();
    }
}
 
Example 4
Source File: KeyStoreFileManager.java    From fdroidclient with GNU General Public License v3.0 6 votes vote down vote up
public static String renameKey(String keystorePath, String storePass, String oldKeyName, String newKeyName, String keyPass)
        throws Exception {
    char[] keyPw = null;

    try {
        KeyStore ks = loadKeyStore(keystorePath, storePass);
        if (ks instanceof JksKeyStore) newKeyName = newKeyName.toLowerCase(Locale.ENGLISH);

        if (ks.containsAlias(newKeyName)) throw new KeyNameConflictException();

        keyPw = PasswordObfuscator.getInstance().decodeAliasPassword(keystorePath, oldKeyName, keyPass);
        Key key = ks.getKey(oldKeyName, keyPw);
        Certificate cert = ks.getCertificate(oldKeyName);

        ks.setKeyEntry(newKeyName, key, keyPw, new Certificate[]{cert});
        ks.deleteEntry(oldKeyName);

        writeKeyStore(ks, keystorePath, storePass);
        return newKeyName;
    } finally {
        PasswordObfuscator.flush(keyPw);
    }
}
 
Example 5
Source File: NettyTransportSupport.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
private static void validateAlias(KeyStore store, String alias) throws IllegalArgumentException, KeyStoreException {
   if (!store.containsAlias(alias)) {
      throw new IllegalArgumentException("The alias '" + alias + "' doesn't exist in the key store");
   }

   if (!store.isKeyEntry(alias)) {
      throw new IllegalArgumentException("The alias '" + alias + "' in the keystore doesn't represent a key entry");
   }
}
 
Example 6
Source File: PFSecurityUtilsOld.java    From PFLockScreen-Android with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isKeystoreContainAlias(String alias) throws PFSecurityException {
    final KeyStore keyStore = loadKeyStore();
    try {
        return keyStore.containsAlias(alias);
    } catch (KeyStoreException e) {
        e.printStackTrace();
        throw new PFSecurityException(
                e.getMessage(),
                PFSecurityUtilsErrorCodes.ERROR_KEY_STORE
        );
    }
}
 
Example 7
Source File: KeyGenHelper.java    From privacy-friendly-food-tracker with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Checks if a generated key already exist
 *
 * @return true if a key exists
 */
public static boolean isKeyGenerated() {
    KeyStore keyStore;
    try {
        keyStore = KeyStore.getInstance(AndroidKeyStore);
        keyStore.load(null);
        return keyStore.containsAlias(KEY_ALIAS);
    } catch (Exception e) {
        Log.e("LoggingKeyGenHelper: ", "Can not check if key exists. Default return false.");
    }
    return false;
}
 
Example 8
Source File: KeyStoreBasedMasterKey.java    From kafka-encryption with Apache License 2.0 5 votes vote down vote up
public KeyStoreBasedMasterKey(File masterKeyFile, String masterKeyPass, String alias, AesGcmNoPaddingCryptoAlgorithm aesGcmNoPaddingCryptoAlgorithm) {
    this.aesGcmNoPaddingCryptoAlgorithm = aesGcmNoPaddingCryptoAlgorithm;
    try (InputStream keystoreStream = new FileInputStream(masterKeyFile)) {
        KeyStore keystore = KeyStore.getInstance("PKCS12");
        keystore.load(keystoreStream, masterKeyPass.toCharArray());
        if (!keystore.containsAlias(alias)) {
            throw new RuntimeException("Alias for key not found");
        }
        masterKey = keystore.getKey(alias, masterKeyPass.toCharArray());

    }
    catch (Exception e) {
        throw new RuntimeException(e);
    }
}
 
Example 9
Source File: KeyStoreHelper.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
@RequiresApi(Build.VERSION_CODES.M)
private static boolean hasKeyStoreEntry() {
  try {
    KeyStore ks = KeyStore.getInstance(ANDROID_KEY_STORE);
    ks.load(null);

    return ks.containsAlias(KEY_ALIAS) && ks.entryInstanceOf(KEY_ALIAS, KeyStore.SecretKeyEntry.class);
  } catch (KeyStoreException | IOException | NoSuchAlgorithmException | CertificateException e) {
    throw new AssertionError(e);
  }
}
 
Example 10
Source File: TestKeyStoreBasic.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
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");
        }
    }
}
 
Example 11
Source File: CipherStorageBase.java    From react-native-keychain with MIT License 5 votes vote down vote up
/** Remove key with provided name from security storage. */
@Override
public void removeKey(@NonNull final String alias) throws KeyStoreAccessException {
  final String safeAlias = getDefaultAliasIfEmpty(alias, getDefaultAliasServiceName());
  final KeyStore ks = getKeyStoreAndLoad();

  try {
    if (ks.containsAlias(safeAlias)) {
      ks.deleteEntry(safeAlias);
    }
  } catch (GeneralSecurityException ignored) {
    /* only one exception can be raised by code: 'KeyStore is not loaded' */
  }
}
 
Example 12
Source File: AdvancedModifiableKeyStoreDecorator.java    From wildfly-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
@Override
protected void executeRuntimeStep(final OperationContext context, final ModelNode operation) throws OperationFailedException {
    ModifiableKeyStoreService keyStoreService = getModifiableKeyStoreService(context);
    KeyStore keyStore = keyStoreService.getModifiableValue();

    String alias = ALIAS.resolveModelAttribute(context, operation).asString();
    String algorithm = ALGORITHM.resolveModelAttribute(context, operation).asStringOrNull();
    String signatureAlgorithm = SIGNATURE_ALGORITHM.resolveModelAttribute(context, operation).asStringOrNull();
    Integer keySize = KEY_SIZE.resolveModelAttribute(context, operation).asIntOrNull();
    String distinguishedName = DISTINGUISHED_NAME.resolveModelAttribute(context, operation).asString();
    String notBefore = NOT_BEFORE.resolveModelAttribute(context, operation).asStringOrNull();
    Long validity = VALIDITY.resolveModelAttribute(context, operation).asLong();
    ModelNode extensions = EXTENSIONS.resolveModelAttribute(context, operation);
    ExceptionSupplier<CredentialSource, Exception> credentialSourceSupplier = null;
    ModelNode credentialReference = CREDENTIAL_REFERENCE.resolveModelAttribute(context, operation);
    if (credentialReference.isDefined()) {
        credentialSourceSupplier = CredentialReference.getCredentialSourceSupplier(context, CREDENTIAL_REFERENCE, operation, null);
    }
    char[] keyPassword = resolveKeyPassword(((KeyStoreService) keyStoreService), credentialSourceSupplier);

    try {
        if (keyStore.containsAlias(alias)) {
            throw ROOT_LOGGER.keyStoreAliasAlreadyExists(alias);
        }
        SelfSignedX509CertificateAndSigningKey.Builder certAndKeyBuilder = SelfSignedX509CertificateAndSigningKey.builder();
        certAndKeyBuilder.setDn(new X500Principal(distinguishedName));
        if (algorithm != null) {
            certAndKeyBuilder.setKeyAlgorithmName(algorithm);
        }
        if (signatureAlgorithm != null) {
            certAndKeyBuilder.setSignatureAlgorithmName(signatureAlgorithm);
        }
        if (keySize != null) {
            certAndKeyBuilder.setKeySize(keySize);
        }
        final ZonedDateTime notBeforeDateTime;
        if (notBefore != null) {
            notBeforeDateTime = ZonedDateTime.from(NOT_VALID_BEFORE_FORMATTER.parse(notBefore));
        } else {
            notBeforeDateTime = ZonedDateTime.now();
        }
        certAndKeyBuilder.setNotValidBefore(notBeforeDateTime);
        certAndKeyBuilder.setNotValidAfter(notBeforeDateTime.plusDays(validity));
        if (extensions.isDefined()) {
            for (ModelNode extension : extensions.asList()) {
                Boolean critical = CRITICAL.resolveModelAttribute(context, extension).asBoolean();
                String extensionName = NAME.resolveModelAttribute(context, extension).asString();
                String extensionValue = VALUE.resolveModelAttribute(context, extension).asString();
                certAndKeyBuilder.addExtension(critical, extensionName, extensionValue);
            }
        }

        SelfSignedX509CertificateAndSigningKey certAndKey = certAndKeyBuilder.build();
        final PrivateKey privateKey = certAndKey.getSigningKey();
        final X509Certificate[] certChain = new X509Certificate[1];
        certChain[0] = certAndKey.getSelfSignedCertificate();
        keyStore.setKeyEntry(alias, privateKey, keyPassword, certChain);
    } catch (Exception e) {
        rollbackCredentialStoreUpdate(CREDENTIAL_REFERENCE, context, credentialReference);
        if (e instanceof IllegalArgumentException) {
            throw new OperationFailedException(e);
        } else {
            throw new RuntimeException(e);
        }
    }
}
 
Example 13
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 14
Source File: KeyStoreFileManager.java    From java-n-IDE-for-Android with Apache License 2.0 4 votes vote down vote up
public static boolean containsKey( String keystorePath, String storePass, String keyName)
    throws Exception
{
    KeyStore ks = loadKeyStore(keystorePath, storePass);
    return ks.containsAlias( keyName);
}
 
Example 15
Source File: WriteP12Test.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
private void testKeyStore(KeyStore inputKeyStore, char[] keypass)
        throws KeyStoreException, UnrecoverableKeyException,
        NoSuchAlgorithmException {
    out.println("========== Key Store ==========");
    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();
        if (!inputKeyStore.containsAlias(alias)) {
            throw new RuntimeException("Alias not found");
        }
        out.println("Alias " + idx + " : " + alias);
        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, actually "
                    + retAlias + ", expected " + alias);
        }
        out.println("getCertificateAlias : " + retAlias);
        Certificate[] certs = inputKeyStore.getCertificateChain(alias);
        int i = 0;
        for (Certificate certification : certs) {
            out.println("getCertificateChain " + i
                    + ((X509Certificate) certification).getSubjectDN());
            i++;
        }
        if (inputKeyStore.isCertificateEntry(alias)) {
            throw new RuntimeException(
                    "inputKeystore should not be certEntry because this"
                            + " keystore only contain key pair entries.");
        }
        if (!inputKeyStore.isKeyEntry(alias)) {
            throw new RuntimeException("Entry type unknown.");
        }
        idx++;
    }
    int size = inputKeyStore.size();
    if (idx != size) {
        throw new RuntimeException("Size not match, actually " + idx
                + ", expected " + size);
    }
}
 
Example 16
Source File: Main.java    From jdk8u60 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Recovers entry associated with given alias.
 *
 * @return an array of objects, where the 1st element in the array is the
 * recovered entry, and the 2nd element is the password used to
 * recover it (null if no password).
 */
private Pair<Entry,char[]> recoverEntry(KeyStore ks,
                        String alias,
                        char[] pstore,
                        char[] pkey) throws Exception {

    if (ks.containsAlias(alias) == false) {
        MessageFormat form = new MessageFormat
            (rb.getString("Alias.alias.does.not.exist"));
        Object[] source = {alias};
        throw new Exception(form.format(source));
    }

    PasswordProtection pp = null;
    Entry entry;

    try {
        // First attempt to access entry without key password
        // (PKCS11 entry or trusted certificate entry, for example)

        entry = ks.getEntry(alias, pp);
        pkey = null;
    } catch (UnrecoverableEntryException une) {

        if(P11KEYSTORE.equalsIgnoreCase(ks.getType()) ||
            KeyStoreUtil.isWindowsKeyStore(ks.getType())) {
            // should not happen, but a possibility
            throw une;
        }

        // entry is protected

        if (pkey != null) {

            // try provided key password

            pp = new PasswordProtection(pkey);
            entry = ks.getEntry(alias, pp);

        } else {

            // try store pass

            try {
                pp = new PasswordProtection(pstore);
                entry = ks.getEntry(alias, pp);
                pkey = pstore;
            } catch (UnrecoverableEntryException une2) {
                if (P12KEYSTORE.equalsIgnoreCase(ks.getType())) {

                    // P12 keystore currently does not support separate
                    // store and entry passwords

                    throw une2;
                } else {

                    // prompt for entry password

                    pkey = getKeyPasswd(alias, null, null);
                    pp = new PasswordProtection(pkey);
                    entry = ks.getEntry(alias, pp);
                }
            }
        }
    }

    return Pair.of(entry, pkey);
}
 
Example 17
Source File: AcmeAccountService.java    From wildfly-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
@Override
public void start(StartContext startContext) throws StartException {
    try {
        final ServiceRegistry serviceRegistry = startContext.getController().getServiceContainer();
        final ModifiableKeyStoreService keyStoreService = CertificateAuthorityAccountDefinition.getModifiableKeyStoreService(serviceRegistry, keyStoreName);
        char[] keyPassword = resolveKeyPassword((KeyStoreService) keyStoreService);
        KeyStore keyStore = keyStoreInjector.getValue();
        CertificateAuthority certificateAuthority;
        if (certificateAuthorityName.equalsIgnoreCase(CertificateAuthority.LETS_ENCRYPT.getName())) {
            certificateAuthority = CertificateAuthority.LETS_ENCRYPT;
        } else {
            certificateAuthority = CertificateAuthorityDefinition.getCertificateAuthorityService(serviceRegistry, certificateAuthorityName).getValue();
        }

        AcmeAccount.Builder acmeAccountBuilder = AcmeAccount.builder()
                .setServerUrl(certificateAuthority.getUrl());
        if (certificateAuthority.getStagingUrl() != null) {
            acmeAccountBuilder.setStagingServerUrl(certificateAuthority.getStagingUrl());
        }
        if (! contactUrlsList.isEmpty()) {
            acmeAccountBuilder = acmeAccountBuilder.setContactUrls(contactUrlsList.toArray(new String[contactUrlsList.size()]));
        }
        boolean updateAccountKeyStore = false;
        if (keyStore.containsAlias(alias)) {
            // use existing account key pair
            X509Certificate certificate = (X509Certificate) keyStore.getCertificate(alias);
            if (certificate == null) {
                throw ROOT_LOGGER.unableToObtainCertificateAuthorityAccountCertificate(alias);
            }
            PrivateKey privateKey = (PrivateKey) keyStore.getKey(alias, keyPassword);
            if (privateKey == null) {
                throw ROOT_LOGGER.unableToObtainCertificateAuthorityAccountPrivateKey(alias);
            }
            acmeAccountBuilder = acmeAccountBuilder.setKey(certificate, privateKey);
        } else {
            updateAccountKeyStore = true;
        }
        acmeAccount = acmeAccountBuilder.build();
        if (updateAccountKeyStore) {
            saveCertificateAuthorityAccountKey(keyStoreService, keyPassword); // persist the generated key pair
        }
    } catch (Exception e) {
        throw ROOT_LOGGER.unableToStartService(e);
    }
}
 
Example 18
Source File: RenameTrustedCertificateAction.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();
		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);
	}
}
 
Example 19
Source File: Main.java    From jdk8u-dev-jdk with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Recovers entry associated with given alias.
 *
 * @return an array of objects, where the 1st element in the array is the
 * recovered entry, and the 2nd element is the password used to
 * recover it (null if no password).
 */
private Pair<Entry,char[]> recoverEntry(KeyStore ks,
                        String alias,
                        char[] pstore,
                        char[] pkey) throws Exception {

    if (ks.containsAlias(alias) == false) {
        MessageFormat form = new MessageFormat
            (rb.getString("Alias.alias.does.not.exist"));
        Object[] source = {alias};
        throw new Exception(form.format(source));
    }

    PasswordProtection pp = null;
    Entry entry;

    try {
        // First attempt to access entry without key password
        // (PKCS11 entry or trusted certificate entry, for example)

        entry = ks.getEntry(alias, pp);
        pkey = null;
    } catch (UnrecoverableEntryException une) {

        if(P11KEYSTORE.equalsIgnoreCase(ks.getType()) ||
            KeyStoreUtil.isWindowsKeyStore(ks.getType())) {
            // should not happen, but a possibility
            throw une;
        }

        // entry is protected

        if (pkey != null) {

            // try provided key password

            pp = new PasswordProtection(pkey);
            entry = ks.getEntry(alias, pp);

        } else {

            // try store pass

            try {
                pp = new PasswordProtection(pstore);
                entry = ks.getEntry(alias, pp);
                pkey = pstore;
            } catch (UnrecoverableEntryException une2) {
                if (P12KEYSTORE.equalsIgnoreCase(ks.getType())) {

                    // P12 keystore currently does not support separate
                    // store and entry passwords

                    throw une2;
                } else {

                    // prompt for entry password

                    pkey = getKeyPasswd(alias, null, null);
                    pp = new PasswordProtection(pkey);
                    entry = ks.getEntry(alias, pp);
                }
            }
        }
    }

    return Pair.of(entry, pkey);
}
 
Example 20
Source File: SESecurityManagerImpl.java    From BiglyBT with GNU General Public License v2.0 2 votes vote down vote up
protected SSLSocketFactory
addCertToTrustStore(
	String							alias,
	java.security.cert.Certificate	cert,
	boolean							update_https_factory )

	throws Exception
{
	try{
		this_mon.enter();

		KeyStore keystore = getTrustStore();

		if ( cert != null ){

			if ( keystore.containsAlias( alias )){

				keystore.deleteEntry( alias );
			}

			keystore.setCertificateEntry(alias, cert);

			FileOutputStream	out = null;

			try{
				out = FileUtil.newFileOutputStream(FileUtil.newFile(truststore_name));

				keystore.store(out, SESecurityManager.SSL_PASSWORD.toCharArray());

			}finally{

				if ( out != null ){

					out.close();
				}
			}
		}

			// pick up the changed trust store

		TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());

		tmf.init(keystore);

		SSLContext ctx = SSLContext.getInstance("SSL");

		ctx.init(null, tmf.getTrustManagers(), null);

		SSLSocketFactory	factory = ctx.getSocketFactory();

		if ( update_https_factory ){

			HttpsURLConnection.setDefaultSSLSocketFactory( factory );
		}

		return( factory );
	}finally{

		this_mon.exit();
	}
}