Example usage for java.security KeyStore isKeyEntry

List of usage examples for java.security KeyStore isKeyEntry

Introduction

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

Prototype

public final boolean isKeyEntry(String alias) throws KeyStoreException 

Source Link

Document

Returns true if the entry identified by the given alias was created by a call to setKeyEntry , or created by a call to setEntry with a PrivateKeyEntry or a SecretKeyEntry .

Usage

From source file:org.dasein.cloud.google.GenerateToken.java

public static String getToken(String iss, String p12File) {

    String header = "{\"alg\":\"RS256\",\"typ\":\"JWT\"}";
    String claimTemplate = "'{'\"iss\": \"{0}\", \"scope\": \"{1}\", \"aud\": \"{2}\", \"exp\": \"{3}\", \"iat\": \"{4}\"'}'";

    try {//w w  w  .j  a  v a2  s  .  c om
        StringBuffer token = new StringBuffer();

        //Encode the JWT Header and add it to our string to sign
        token.append(Base64.encodeBase64URLSafeString(header.getBytes("UTF-8")));

        //Separate with a period
        token.append(".");

        //Create the JWT Claims Object
        String[] claimArray = new String[5];
        claimArray[0] = iss;
        claimArray[1] = "https://www.googleapis.com/auth/compute";
        claimArray[2] = "https://accounts.google.com/o/oauth2/token";
        claimArray[3] = Long.toString((System.currentTimeMillis() / 1000) + 300);
        claimArray[4] = Long.toString((System.currentTimeMillis() / 1000));
        MessageFormat claims;
        claims = new MessageFormat(claimTemplate);
        String payload = claims.format(claimArray);
        //         System.out.println(claimArray[3]);
        //         System.out.println(claimArray[4]);
        //Add the encoded claims object
        token.append(Base64.encodeBase64URLSafeString(payload.getBytes("UTF-8")));

        char[] password = "notasecret".toCharArray();
        FileInputStream fin = new FileInputStream(new File(p12File));
        KeyStore store = KeyStore.getInstance("PKCS12");
        try {
            store.load(fin, password);
        } finally {
            try {
                fin.close();
            } catch (IOException e) {
            }
        }
        String alias = "";
        // KeyStore keystore = getKeyStore(password);            
        Enumeration<String> enum1 = store.aliases(); // List the aliases
        while (enum1.hasMoreElements()) {
            String keyStoreAlias = enum1.nextElement().toString();
            if (store.isKeyEntry(keyStoreAlias)) { //Does alias refer to a private key?
                alias = keyStoreAlias;
                break;
            }
        }
        PrivateKey privateKey = (PrivateKey) store.getKey(alias, password);

        //Sign the JWT Header + "." + JWT Claims Object
        Signature signature = Signature.getInstance("SHA256withRSA");
        signature.initSign(privateKey);
        signature.update(token.toString().getBytes("UTF-8"));
        String signedPayload = Base64.encodeBase64URLSafeString(signature.sign());

        //Separate with a period
        token.append(".");

        //Add the encoded signature
        token.append(signedPayload);

        //      System.out.println(token.toString());
        return token.toString();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:org.adempierelbr.model.MLBRDigitalCertificate.java

/**
 * setCertificate//from  w  ww  .  jav  a  2s .c o m
 * Set all System.property for webservice connection
 */
public static void setCertificate(Properties ctx, MOrgInfo oi) throws Exception {

    Integer certOrg = (Integer) oi.get_Value("LBR_DC_Org_ID");
    Integer certWS = (Integer) oi.get_Value("LBR_DC_WS_ID");
    MLBRDigitalCertificate dcOrg = new MLBRDigitalCertificate(Env.getCtx(), certOrg, null);
    MLBRDigitalCertificate dcWS = new MLBRDigitalCertificate(Env.getCtx(), certWS, null);

    String orgPassword = dcOrg.getPassword();
    String certType = null;
    InputStream certFileOrg = null;

    if (MLBRDigitalCertificate.LBR_CERTTYPE_PKCS12.equals(dcOrg.getlbr_CertType())) {
        certType = "PKCS12";
        certFileOrg = dcOrg.getAttachment(true).getEntry(0).getInputStream();
        if (certFileOrg == null)
            throw new Exception("Unable to find private key attachment");
    } else if (MLBRDigitalCertificate.LBR_CERTTYPE_PKCS11.equals(dcOrg.getlbr_CertType())) {
        certType = "PKCS11";
        Provider p = new sun.security.pkcs11.SunPKCS11(dcOrg.getConfigurationFile());
        Security.addProvider(p);
    } else
        return; //   Unknown Certificate

    KeyStore ks = KeyStore.getInstance(certType);
    try {
        ks.load(certFileOrg, orgPassword.toCharArray());
    } catch (IOException e) {
        throw new Exception("Incorrect Certificate Password");
    }

    InputStream certFileWS = dcWS.getAttachment(true).getEntry(0).getInputStream();
    if (certFileWS == null) {
        throw new Exception("Unable to find webservices keystore attachment");
    }

    String alias = dcOrg.getAlias();
    if (alias != null && ks.containsAlias(alias) && ks.isKeyEntry(alias))
        ;//   Do Nothing
    else {
        Enumeration<String> aliasesEnum = ks.aliases();
        while (aliasesEnum.hasMoreElements()) {
            alias = (String) aliasesEnum.nextElement();
            if (ks.isKeyEntry(alias))
                break;
        }
    }

    //Erro NFe 3.10
    System.setProperty("sun.security.ssl.allowUnsafeRenegotiation", "true");

    X509Certificate certificate = (X509Certificate) ks.getCertificate(alias);
    PrivateKey privateKey = (PrivateKey) ks.getKey(alias, orgPassword.toCharArray());
    SocketFactoryDinamico socketFactoryDinamico = new SocketFactoryDinamico(certificate, privateKey);
    socketFactoryDinamico.setFileCacerts(certFileWS, dcWS.getPassword());

    Protocol protocol = new Protocol("https", socketFactoryDinamico, 443);
    Protocol.registerProtocol("https", protocol);
}

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 {/*  ww  w.j  av  a 2  s  . 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 PrivateKeyEntry loadFirstPrivateKeyEntry(String keystoreType, InputStream keyStoreInputStream,
        char[] keyStorePassword, char[] keyEntryPassword) {

    /* Find the keystore. */
    KeyStore keyStore = loadKeyStore(keystoreType, keyStoreInputStream, keyStorePassword);
    Enumeration<String> aliases;
    try {/*from w  ww. jav  a 2  s. com*/
        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:com.indivica.olis.Driver.java

public static String signData(String data) {
    X509Certificate cert = null;/*from w  ww  .j ava  2s .  c  o m*/
    PrivateKey priv = null;
    KeyStore keystore = null;
    String pwd = "Olis2011";
    String result = null;
    try {
        Security.addProvider(new BouncyCastleProvider());

        keystore = KeyStore.getInstance("PKCS12", "SunJSSE");
        // Load the keystore
        keystore.load(new FileInputStream(OscarProperties.getInstance().getProperty("olis_keystore")),
                pwd.toCharArray());

        Enumeration e = keystore.aliases();
        String name = "";

        if (e != null) {
            while (e.hasMoreElements()) {
                String n = (String) e.nextElement();
                if (keystore.isKeyEntry(n)) {
                    name = n;
                }
            }
        }

        // Get the private key and the certificate
        priv = (PrivateKey) keystore.getKey(name, pwd.toCharArray());
        cert = (X509Certificate) keystore.getCertificate(name);

        // I'm not sure if this is necessary

        ArrayList<Certificate> certList = new ArrayList<Certificate>();
        certList.add(cert);

        Store certs = new JcaCertStore(certList);

        // Encrypt data
        CMSSignedDataGenerator sgen = new CMSSignedDataGenerator();

        // What digest algorithm i must use? SHA1? MD5? RSA?...
        ContentSigner sha1Signer = new JcaContentSignerBuilder("SHA1withRSA").setProvider("BC").build(priv);
        sgen.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(
                new JcaDigestCalculatorProviderBuilder().setProvider("BC").build()).build(sha1Signer, cert));

        // I'm not sure this is necessary
        sgen.addCertificates(certs);

        // I think that the 2nd parameter need to be false (detached form)
        CMSSignedData csd = sgen.generate(new CMSProcessableByteArray(data.getBytes()), true);

        byte[] signedData = csd.getEncoded();
        byte[] signedDataB64 = Base64.encode(signedData);

        result = new String(signedDataB64);

    } catch (Exception e) {
        MiscUtils.getLogger().error("Can't sign HL7 message for OLIS", e);
    }
    return result;
}

From source file:be.fedict.trust.service.KeyStoreUtils.java

public static PrivateKeyEntry loadPrivateKeyEntry(KeyStoreType type, String path, String storePassword,
        String entryPassword, String alias) throws KeyStoreLoadException {

    LOG.debug("load keystore");
    InputStream keyStoreStream = null;

    if (type.equals(KeyStoreType.PKCS11)) {
        Security.addProvider(new SunPKCS11(path));
    } else {//from  w  w w.ja  v  a 2 s.  c  o m
        try {
            keyStoreStream = new FileInputStream(path);
        } catch (FileNotFoundException e) {
            throw new KeyStoreLoadException("Can't load keystore from config-specified location: " + path, e);
        }
    }

    /* Find the keystore. */
    KeyStore keyStore;
    try {
        keyStore = KeyStore.getInstance(type.name());
    } catch (Exception e) {
        throw new KeyStoreLoadException("keystore instance not available: " + e.getMessage(), e);
    }

    /* Open the keystore and find the key entry. */
    try {
        keyStore.load(keyStoreStream, storePassword.toCharArray());
    } catch (Exception e) {
        throw new KeyStoreLoadException("keystore load error: " + e.getMessage(), e);
    }
    Enumeration<String> aliases;
    try {
        aliases = keyStore.aliases();
    } catch (KeyStoreException e) {
        throw new KeyStoreLoadException("could not get aliases: " + e.getMessage(), e);
    }
    if (!aliases.hasMoreElements()) {
        throw new KeyStoreLoadException("keystore is empty");
    }
    if (null == alias || alias.isEmpty()) {
        alias = aliases.nextElement();
        LOG.debug("alias: " + alias);
    }

    try {
        if (!keyStore.isKeyEntry(alias))
            throw new KeyStoreLoadException("not key entry: " + alias);
    } catch (KeyStoreException e) {
        throw new KeyStoreLoadException("key store error: " + e.getMessage(), e);
    }

    /* Get the private key entry. */
    try {
        PrivateKeyEntry privateKeyEntry = (PrivateKeyEntry) keyStore.getEntry(alias,
                new KeyStore.PasswordProtection(entryPassword.toCharArray()));
        return privateKeyEntry;
    } catch (Exception e) {
        throw new KeyStoreLoadException("error retrieving key: " + e.getMessage(), e);
    }
}

From source file:org.apache.taverna.security.credentialmanager.impl.CredentialManagerImplIT.java

/**
 * @throws java.lang.Exception/*from  w  ww. ja  v a 2s . c  o  m*/
 */
@BeforeClass
@Ignore
public static void setUpBeforeCLass() throws Exception {

    Security.addProvider(new BouncyCastleProvider());

    // Create some test username and passwords for services
    serviceURI = new URI("http://someservice");
    usernamePassword = new UsernamePassword("testuser", "testpasswd");
    serviceURI2 = new URI("http://someservice2");
    usernamePassword2 = new UsernamePassword("testuser2", "testpasswd2");
    serviceURI3 = new URI("http://someservice3");
    usernamePassword3 = new UsernamePassword("testuser3", "testpasswd3");

    // Load the test private key and its certificate
    File privateKeyCertFile = new File(privateKeyFileURL.getPath());
    KeyStore pkcs12Keystore = java.security.KeyStore.getInstance("PKCS12", "BC"); // We have to use the BC provider here as the certificate chain is not loaded if we use whichever provider is first in Java!!!
    FileInputStream inStream = new FileInputStream(privateKeyCertFile);
    pkcs12Keystore.load(inStream, privateKeyAndPKCS12KeystorePassword.toCharArray());
    // KeyStore pkcs12Keystore = credentialManager.loadPKCS12Keystore(privateKeyCertFile, privateKeyPassword);
    Enumeration<String> aliases = pkcs12Keystore.aliases();
    while (aliases.hasMoreElements()) {
        // The test-private-key-cert.p12 file contains only one private key
        // and corresponding certificate entry
        String alias = aliases.nextElement();
        if (pkcs12Keystore.isKeyEntry(alias)) { // is it a (private) key entry?
            privateKey = pkcs12Keystore.getKey(alias, privateKeyAndPKCS12KeystorePassword.toCharArray());
            privateKeyCertChain = pkcs12Keystore.getCertificateChain(alias);
            break;
        }
    }
    inStream.close();

    // Load the test trusted certificate (belonging to *.Google.com)
    File trustedCertFile = new File(trustedCertficateGoogleFileURL.getPath());
    inStream = new FileInputStream(trustedCertFile);
    CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
    trustedCertficateGoogle = (X509Certificate) certFactory.generateCertificate(inStream);
    try {
        inStream.close();
    } catch (Exception e) {
        // Ignore
    }
    // Load the test trusted certificate (belonging to heater.cs.man.ac.uk)
    File trustedCertFile2 = new File(trustedCertficateHeaterFileURL.getPath());
    inStream = new FileInputStream(trustedCertFile2);
    trustedCertficateHeater = (X509Certificate) certFactory.generateCertificate(inStream);
    try {
        inStream.close();
    } catch (Exception e) {
        // Ignore
    }

    credentialManager = new CredentialManagerImpl();

    //      // The code below sets up the Keystore and Truststore files and loads some data into them
    //      // and saves them into a temp directory. These files can later be used for testing the Credential
    //      // Manager with non-empty keystores.
    //      Random randomGenerator = new Random();
    //      String credentialManagerDirectoryPath = System
    //            .getProperty("java.io.tmpdir")
    //            + System.getProperty("file.separator")
    //            + "taverna-security-"
    //            + randomGenerator.nextInt(1000000);
    //      System.out.println("Credential Manager's directory path: "
    //            + credentialManagerDirectoryPath);
    //      credentialManagerDirectory = new File(credentialManagerDirectoryPath);
    //      credentialManager.setConfigurationDirectoryPath(credentialManagerDirectory);
    //      
    //      // Create the dummy master password provider
    //      masterPasswordProvider = new DummyMasterPasswordProvider();
    //      masterPasswordProvider.setMasterPassword(masterPassword);
    //      List<MasterPasswordProvider> masterPasswordProviders = new ArrayList<MasterPasswordProvider>();
    //      masterPasswordProviders.add(masterPasswordProvider);
    //      credentialManager.setMasterPasswordProviders(masterPasswordProviders);
    //      
    //      // Add some stuff into Credential Manager
    //      credentialManager.addUsernameAndPasswordForService(usernamePassword, serviceURI);
    //      credentialManager.addUsernameAndPasswordForService(usernamePassword2, serviceURI2);
    //      credentialManager.addUsernameAndPasswordForService(usernamePassword3, serviceURI3);
    //      credentialManager.addKeyPair(privateKey, privateKeyCertChain);
    //      credentialManager.addTrustedCertificate(trustedCertficate);

    // Set up a random temp directory and copy the test keystore files 
    // from resources/security
    Random randomGenerator = new Random();
    String credentialManagerDirectoryPath = System.getProperty("java.io.tmpdir")
            + System.getProperty("file.separator") + "taverna-security-" + randomGenerator.nextInt(1000000);
    System.out.println("Credential Manager's directory path: " + credentialManagerDirectoryPath);
    credentialManagerDirectory = new File(credentialManagerDirectoryPath);
    if (!credentialManagerDirectory.exists()) {
        credentialManagerDirectory.mkdir();
    }
    URL keystoreFileURL = CredentialManagerImplIT.class.getResource("/security/t2keystore.ubr");
    File keystoreFile = new File(keystoreFileURL.getPath());
    File keystoreDestFile = new File(credentialManagerDirectory, "taverna-keystore.ubr");
    URL truststroreFileURL = CredentialManagerImplIT.class.getResource("/security/t2truststore.ubr");
    File truststoreFile = new File(truststroreFileURL.getPath());
    File truststoreDestFile = new File(credentialManagerDirectory, "taverna-truststore.ubr");
    FileUtils.copyFile(keystoreFile, keystoreDestFile);
    FileUtils.copyFile(truststoreFile, truststoreDestFile);
    credentialManager.setConfigurationDirectoryPath(credentialManagerDirectory.toPath());

    // Create the dummy master password provider
    masterPasswordProvider = new DummyMasterPasswordProvider();
    masterPasswordProvider.setMasterPassword(masterPassword);
    List<MasterPasswordProvider> masterPasswordProviders = new ArrayList<MasterPasswordProvider>();
    masterPasswordProviders.add(masterPasswordProvider);
    credentialManager.setMasterPasswordProviders(masterPasswordProviders);

    // Set an empty list for trust confirmation providers
    credentialManager.setTrustConfirmationProviders(new ArrayList<TrustConfirmationProvider>());

    keystoreChangedObserver = new Observer<KeystoreChangedEvent>() {
        @Override
        public void notify(Observable<KeystoreChangedEvent> sender, KeystoreChangedEvent message)
                throws Exception {
            // TODO Auto-generated method stub
        }
    };
    credentialManager.addObserver(keystoreChangedObserver);
}

From source file:net.sf.taverna.t2.security.credentialmanager.impl.CredentialManagerImplIT.java

/**
 * @throws java.lang.Exception/* w ww .  j a v  a  2  s. c  o  m*/
 */
@BeforeClass
@Ignore
public static void setUpBeforeCLass() throws Exception {

    Security.addProvider(new BouncyCastleProvider());

    // Create some test username and passwords for services
    serviceURI = new URI("http://someservice");
    usernamePassword = new UsernamePassword("testuser", "testpasswd");
    serviceURI2 = new URI("http://someservice2");
    usernamePassword2 = new UsernamePassword("testuser2", "testpasswd2");
    serviceURI3 = new URI("http://someservice3");
    usernamePassword3 = new UsernamePassword("testuser3", "testpasswd3");

    // Load the test private key and its certificate
    File privateKeyCertFile = new File(privateKeyFileURL.getPath());
    KeyStore pkcs12Keystore = java.security.KeyStore.getInstance("PKCS12", "BC"); // We have to use the BC provider here as the certificate chain is not loaded if we use whichever provider is first in Java!!!
    FileInputStream inStream = new FileInputStream(privateKeyCertFile);
    pkcs12Keystore.load(inStream, privateKeyAndPKCS12KeystorePassword.toCharArray());
    // KeyStore pkcs12Keystore = credentialManager.loadPKCS12Keystore(privateKeyCertFile, privateKeyPassword);
    Enumeration<String> aliases = pkcs12Keystore.aliases();
    while (aliases.hasMoreElements()) {
        // The test-private-key-cert.p12 file contains only one private key
        // and corresponding certificate entry
        String alias = aliases.nextElement();
        if (pkcs12Keystore.isKeyEntry(alias)) { // is it a (private) key entry?
            privateKey = pkcs12Keystore.getKey(alias, privateKeyAndPKCS12KeystorePassword.toCharArray());
            privateKeyCertChain = pkcs12Keystore.getCertificateChain(alias);
            break;
        }
    }
    inStream.close();

    // Load the test trusted certificate (belonging to *.Google.com)
    File trustedCertFile = new File(trustedCertficateGoogleFileURL.getPath());
    inStream = new FileInputStream(trustedCertFile);
    CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
    trustedCertficateGoogle = (X509Certificate) certFactory.generateCertificate(inStream);
    try {
        inStream.close();
    } catch (Exception e) {
        // Ignore
    }
    // Load the test trusted certificate (belonging to heater.cs.man.ac.uk)
    File trustedCertFile2 = new File(trustedCertficateHeaterFileURL.getPath());
    inStream = new FileInputStream(trustedCertFile2);
    trustedCertficateHeater = (X509Certificate) certFactory.generateCertificate(inStream);
    try {
        inStream.close();
    } catch (Exception e) {
        // Ignore
    }

    credentialManager = new CredentialManagerImpl();

    //      // The code below sets up the Keystore and Truststore files and loads some data into them
    //      // and saves them into a temp directory. These files can later be used for testing the Credential
    //      // Manager with non-empty keystores.
    //      Random randomGenerator = new Random();
    //      String credentialManagerDirectoryPath = System
    //            .getProperty("java.io.tmpdir")
    //            + System.getProperty("file.separator")
    //            + "taverna-security-"
    //            + randomGenerator.nextInt(1000000);
    //      System.out.println("Credential Manager's directory path: "
    //            + credentialManagerDirectoryPath);
    //      credentialManagerDirectory = new File(credentialManagerDirectoryPath);
    //      credentialManager.setConfigurationDirectoryPath(credentialManagerDirectory);
    //      
    //      // Create the dummy master password provider
    //      masterPasswordProvider = new DummyMasterPasswordProvider();
    //      masterPasswordProvider.setMasterPassword(masterPassword);
    //      List<MasterPasswordProvider> masterPasswordProviders = new ArrayList<MasterPasswordProvider>();
    //      masterPasswordProviders.add(masterPasswordProvider);
    //      credentialManager.setMasterPasswordProviders(masterPasswordProviders);
    //      
    //      // Add some stuff into Credential Manager
    //      credentialManager.addUsernameAndPasswordForService(usernamePassword, serviceURI);
    //      credentialManager.addUsernameAndPasswordForService(usernamePassword2, serviceURI2);
    //      credentialManager.addUsernameAndPasswordForService(usernamePassword3, serviceURI3);
    //      credentialManager.addKeyPair(privateKey, privateKeyCertChain);
    //      credentialManager.addTrustedCertificate(trustedCertficate);

    // Set up a random temp directory and copy the test keystore files 
    // from resources/security
    Random randomGenerator = new Random();
    String credentialManagerDirectoryPath = System.getProperty("java.io.tmpdir")
            + System.getProperty("file.separator") + "taverna-security-" + randomGenerator.nextInt(1000000);
    System.out.println("Credential Manager's directory path: " + credentialManagerDirectoryPath);
    credentialManagerDirectory = new File(credentialManagerDirectoryPath);
    if (!credentialManagerDirectory.exists()) {
        credentialManagerDirectory.mkdir();
    }
    URL keystoreFileURL = CredentialManagerImplIT.class.getResource("/security/t2keystore.ubr");
    File keystoreFile = new File(keystoreFileURL.getPath());
    File keystoreDestFile = new File(credentialManagerDirectory, "taverna-keystore.ubr");
    URL truststroreFileURL = CredentialManagerImplIT.class.getResource("/security/t2truststore.ubr");
    File truststoreFile = new File(truststroreFileURL.getPath());
    File truststoreDestFile = new File(credentialManagerDirectory, "taverna-truststore.ubr");
    FileUtils.copyFile(keystoreFile, keystoreDestFile);
    FileUtils.copyFile(truststoreFile, truststoreDestFile);
    credentialManager.setConfigurationDirectoryPath(credentialManagerDirectory);

    // Create the dummy master password provider
    masterPasswordProvider = new DummyMasterPasswordProvider();
    masterPasswordProvider.setMasterPassword(masterPassword);
    List<MasterPasswordProvider> masterPasswordProviders = new ArrayList<MasterPasswordProvider>();
    masterPasswordProviders.add(masterPasswordProvider);
    credentialManager.setMasterPasswordProviders(masterPasswordProviders);

    // Set an empty list for trust confirmation providers
    credentialManager.setTrustConfirmationProviders(new ArrayList<TrustConfirmationProvider>());

    keystoreChangedObserver = new Observer<KeystoreChangedEvent>() {
        @Override
        public void notify(Observable<KeystoreChangedEvent> sender, KeystoreChangedEvent message)
                throws Exception {
            // TODO Auto-generated method stub
        }
    };
    credentialManager.addObserver(keystoreChangedObserver);
}

From source file:nu.yona.server.AppServiceApplication.java

private void assertKeyStoreContent(KeyStore keyStore) {
    try {/*from  w  w  w  .  j  av a  2 s .  co m*/
        String alias = yonaProperties.getAppleMobileConfig().getSigningAlias();
        if (!keyStore.isKeyEntry(alias)) {
            logAliases(keyStore);
            throw ConfigurationException.missingKeyInKeyStore(alias);
        }
    } catch (KeyStoreException e) {
        throw YonaException.unexpected(e);
    }
}

From source file:org.wso2.identity.integration.common.clients.KeyStoreAdminClient.java

public boolean isPrivateKeyStore(byte[] content, String password, String type) throws Exception {
    try {/* ww  w  . j  ava 2 s .  co m*/
        boolean isPrivateStore = false;
        ByteArrayInputStream stream = new ByteArrayInputStream(content);
        KeyStore store = KeyStore.getInstance(type);
        store.load(stream, password.toCharArray());
        Enumeration<String> aliases = store.aliases();
        while (aliases.hasMoreElements()) {
            String value = aliases.nextElement();
            if (store.isKeyEntry(value)) {
                isPrivateStore = true;
                break;
            }
        }
        return isPrivateStore;
    } catch (Exception e) {
        log.error("Error in checking private key store.", e);
        throw new Exception("Error in checking private key store.");
    }
}