Example usage for java.security KeyStore.PasswordProtection KeyStore.PasswordProtection

List of usage examples for java.security KeyStore.PasswordProtection KeyStore.PasswordProtection

Introduction

In this page you can find the example usage for java.security KeyStore.PasswordProtection KeyStore.PasswordProtection.

Prototype

public PasswordProtection(char[] password) 

Source Link

Document

Creates a password parameter.

Usage

From source file:Main.java

public static KeyStore.PrivateKeyEntry getThaliListenerKeyStoreEntry(KeyStore keyStore, char[] passPhrase)
        throws UnrecoverableEntryException, NoSuchAlgorithmException, KeyStoreException {
    return (KeyStore.PrivateKeyEntry) keyStore.getEntry(ThaliKeyAlias,
            new KeyStore.PasswordProtection(passPhrase));
}

From source file:com.springcryptoutils.core.key.PrivateKeyFactoryBean.java

public void afterPropertiesSet()
        throws NoSuchAlgorithmException, UnrecoverableEntryException, KeyStoreException {
    KeyStore.PrivateKeyEntry privateKeyEntry = (KeyStore.PrivateKeyEntry) keystore.getEntry(alias,
            new KeyStore.PasswordProtection(password.toCharArray()));

    if (privateKeyEntry == null) {
        throw new PrivateKeyException("no such private key with alias: " + alias);
    }/* ww w . ja  va 2 s.  c o  m*/

    this.privateKey = privateKeyEntry.getPrivateKey();
}

From source file:davmail.http.DavGatewaySSLProtocolSocketFactory.java

private KeyStore.ProtectionParameter getProtectionParameter(String password) {
    if (password != null && password.length() > 0) {
        // password provided: create a PasswordProtection
        return new KeyStore.PasswordProtection(password.toCharArray());
    } else {//from   w  ww . j ava  2 s  .c o m
        // request password at runtime through a callback
        return new KeyStore.CallbackHandlerProtection(new CallbackHandler() {
            public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
                if (callbacks.length > 0 && callbacks[0] instanceof PasswordCallback) {
                    PasswordPromptDialog passwordPromptDialog = new PasswordPromptDialog(
                            ((PasswordCallback) callbacks[0]).getPrompt());
                    ((PasswordCallback) callbacks[0]).setPassword(passwordPromptDialog.getPassword());
                }
            }
        });
    }
}

From source file:net.link.util.common.KeyUtils.java

public static PrivateKeyEntry loadFirstPrivateKeyEntry(String keystoreType, InputStream keyStoreInputStream,
        char[] keyStorePassword, char[] keyEntryPassword) {

    /* Find the keystore. */
    KeyStore keyStore = loadKeyStore(keystoreType, keyStoreInputStream, keyStorePassword);
    Enumeration<String> aliases;
    try {/*  w  ww  . j  av a2s . c o  m*/
        aliases = keyStore.aliases();
    } catch (KeyStoreException e) {
        throw new InternalInconsistencyException("could not get aliases", e);
    }
    String alias = null;
    while (aliases.hasMoreElements()) {
        alias = aliases.nextElement();
        try {
            if (keyStore.isKeyEntry(alias))
                break;
        } catch (KeyStoreException e) {
            throw new InternalInconsistencyException(e);
        }

        alias = null;
    }
    if (alias == null)
        throw new InternalInconsistencyException("no private key found in keystore");

    /* Get the private key entry. */
    try {
        return (PrivateKeyEntry) keyStore.getEntry(alias, new KeyStore.PasswordProtection(keyEntryPassword));
    } catch (UnrecoverableEntryException e) {
        throw new InternalInconsistencyException("error retrieving key", e);
    } catch (NoSuchAlgorithmException e) {
        throw new InternalInconsistencyException("error retrieving key", e);
    } catch (KeyStoreException e) {
        throw new InternalInconsistencyException("error retrieving key", e);
    }
}

From source file:net.link.util.common.KeyUtils.java

public static PrivateKeyEntry loadPrivateKeyEntry(String keystoreType, InputStream keyStoreInputStream,
        char[] keyStorePassword, char[] keyEntryPassword, String alias) {

    /* Find the keystore. */
    KeyStore keyStore = loadKeyStore(keystoreType, keyStoreInputStream, keyStorePassword);
    Enumeration<String> aliases;
    try {/*from  www  .  jav a 2s  .co  m*/
        aliases = keyStore.aliases();
    } catch (KeyStoreException e) {
        throw new InternalInconsistencyException("could not get aliases", e);
    }
    if (!aliases.hasMoreElements())
        throw new InternalInconsistencyException("keystore is empty");

    try {
        if (!keyStore.isKeyEntry(alias))
            throw new InternalInconsistencyException(String.format("not key entry: %s", alias));
    } catch (KeyStoreException e) {
        throw new InternalInconsistencyException("key store error", e);
    }

    /* Get the private key entry. */
    try {
        return (PrivateKeyEntry) keyStore.getEntry(alias, new KeyStore.PasswordProtection(keyEntryPassword));
    } catch (UnrecoverableEntryException e) {
        throw new InternalInconsistencyException("error retrieving key", e);
    } catch (NoSuchAlgorithmException e) {
        throw new InternalInconsistencyException("error retrieving key", e);
    } catch (KeyStoreException e) {
        throw new InternalInconsistencyException("error retrieving key", e);
    }
}

From source file:net.link.util.common.KeyUtils.java

public static KeyStore addEntry(KeyStore keyStore, KeyStore.Entry entry, char[] keyEntryPassword,
        String alias) {/*w  w w .ja  v a  2s  .  c  om*/

    try {
        keyStore.setEntry(alias, entry, new KeyStore.PasswordProtection(keyEntryPassword));

        return keyStore;
    } catch (KeyStoreException e) {
        throw new InternalInconsistencyException(
                String.format("could not set new entry on keystore for alias: %s", alias), e);
    }
}

From source file:com.thoughtworks.go.security.X509CertificateGenerator.java

public Registration createAgentCertificate(final File authorityKeystore, String agentHostname) {
    Date epoch = new Date(0);
    KeyPair agentKeyPair = generateKeyPair();
    try {// w w  w  .  j  av a2s  .  c o  m
        KeyStore store = loadOrCreateCAKeyStore(authorityKeystore);
        KeyStore.PrivateKeyEntry intermediateEntry = (KeyStore.PrivateKeyEntry) store
                .getEntry("ca-intermediate", new KeyStore.PasswordProtection(PASSWORD_AS_CHAR_ARRAY));

        X509Certificate[] chain = new X509Certificate[3];
        chain[2] = (X509Certificate) store.getCertificate("ca-cert");
        chain[1] = (X509Certificate) intermediateEntry.getCertificate();
        chain[0] = createAgentCertificate(agentKeyPair.getPublic(), intermediateEntry.getPrivateKey(),
                chain[1].getPublicKey(), agentHostname, epoch);
        return new Registration(agentKeyPair.getPrivate(), chain);
    } catch (Exception e) {
        throw bomb("Couldn't create agent certificate", e);
    }
}

From source file:davmail.util.ClientCertificateTest.java

private SSLContext createSSLContext()
        throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, KeyManagementException,
        KeyStoreException, IOException, CertificateException, UnrecoverableKeyException {
    // PKCS11 client certificate settings
    String pkcs11Library = Settings.getProperty("davmail.ssl.pkcs11Library");

    String clientKeystoreType = Settings.getProperty("davmail.ssl.clientKeystoreType");
    // set default keystore type
    if (clientKeystoreType == null || clientKeystoreType.length() == 0) {
        clientKeystoreType = "PKCS11";
    }/*from  w  ww  .ja v a  2s  . com*/

    if (pkcs11Library != null && pkcs11Library.length() > 0 && "PKCS11".equals(clientKeystoreType)) {
        StringBuilder pkcs11Buffer = new StringBuilder();
        pkcs11Buffer.append("name=DavMail\n");
        pkcs11Buffer.append("library=").append(pkcs11Library).append('\n');
        String pkcs11Config = Settings.getProperty("davmail.ssl.pkcs11Config");
        if (pkcs11Config != null && pkcs11Config.length() > 0) {
            pkcs11Buffer.append(pkcs11Config).append('\n');
        }
        SunPKCS11ProviderHandler.registerProvider(pkcs11Buffer.toString());
    }
    String algorithm = KeyManagerFactory.getDefaultAlgorithm();
    if ("SunX509".equals(algorithm)) {
        algorithm = "NewSunX509";
    } else if ("IbmX509".equals(algorithm)) {
        algorithm = "NewIbmX509";
    }
    KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(algorithm);

    ArrayList<KeyStore.Builder> keyStoreBuilders = new ArrayList<KeyStore.Builder>();
    // PKCS11 (smartcard) keystore with password callback
    KeyStore.Builder scBuilder = KeyStore.Builder.newInstance("PKCS11", null, getProtectionParameter(null));
    //keyStoreBuilders.add(scBuilder);

    String clientKeystoreFile = Settings.getProperty("davmail.ssl.clientKeystoreFile");
    String clientKeystorePass = Settings.getProperty("davmail.ssl.clientKeystorePass");
    if (clientKeystoreFile != null && clientKeystoreFile.length() > 0
            && ("PKCS12".equals(clientKeystoreType) || "JKS".equals(clientKeystoreType))) {
        // PKCS12 file based keystore
        KeyStore.Builder fsBuilder = KeyStore.Builder.newInstance(clientKeystoreType, null,
                new File(clientKeystoreFile), getProtectionParameter(clientKeystorePass));
        keyStoreBuilders.add(fsBuilder);
    }
    System.setProperty("javax.net.debug", "ssl,handshake");
    //try {
    Provider sunMSCAPI = new sun.security.mscapi.SunMSCAPI();
    //Security.insertProviderAt(sunMSCAPI, 1);
    KeyStore keyStore = KeyStore.getInstance("Windows-MY", sunMSCAPI);

    keyStore.load(null, null);

    keyStoreBuilders.add(KeyStore.Builder.newInstance(keyStore, new KeyStore.PasswordProtection(null)));

    /*} catch (IOException e) {
    e.printStackTrace();
    } catch (CertificateException e) {
    e.printStackTrace();
    }*/

    ManagerFactoryParameters keyStoreBuilderParameters = new KeyStoreBuilderParameters(keyStoreBuilders);
    keyManagerFactory.init(keyStoreBuilderParameters);
    //keyManagerFactory.init(keyStore, null);

    // Get a list of key managers
    KeyManager[] keyManagers = keyManagerFactory.getKeyManagers();

    // Walk through the key managers and replace all X509 Key Managers with
    // a specialized wrapped DavMail X509 Key Manager
    for (int i = 0; i < keyManagers.length; i++) {
        KeyManager keyManager = keyManagers[i];
        if (keyManager instanceof X509KeyManager) {
            keyManagers[i] = new DavMailX509KeyManager((X509KeyManager) keyManager);
        }
    }

    //keyManagers = new KeyManager[]{new DavMailX509KeyManager(new X509KeyManagerImpl())}

    SSLContext context = SSLContext.getInstance("TLS");
    context.init(keyManagers, new TrustManager[] { new DavGatewayX509TrustManager() }, null);
    return context;
}

From source file:com.thoughtworks.go.security.X509CertificateGenerator.java

boolean verifySigned(File keystore, Certificate agentCertificate) {
    try {// w  w  w .  jav a  2s  .  c  o m
        KeyStore store = KeyStore.getInstance("JKS");
        FileInputStream inputStream = new FileInputStream(keystore);
        store.load(inputStream, PASSWORD_AS_CHAR_ARRAY);
        IOUtils.closeQuietly(inputStream);
        KeyStore.PrivateKeyEntry intermediateEntry = (KeyStore.PrivateKeyEntry) store
                .getEntry("ca-intermediate", new KeyStore.PasswordProtection(PASSWORD_AS_CHAR_ARRAY));
        Certificate intermediateCertificate = intermediateEntry.getCertificate();
        agentCertificate.verify(intermediateCertificate.getPublicKey());
        return true;
    } catch (Exception e) {
        return false;
    }
}

From source file:com.bcmcgroup.flare.client.ClientUtil.java

/**
 * Fetch private key from KeyStore//  w w  w .jav a 2  s . co  m
 *
 * @param keyStorePath a String containing the path to the KeyStore
 * @param keyStorePW   a String containing the KeyStore password
 * @param keyName      a String containing the alias of targeted certificate
 * @param keyPW        a String containing the key password
 * @return the PrivateKeyEntry object containing the targeted private key
 *
 */
public static PrivateKeyEntry getKeyEntry(String keyStorePath, String keyStorePW, String keyName,
        String keyPW) {
    KeyStore ks;
    PrivateKeyEntry keyEntry = null;
    FileInputStream is = null;
    try {
        ks = KeyStore.getInstance("JKS");
        is = new FileInputStream(keyStorePath);
        ks.load(is, keyStorePW.toCharArray());
        keyEntry = (PrivateKeyEntry) ks.getEntry(keyName, new KeyStore.PasswordProtection(keyPW.toCharArray()));
    } catch (FileNotFoundException e) {
        logger.error("FileNotFoundException when attempting to get a key entry in a keystore. " + e);
    } catch (IOException e) {
        logger.error("IOException when attempting to get a key entry in a keystore. " + e);
    } catch (KeyStoreException e) {
        logger.error("KeyStoreException when attempting to get a key entry in a keystore. " + e);
    } catch (NoSuchAlgorithmException e) {
        logger.error("NoSuchAlgorithmException when attempting to get a key entry in a keystore. " + e);
    } catch (CertificateException e) {
        logger.error("CertificateException when attempting to get a key entry in a keystore. " + e);
    } catch (UnrecoverableEntryException e) {
        logger.error("UnrecoverableEntryException when attempting to get a key entry in a keystore. " + e);
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException ioe) {
                logger.error("IOException when attempting to close an input stream. " + ioe);
            }
        }
    }
    return keyEntry;
}