Example usage for java.security KeyStore getKey

List of usage examples for java.security KeyStore getKey

Introduction

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

Prototype

public final Key getKey(String alias, char[] password)
        throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException 

Source Link

Document

Returns the key associated with the given alias, using the given password to recover it.

Usage

From source file:org.opendatakit.aggregate.externalservice.GoogleOauth2ExternalService.java

protected static GoogleCredential getCredential(String scopes, CallingContext cc)
        throws ODKExternalServiceCredentialsException {
    try {/* w  w w  .j  ava2  s  . c om*/
        String serviceAccountUser = ServerPreferencesProperties.getServerPreferencesProperty(cc,
                ServerPreferencesProperties.GOOGLE_API_SERVICE_ACCOUNT_EMAIL);
        String privateKeyString = ServerPreferencesProperties.getServerPreferencesProperty(cc,
                ServerPreferencesProperties.PRIVATE_KEY_FILE_CONTENTS);

        if (serviceAccountUser == null || privateKeyString == null || serviceAccountUser.length() == 0
                || privateKeyString.length() == 0) {
            throw new ODKExternalServiceCredentialsException(
                    "No OAuth2 credentials. Have you supplied any OAuth2 credentials on the Site Admin / Preferences page?");
        }

        byte[] privateKeyBytes = Base64.decodeBase64(privateKeyString.getBytes(UTF_CHARSET));

        // TODO: CHANGE TO MORE OPTIMAL METHOD
        KeyStore ks = null;
        ks = KeyStore.getInstance("PKCS12");
        ks.load(new ByteArrayInputStream(privateKeyBytes), "notasecret".toCharArray());
        Enumeration<String> aliasEnum = null;
        aliasEnum = ks.aliases();

        Key key = null;
        while (aliasEnum.hasMoreElements()) {
            String keyName = (String) aliasEnum.nextElement();
            key = ks.getKey(keyName, "notasecret".toCharArray());
            break;
        }
        PrivateKey serviceAccountPrivateKey = (PrivateKey) key;

        HttpClientFactory httpClientFactory = (HttpClientFactory) cc.getBean(BeanDefs.HTTP_CLIENT_FACTORY);
        HttpTransport httpTransport = httpClientFactory.getGoogleOAuth2Transport();

        GoogleCredential credential = new GoogleCredential.Builder().setTransport(httpTransport)
                .setJsonFactory(jsonFactory).setServiceAccountId(serviceAccountUser)
                .setServiceAccountScopes(Collections.singleton(scopes))
                .setServiceAccountPrivateKey(serviceAccountPrivateKey).build();
        credential.refreshToken();
        return credential;
    } catch (Exception e) {
        e.printStackTrace();
        throw new ODKExternalServiceCredentialsException(e);
    }
}

From source file:com.vmware.identity.idm.IdmDataCreator.java

private static KeyPair readKeyStore(CredentialDescriptor cd) throws IOException {
    KeyPair kp = null;/*from   w  w w  .  j  av  a2 s .c  o  m*/
    InputStream is = null;

    try {
        KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
        char[] stsKeystorePassword = cd.getPassword().toCharArray();
        is = getInputStream(cd.getFilename());
        ks.load(is, stsKeystorePassword);

        kp = new KeyPair();
        kp.setCertificateChain(Arrays.asList(ks.getCertificateChain(cd.getAlias())));
        kp.setPrivateKey((PrivateKey) ks.getKey(cd.getAlias(), stsKeystorePassword));
    } catch (Exception e) {
        logger.debug("Caught exception while reading keystore {}", e.toString());
    } finally {
        if (is != null) {
            is.close();
        }
    }

    return kp;
}

From source file:it.cnr.icar.eric.client.xml.registry.util.CertificateUtil.java

/**
 * Generate a self signed certificate and store it in the keystore.
 * //from   w  ww . j a  v  a  2s .com
 * @param userRegInfo
 * @throws JAXRException
 */
public static void generateRegistryIssuedCertificate(UserRegistrationInfo userRegInfo) throws JAXRException {
    User user = userRegInfo.getUser();
    LifeCycleManager lcm = user.getLifeCycleManager();
    String dname = getDNameFromUser(userRegInfo);
    File keystoreFile = KeystoreUtil.getKeystoreFile();
    KeystoreUtil.createKeystoreDirectory(keystoreFile);
    String keystoreType = ProviderProperties.getInstance().getProperty("jaxr-ebxml.security.storetype", "JKS");
    String storePassStr = new String(userRegInfo.getStorePassword());
    String keyPassStr = new String(userRegInfo.getKeyPassword());
    String alias = userRegInfo.getAlias();
    String keyAlg = "RSA"; // XWSS does not support DSA which is default is
    // KeyTool. Hmm. Weird.

    String[] args = { "-genkey", "-keyAlg", keyAlg, "-alias", alias, "-keypass", keyPassStr, "-keystore",
            keystoreFile.getAbsolutePath(), "-storepass", storePassStr, "-storetype", keystoreType, "-dname",
            dname };

    try {
        KeyTool keytool = new KeyTool();
        keytool.run(args, System.out);

        // Now load the KeyStore and get the cert
        FileInputStream fis = new FileInputStream(keystoreFile);

        KeyStore keyStore = KeyStore.getInstance(keystoreType);
        keyStore.load(fis, storePassStr.toCharArray());
        fis.close();

        X509Certificate cert = (X509Certificate) keyStore.getCertificate(alias);
        Certificate[] certChain = getCertificateSignedByRegistry(lcm, cert);
        Key key = keyStore.getKey(alias, userRegInfo.getKeyPassword());

        // Now overwrite original cert with signed cert
        keyStore.deleteEntry(alias);

        // keyStore.setCertificateEntry(alias, cert);
        keyStore.setKeyEntry(alias, key, userRegInfo.getKeyPassword(), certChain);
        FileOutputStream fos = new java.io.FileOutputStream(keystoreFile);
        keyStore.store(fos, storePassStr.toCharArray());
        fos.flush();
        fos.close();
    } catch (Exception e) {
        throw new JAXRException(JAXRResourceBundle.getInstance().getString("message.CertGenFailed"), e);
    }

    log.debug(JAXRResourceBundle.getInstance().getString("message.StoredUserInKeyStore",
            new Object[] { alias, keystoreFile.getAbsolutePath() }));

    try {
        // Export registry issued cert to certFile so it can be available
        // for import into a web browser for SSL access to registry
        exportRegistryIssuedCert(userRegInfo);
    } catch (Exception e) {
        String msg = JAXRResourceBundle.getInstance().getString(
                "message.UnableToExportCertificateSeeNextExceptionNoteThatThisFeatureRequiresUseOfJDK5");
        log.warn(msg, e);
        // Do not throw exception as user reg can be done despite not
        // exporting the p12 file for the web browser.
    }
}

From source file:com.vmware.identity.samlservice.SamlServiceTest.java

@BeforeClass
public static void setUp() throws Exception {
    SharedUtils.bootstrap(false); // use real data
    String tenantName = ServerConfig.getTenant(0);
    String rpName = ServerConfig.getRelyingParty(tenantName, 0);
    String issuerUrl = ServerConfig.getRelyingPartyUrl(rpName);
    String acsName = ServerConfig.getAssertionConsumerService(rpName, 0);
    acsUrl = ServerConfig.getServiceEndpoint(acsName);

    KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
    InputStream is = new FileInputStream(SamlServiceTest.class.getResource("/sts-store.jks").getFile());
    char[] stsKeystorePassword = "ca$hc0w".toCharArray();
    ks.load(is, stsKeystorePassword);/*from   www  . ja v  a2  s . com*/

    String stsAlias = "stskey";
    Certificate certificate = ks.getCertificate(stsAlias);
    Key key = ks.getKey(stsAlias, stsKeystorePassword);

    List<X509Certificate> certificates = new ArrayList<X509Certificate>();
    certificates.add((X509Certificate) certificate);

    CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
    CertPath certPath = certFactory.generateCertPath(certificates);

    privateKey = (PrivateKey) key;
    x509Certificate = (X509Certificate) certificate;

    SamlServiceFactory factory = new DefaultSamlServiceFactory();
    service = factory.createSamlService(privateKey, SignatureAlgorithm.RSA_SHA256,
            SignatureAlgorithm.RSA_SHA256, issuerUrl, certPath);
}

From source file:org.apache.accumulo.test.util.CertUtils.java

static PrivateKey findPrivateKey(KeyStore keyStore, char[] keystorePassword)
        throws UnrecoverableKeyException, KeyStoreException, NoSuchAlgorithmException {
    Enumeration<String> aliases = keyStore.aliases();
    PrivateKey key = null;//w w  w. j  a v a2  s. c  o m
    while (aliases.hasMoreElements()) {
        String alias = aliases.nextElement();
        if (keyStore.isKeyEntry(alias)) {
            if (key == null) {
                key = (PrivateKey) keyStore.getKey(alias, keystorePassword);
            } else {
                log.warn("Found multiple keys in keystore.  Ignoring " + alias);
            }
        }
    }
    if (key == null) {
        throw new KeyStoreException("Could not find private key in keystore");
    }
    return key;
}

From source file:org.wso2.carbon.identity.jwt.client.extension.util.JWTClientUtil.java

public static String generateSignedJWTAssertion(String username, JWTConfig jwtConfig,
        boolean isDefaultJWTClient, Map<String, String> customClaims) throws JWTClientException {
    try {/* w w w . jav a2  s  . c  o m*/
        long currentTimeMillis = System.currentTimeMillis();
        // add the skew between servers
        String iss = jwtConfig.getIssuer();
        if (iss == null || iss.isEmpty()) {
            return null;
        }
        currentTimeMillis += jwtConfig.getSkew();
        long iat = currentTimeMillis + jwtConfig.getIssuedInternal() * 60 * 1000;
        long exp = currentTimeMillis + jwtConfig.getExpirationTime() * 60 * 1000;
        long nbf = currentTimeMillis + jwtConfig.getValidityPeriodFromCurrentTime() * 60 * 1000;
        String jti = jwtConfig.getJti();
        if (jti == null) {
            String defaultTokenId = currentTimeMillis + "" + new SecureRandom().nextInt();
            jti = defaultTokenId;
        }
        List<String> aud = jwtConfig.getAudiences();
        //set up the basic claims
        JWTClaimsSet claimsSet = new JWTClaimsSet();
        claimsSet.setIssueTime(new Date(iat));
        claimsSet.setExpirationTime(new Date(exp));
        claimsSet.setIssuer(iss);
        claimsSet.setSubject(username);
        claimsSet.setNotBeforeTime(new Date(nbf));
        claimsSet.setJWTID(jti);
        claimsSet.setAudience(aud);
        claimsSet.setClaim(SIGNED_JWT_AUTH_USERNAME, username);
        if (customClaims != null && !customClaims.isEmpty()) {
            for (String key : customClaims.keySet()) {
                claimsSet.setClaim(key, customClaims.get(key));
            }
        }

        // get Keystore params
        String keyStorePath = jwtConfig.getKeyStorePath();
        String privateKeyAlias = jwtConfig.getPrivateKeyAlias();
        String privateKeyPassword = jwtConfig.getPrivateKeyPassword();
        KeyStore keyStore;
        RSAPrivateKey rsaPrivateKey;
        if (!isDefaultJWTClient && (keyStorePath != null && !keyStorePath.isEmpty())) {
            String keyStorePassword = jwtConfig.getKeyStorePassword();
            keyStore = loadKeyStore(new File(keyStorePath), keyStorePassword, "JKS");
            rsaPrivateKey = (RSAPrivateKey) keyStore.getKey(privateKeyAlias, privateKeyPassword.toCharArray());
        } else {
            int tenantId = PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantId(true);
            JWTClientUtil.loadTenantRegistry(tenantId);
            if (!(MultitenantConstants.SUPER_TENANT_ID == tenantId) && !isDefaultJWTClient) {
                KeyStoreManager tenantKeyStoreManager = KeyStoreManager.getInstance(tenantId);
                String tenantDomain = PrivilegedCarbonContext.getThreadLocalCarbonContext()
                        .getTenantDomain(true);
                String ksName = tenantDomain.trim().replace('.', '-');
                String jksName = ksName + ".jks";
                rsaPrivateKey = (RSAPrivateKey) tenantKeyStoreManager.getPrivateKey(jksName, tenantDomain);
            } else {
                try {
                    PrivilegedCarbonContext.startTenantFlow();
                    PrivilegedCarbonContext.getThreadLocalCarbonContext()
                            .setTenantId(MultitenantConstants.SUPER_TENANT_ID);
                    KeyStoreManager tenantKeyStoreManager = KeyStoreManager
                            .getInstance(MultitenantConstants.SUPER_TENANT_ID);
                    rsaPrivateKey = (RSAPrivateKey) tenantKeyStoreManager.getDefaultPrivateKey();
                } finally {
                    PrivilegedCarbonContext.endTenantFlow();
                }
            }
        }
        JWSSigner signer = new RSASSASigner(rsaPrivateKey);
        SignedJWT signedJWT = new SignedJWT(new JWSHeader(JWSAlgorithm.RS256), claimsSet);
        signedJWT.sign(signer);
        String assertion = signedJWT.serialize();
        return assertion;
    } catch (KeyStoreException e) {
        throw new JWTClientException("Failed loading the keystore.", e);
    } catch (IOException e) {
        throw new JWTClientException("Failed parsing the keystore file.", e);
    } catch (NoSuchAlgorithmException e) {
        throw new JWTClientException("No such algorithm found RS256.", e);
    } catch (CertificateException e) {
        throw new JWTClientException("Failed loading the certificate from the keystore.", e);
    } catch (UnrecoverableKeyException e) {
        throw new JWTClientException("Failed loading the keys from the keystore.", e);
    } catch (JOSEException e) {
        throw new JWTClientException(e);
    } catch (Exception e) {
        //This is thrown when loading default private key.
        throw new JWTClientException("Failed loading the private key.", e);
    }
}

From source file:org.wso2.carbon.device.mgt.iot.virtualfirealarm.plugin.impl.util.VirtualFirealarmSecurityManager.java

public static PrivateKey retrievePrivateKey() {
    PrivateKey privateKey = null;
    InputStream inputStream = null;
    KeyStore keyStore;
    try {//from   www .  j av a  2 s  .c  o  m
        CertificateKeystoreConfig certificateKeystoreConfig = getCertKeyStoreConfig();
        keyStore = KeyStore.getInstance(certificateKeystoreConfig.getCertificateKeystoreType());
        inputStream = new FileInputStream(certificateKeystoreConfig.getCertificateKeystoreLocation());

        keyStore.load(inputStream, certificateKeystoreConfig.getCertificateKeystorePassword().toCharArray());

        privateKey = (PrivateKey) (keyStore.getKey(certificateKeystoreConfig.getCACertAlias(),
                certificateKeystoreConfig.getCAPrivateKeyPassword().toCharArray()));

    } catch (KeyStoreException e) {
        String errorMsg = "Could not load KeyStore of given type in [certificate-config.xml] file.";
        log.error(errorMsg, e);
    } catch (FileNotFoundException e) {
        String errorMsg = "KeyStore file could not be loaded from path given in [certificate-config.xml] file.";
        log.error(errorMsg, e);
    } catch (NoSuchAlgorithmException e) {
        String errorMsg = "Algorithm not found when loading KeyStore";
        log.error(errorMsg, e);
    } catch (CertificateException e) {
        String errorMsg = "CertificateException when loading KeyStore";
        log.error(errorMsg, e);
    } catch (IOException e) {
        String errorMsg = "Input output issue occurred when loading KeyStore";
        log.error(errorMsg, e);
    } catch (UnrecoverableKeyException e) {
        String errorMsg = "Key is unrecoverable when retrieving CA private key";
        log.error(errorMsg, e);
    } catch (CertificateManagementException e) {
        String errorMsg = "Failed to load the certificate";
        log.error(errorMsg, e);
    } finally {
        try {
            if (inputStream != null) {
                inputStream.close();
            }
        } catch (IOException e) {
            log.error("Error closing KeyStore input stream", e);
        }
    }

    return privateKey;
}

From source file:net.firejack.platform.web.security.x509.KeyUtils.java

public static KeyPair generate(File keystore) {
    if (keystore == null) {
        throw new IllegalArgumentException("Key Store file should not be null.");
    }/*from  w  w w . j  ava 2 s .  co  m*/

    try {
        KeyStore ks = KeyStore.getInstance("JKS", "SUN");
        if (keystore.exists()) {
            FileInputStream stream = new FileInputStream(keystore);
            ks.load(stream, SECRET);
            IOUtils.closeQuietly(stream);
        } else {
            ks.load(null, SECRET);
        }

        if (ks.containsAlias(ALIAS)) {
            PrivateKey privateKey = (PrivateKey) ks.getKey(ALIAS, SECRET);
            PublicKey publicKey = ks.getCertificate(ALIAS).getPublicKey();
            return new KeyPair(publicKey, privateKey);
        } else {
            KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
            generator.initialize(KEYSIZE, new SecureRandom());
            return generator.generateKeyPair();
        }
    } catch (Throwable th) {
        logger.error("Failed to initialize key store");
        throw new OpenFlameRuntimeException(th.getMessage(), th);
    }
}

From source file:net.sf.jsignpdf.utils.KeyStoreUtils.java

/**
 * Returns PrivateKey and its certificate chain
 * // w w  w. j ava2s  .  c  om
 * @param options
 * @return
 * @throws NoSuchAlgorithmException
 * @throws KeyStoreException
 * @throws UnrecoverableKeyException
 */
public static PrivateKeyInfo getPkInfo(BasicSignerOptions options)
        throws UnrecoverableKeyException, KeyStoreException, NoSuchAlgorithmException {
    LOGGER.info("ksType " + options.getKsType() + " ksFile " + options.getKsFile() + " ksPasswd "
            + options.getKsPasswd());
    final KeyStore tmpKs = loadKeyStore(options.getKsType(), options.getKsFile(), options.getKsPasswd());

    String tmpAlias = getKeyAliasInternal(options, tmpKs);
    LOGGER.info(RES.get("console.getPrivateKey"));
    final PrivateKey tmpPk = (PrivateKey) tmpKs.getKey(tmpAlias, options.getKeyPasswdX());
    LOGGER.info(RES.get("console.getCertChain"));
    final Certificate[] tmpChain = tmpKs.getCertificateChain(tmpAlias);
    PrivateKeyInfo tmpResult = new PrivateKeyInfo(tmpPk, tmpChain);
    return tmpResult;
}

From source file:org.wso2.carbon.device.mgt.iot.virtualfirealarm.service.impl.util.SecurityManager.java

public static PrivateKey retrievePrivateKey(String alias, String password) {
    PrivateKey privateKey = null;
    InputStream inputStream = null;
    KeyStore keyStore;

    try {/*from   w w w  .j  a v  a 2  s.c o  m*/
        keyStore = KeyStore
                .getInstance(ConfigurationUtil.getConfigEntry(ConfigurationUtil.CERTIFICATE_KEYSTORE));
        inputStream = new FileInputStream(
                ConfigurationUtil.getConfigEntry(ConfigurationUtil.PATH_CERTIFICATE_KEYSTORE));

        keyStore.load(inputStream, ConfigurationUtil
                .getConfigEntry(ConfigurationUtil.CERTIFICATE_KEYSTORE_PASSWORD).toCharArray());

        privateKey = (PrivateKey) (keyStore.getKey(ConfigurationUtil.getConfigEntry(alias),
                ConfigurationUtil.getConfigEntry(password).toCharArray()));

    } catch (KeyStoreException e) {
        String errorMsg = "Could not load KeyStore of given type in [certificate-config.xml] file.";
        log.error(errorMsg, e);
    } catch (FileNotFoundException e) {
        String errorMsg = "KeyStore file could not be loaded from path given in [certificate-config.xml] file.";
        log.error(errorMsg, e);
    } catch (NoSuchAlgorithmException e) {
        String errorMsg = "Algorithm not found when loading KeyStore";
        log.error(errorMsg, e);
    } catch (CertificateException e) {
        String errorMsg = "CertificateException when loading KeyStore";
        log.error(errorMsg, e);
    } catch (IOException e) {
        String errorMsg = "Input output issue occurred when loading KeyStore";
        log.error(errorMsg, e);
    } catch (KeystoreException e) {
        String errorMsg = "An error occurred whilst trying load Configs for KeyStoreReader";
        log.error(errorMsg, e);
    } catch (UnrecoverableKeyException e) {
        String errorMsg = "Key is unrecoverable when retrieving CA private key";
        log.error(errorMsg, e);
    } finally {
        try {
            if (inputStream != null) {
                inputStream.close();
            }
        } catch (IOException e) {
            log.error("Error closing KeyStore input stream", e);
        }
    }

    return privateKey;
}