Example usage for java.security KeyStore getCertificate

List of usage examples for java.security KeyStore getCertificate

Introduction

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

Prototype

public final Certificate getCertificate(String alias) throws KeyStoreException 

Source Link

Document

Returns the certificate associated with the given alias.

Usage

From source file:ca.psiphon.PsiphonTunnel.java

private String setupTrustedCertificates(Context context) throws Exception {

    // Copy the Android system CA store to a local, private cert bundle file.
    ///*from w  w  w . ja  va 2 s  .co m*/
    // This results in a file that can be passed to SSL_CTX_load_verify_locations
    // for use with OpenSSL modes in tunnel-core.
    // https://www.openssl.org/docs/manmaster/ssl/SSL_CTX_load_verify_locations.html
    //
    // TODO: to use the path mode of load_verify_locations would require emulating
    // the filename scheme used by c_rehash:
    // https://www.openssl.org/docs/manmaster/apps/c_rehash.html
    // http://stackoverflow.com/questions/19237167/the-new-subject-hash-openssl-algorithm-differs

    File directory = context.getDir("PsiphonCAStore", Context.MODE_PRIVATE);

    final String errorMessage = "copy AndroidCAStore failed";
    try {

        File file = new File(directory, "certs.dat");

        // Pave a fresh copy on every run, which ensures we're not using old certs.
        // Note: assumes KeyStore doesn't return revoked certs.
        //
        // TODO: this takes under 1 second, but should we avoid repaving every time?
        file.delete();

        PrintStream output = null;
        try {
            output = new PrintStream(new FileOutputStream(file));

            KeyStore keyStore;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                keyStore = KeyStore.getInstance("AndroidCAStore");
                keyStore.load(null, null);
            } else {
                keyStore = KeyStore.getInstance("BKS");
                FileInputStream inputStream = new FileInputStream("/etc/security/cacerts.bks");
                try {
                    keyStore.load(inputStream, "changeit".toCharArray());
                } finally {
                    if (inputStream != null) {
                        inputStream.close();
                    }
                }
            }

            Enumeration<String> aliases = keyStore.aliases();
            while (aliases.hasMoreElements()) {
                String alias = aliases.nextElement();
                X509Certificate cert = (X509Certificate) keyStore.getCertificate(alias);

                output.println("-----BEGIN CERTIFICATE-----");
                String pemCert = new String(Base64.encode(cert.getEncoded(), Base64.NO_WRAP), "UTF-8");
                // OpenSSL appears to reject the default linebreaking done by Base64.encode,
                // so we manually linebreak every 64 characters
                for (int i = 0; i < pemCert.length(); i += 64) {
                    output.println(pemCert.substring(i, Math.min(i + 64, pemCert.length())));
                }
                output.println("-----END CERTIFICATE-----");
            }

            mHostService.onDiagnosticMessage("prepared PsiphonCAStore");

            return file.getAbsolutePath();

        } finally {
            if (output != null) {
                output.close();
            }
        }

    } catch (KeyStoreException e) {
        throw new Exception(errorMessage, e);
    } catch (NoSuchAlgorithmException e) {
        throw new Exception(errorMessage, e);
    } catch (CertificateException e) {
        throw new Exception(errorMessage, e);
    } catch (IOException e) {
        throw new Exception(errorMessage, e);
    }
}

From source file:org.apache.ws.security.components.crypto.Merlin.java

/**
 * Find the Public Key in a keystore. // w  ww  .j  av a  2 s .c  o m
 */
private boolean findPublicKeyInKeyStore(PublicKey publicKey, KeyStore keyStoreToSearch) {
    if (keyStoreToSearch == null) {
        return false;
    }
    try {
        for (Enumeration<String> e = keyStoreToSearch.aliases(); e.hasMoreElements();) {
            String alias = e.nextElement();
            Certificate[] certs = keyStoreToSearch.getCertificateChain(alias);
            Certificate cert;
            if (certs == null || certs.length == 0) {
                // no cert chain, so lets check if getCertificate gives us a result.
                cert = keyStoreToSearch.getCertificate(alias);
                if (cert == null) {
                    continue;
                }
            } else {
                cert = certs[0];
            }
            if (!(cert instanceof X509Certificate)) {
                continue;
            }
            X509Certificate x509cert = (X509Certificate) cert;
            if (publicKey.equals(x509cert.getPublicKey())) {
                return true;
            }
        }
    } catch (KeyStoreException e) {
        return false;
    }
    return false;
}

From source file:it.cnr.icar.eric.common.security.KeystoreMover.java

public void move(String sourceKeystoreType, String sourceKeystorePath, String sourceKeystorePassword,
        String sourceAlias, String sourceKeyPassword, String destinationKeystoreType,
        String destinationKeystorePath, String destinationKeystorePassword, String destinationAlias,
        String destinationKeyPassword) throws Exception {

    char[] sourceKeystorePasswordArr = null;
    if (sourceKeystorePassword != null) {
        sourceKeystorePasswordArr = sourceKeystorePassword.toCharArray();
    }//from   w w w. j av a 2s. co m

    char[] sourceKeyPasswordArr = sourceKeystorePasswordArr;
    if (sourceKeyPassword != null) {
        sourceKeyPasswordArr = sourceKeyPassword.toCharArray();
    }

    char[] destinationKeystorePasswordArr = null;
    if (destinationKeystorePassword != null) {
        destinationKeystorePasswordArr = destinationKeystorePassword.toCharArray();
    }

    char[] destinationKeyPasswordArr = destinationKeystorePasswordArr;
    if (destinationKeyPassword != null) {
        destinationKeyPasswordArr = destinationKeyPassword.toCharArray();
    }

    FileInputStream in;

    // --------  Load source keystore to memory ---------
    in = new FileInputStream(sourceKeystorePath);
    KeyStore ksin = KeyStore.getInstance(sourceKeystoreType);

    ksin.load(in, sourceKeystorePasswordArr);
    in.close();

    // --------  Load destination keystore initial contents to memory ---------
    KeyStore ksout = KeyStore.getInstance(destinationKeystoreType);

    try {
        in = new FileInputStream(destinationKeystorePath);
        ksout.load(in, destinationKeystorePasswordArr);
    } catch (java.io.FileNotFoundException e) {
        ksout.load(null, destinationKeystorePasswordArr);
    } finally {
        in.close();
    }

    Enumeration<String> en = ksin.aliases();
    while (en.hasMoreElements()) {
        String alias = en.nextElement();

        if ((sourceAlias == null) || (sourceAlias.equalsIgnoreCase(alias))) {

            if (ksout.containsAlias(alias)) {
                log.info(CommonResourceBundle.getInstance().getString(
                        "message.destinationKeystorePathAlreadyContains",
                        new Object[] { destinationKeystorePath, alias }));
                continue;
            }

            //Use existing alias if no destinationAlias specified
            if (destinationAlias == null) {
                destinationAlias = alias;
            }

            if (ksin.isCertificateEntry(alias)) {
                log.debug(CommonResourceBundle.getInstance().getString("message.importingCertificate",
                        new Object[] { alias }));
                ksout.setCertificateEntry(destinationAlias, ksin.getCertificate(alias));
            }

            if (ksin.isKeyEntry(alias)) {
                log.debug(CommonResourceBundle.getInstance().getString("message.importingKey",
                        new Object[] { alias }));
                Certificate[] certChain = ksin.getCertificateChain(alias);
                ksout.setKeyEntry(destinationAlias, ksin.getKey(alias, sourceKeyPasswordArr),
                        destinationKeyPasswordArr, certChain);
            }
        }

    }

    //---------  Overwrite the destination keystore with new keys/certs which is a merge of source and original destination keystores--------------
    FileOutputStream out = new FileOutputStream(destinationKeystorePath);
    ksout.store(out, destinationKeystorePasswordArr);
    out.close();
    log.debug(CommonResourceBundle.getInstance().getString("message.keystoreCopySuccessful"));
}

From source file:org.eclipse.gyrex.admin.ui.http.jetty.internal.ImportCertificateDialog.java

void importKeystore(final InputStream in) throws Exception {
    KeyStore tempKs;
    if (keystoreTypeField.isSelected(0)) {
        tempKs = KeyStore.getInstance("JKS");
    } else if (keystoreTypeField.isSelected(1)) {
        tempKs = KeyStore.getInstance("PKCS12");
    } else {//  w w  w.j  av a  2 s . c  o  m
        throw new IllegalArgumentException(
                "Please select a keystore type before uploading a keystore and retry.");
    }

    final String keystorePassword = keyStorePasswordField.getText();
    final String keyPassword = keyPasswordField.getText();

    // load keystore
    tempKs.load(new BufferedInputStream(in), null != keystorePassword ? keystorePassword.toCharArray() : null);

    // initialize new JKS store
    final KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(null);

    generatedKeystorePassword = UUID.randomUUID().toString().toCharArray();
    generatedKeyPassword = UUID.randomUUID().toString().toCharArray();

    // verify and copy into new store
    final Enumeration aliases = tempKs.aliases();
    while (aliases.hasMoreElements()) {
        final String alias = (String) aliases.nextElement();
        if (tempKs.isKeyEntry(alias)) {
            final Key key = tempKs.getKey(alias, null != keyPassword ? keyPassword.toCharArray()
                    : null != keystorePassword ? keystorePassword.toCharArray() : null);
            Certificate[] chain = tempKs.getCertificateChain(alias);
            if (null == chain) {
                final Certificate certificate = tempKs.getCertificate(alias);
                if (null == certificate) {
                    // skip to next
                    continue;
                }
                chain = new Certificate[] { certificate };
            }
            ks.setKeyEntry("jetty", key, generatedKeyPassword, chain);
            break;
        }
    }

    if (!ks.aliases().hasMoreElements()) {
        throw new IllegalArgumentException(
                "The uploaded keystore does not have a valid key + certificate chain entry. Please use a different keystore and retry.");
    }

    // write into bytes
    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    ks.store(out, generatedKeystorePassword);

    keystoreBytes = out.toByteArray();
}

From source file:org.wso2.carbon.idp.mgt.IdentityProviderManager.java

/**
 * Retrieves resident Identity provider for a given tenant
 *
 * @param tenantDomain Tenant domain whose resident IdP is requested
 * @return <code>LocalIdentityProvider</code>
 * @throws IdentityProviderManagementException Error when getting Resident Identity Providers
 *///from ww  w. j av a 2  s. com
public IdentityProvider getResidentIdP(String tenantDomain) throws IdentityProviderManagementException {

    String tenantContext = "";
    if (!MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equalsIgnoreCase(tenantDomain)) {
        tenantContext = MultitenantConstants.TENANT_AWARE_URL_PREFIX + "/" + tenantDomain + "/";
    }

    String serverUrl = IdentityUtil.getServerURL("") + "/";

    String openIdUrl = null;
    String samlSSOUrl = null;
    String samlLogoutUrl = null;
    String oauth1RequestTokenUrl = null;
    String oauth1AuthorizeUrl = null;
    String oauth1AccessTokenUrl = null;
    String oauth2AuthzEPUrl = null;
    String oauth2TokenEPUrl = null;
    String oauth2UserInfoEPUrl = null;
    String passiveStsUrl = null;
    String stsUrl = null;
    String scimUserEndpoint = null;
    String scimGroupsEndpoint = null;

    OMElement elem = IdentityConfigParser.getInstance().getConfigElement("OpenID.OpenIDServerUrl");
    if (elem != null) {
        openIdUrl = elem.getText();
    }
    elem = IdentityConfigParser.getInstance().getConfigElement("SSOService.IdentityProviderURL");
    if (elem != null) {
        samlSSOUrl = elem.getText();
        samlLogoutUrl = samlSSOUrl;
    }
    elem = IdentityConfigParser.getInstance().getConfigElement("OAuth.OAuth1RequestTokenUrl");
    if (elem != null) {
        oauth1RequestTokenUrl = elem.getText();
    }
    elem = IdentityConfigParser.getInstance().getConfigElement("OAuth.OAuth1AuthorizeUrl");
    if (elem != null) {
        oauth1AuthorizeUrl = elem.getText();
    }
    elem = IdentityConfigParser.getInstance().getConfigElement("OAuth.OAuth1AccessTokenUrl");
    if (elem != null) {
        oauth1AccessTokenUrl = elem.getText();
    }
    elem = IdentityConfigParser.getInstance().getConfigElement("OAuth.OAuth2AuthzEPUrl");
    if (elem != null) {
        oauth2AuthzEPUrl = elem.getText();
    }
    elem = IdentityConfigParser.getInstance().getConfigElement("OAuth.OAuth2TokenEPUrl");
    if (elem != null) {
        oauth2TokenEPUrl = elem.getText();
    }
    elem = IdentityConfigParser.getInstance().getConfigElement("OAuth.OAuth2UserInfoEPUrl");
    if (elem != null) {
        oauth2UserInfoEPUrl = elem.getText();
    }
    elem = IdentityConfigParser.getInstance().getConfigElement("PassiveSTS.IdentityProviderURL");
    if (elem != null) {
        passiveStsUrl = elem.getText();
    }
    elem = IdentityConfigParser.getInstance().getConfigElement("SecurityTokenService.IdentityProviderURL");
    if (elem != null) {
        stsUrl = elem.getText();
    }
    elem = IdentityConfigParser.getInstance().getConfigElement("SCIM.UserEPUrl");
    if (elem != null) {
        scimUserEndpoint = elem.getText();
    }
    elem = IdentityConfigParser.getInstance().getConfigElement("SCIM.GroupEPUrl");
    if (elem != null) {
        scimGroupsEndpoint = elem.getText();
    }

    if (StringUtils.isBlank(openIdUrl)) {
        openIdUrl = serverUrl + "openid";
    }
    if (StringUtils.isBlank(samlSSOUrl)) {
        samlSSOUrl = serverUrl + "samlsso";
    }
    if (StringUtils.isBlank(samlLogoutUrl)) {
        samlLogoutUrl = serverUrl + "samlsso";
    }
    if (StringUtils.isBlank(oauth1RequestTokenUrl)) {
        oauth1RequestTokenUrl = serverUrl + "oauth/request-token";
    }
    if (StringUtils.isBlank(oauth1AuthorizeUrl)) {
        oauth1AuthorizeUrl = serverUrl + "oauth/authorize-url";
    }
    if (StringUtils.isBlank(oauth1AccessTokenUrl)) {
        oauth1AccessTokenUrl = serverUrl + "oauth/access-token";
    }
    if (StringUtils.isBlank(oauth2AuthzEPUrl)) {
        oauth2AuthzEPUrl = serverUrl + "oauth2/authorize";
    }
    if (StringUtils.isBlank(oauth2TokenEPUrl)) {
        oauth2TokenEPUrl = serverUrl + "oauth2/token";
    }
    if (StringUtils.isBlank(oauth2UserInfoEPUrl)) {
        oauth2UserInfoEPUrl = serverUrl + "oauth2/userinfo";
    }
    if (StringUtils.isBlank(passiveStsUrl)) {
        passiveStsUrl = serverUrl + "passivests";
    }
    if (StringUtils.isBlank(stsUrl)) {
        stsUrl = serverUrl + "services/" + tenantContext + "wso2carbon-sts";
    }
    if (StringUtils.isBlank(scimUserEndpoint)) {
        scimUserEndpoint = serverUrl + "wso2/scim/Users";
    }
    if (StringUtils.isBlank(scimGroupsEndpoint)) {
        scimGroupsEndpoint = serverUrl + "wso2/scim/Groups";
    }

    IdentityProvider identityProvider = dao.getIdPByName(null,
            IdentityApplicationConstants.RESIDENT_IDP_RESERVED_NAME,
            IdentityTenantUtil.getTenantId(tenantDomain), tenantDomain);
    if (identityProvider == null) {
        String message = "Could not find Resident Identity Provider for tenant " + tenantDomain;
        log.error(message);
        throw new IdentityProviderManagementException(message);
    }

    int tenantId = -1;
    try {
        tenantId = IdPManagementServiceComponent.getRealmService().getTenantManager().getTenantId(tenantDomain);
    } catch (UserStoreException e) {
        throw new IdentityProviderManagementException(
                "Exception occurred while retrieving Tenant ID from Tenant Domain " + tenantDomain, e);
    }
    X509Certificate cert = null;
    try {
        IdentityTenantUtil.initializeRegistry(tenantId, tenantDomain);
        KeyStoreManager keyStoreManager = KeyStoreManager.getInstance(tenantId);
        if (!MultitenantConstants.SUPER_TENANT_DOMAIN_NAME.equals(tenantDomain)) {
            // derive key store name
            String ksName = tenantDomain.trim().replace(".", "-");
            // derive JKS name
            String jksName = ksName + ".jks";
            KeyStore keyStore = keyStoreManager.getKeyStore(jksName);
            cert = (X509Certificate) keyStore.getCertificate(tenantDomain);
        } else {
            cert = keyStoreManager.getDefaultPrimaryCertificate();
        }
    } catch (Exception e) {
        String msg = "Error retrieving primary certificate for tenant : " + tenantDomain;
        log.error(msg, e);
        throw new IdentityProviderManagementException(msg, e);
    }
    if (cert == null) {
        throw new IdentityProviderManagementException(
                "Cannot find the primary certificate for tenant " + tenantDomain);
    }
    try {
        identityProvider.setCertificate(Base64.encode(cert.getEncoded()));
    } catch (CertificateEncodingException e) {
        String msg = "Error occurred while encoding primary certificate for tenant domain " + tenantDomain;
        log.error(msg, e);
        throw new IdentityProviderManagementException(msg, e);
    }

    List<FederatedAuthenticatorConfig> fedAuthnCofigs = new ArrayList<FederatedAuthenticatorConfig>();
    List<Property> propertiesList = null;

    FederatedAuthenticatorConfig openIdFedAuthn = IdentityApplicationManagementUtil.getFederatedAuthenticator(
            identityProvider.getFederatedAuthenticatorConfigs(),
            IdentityApplicationConstants.Authenticator.OpenID.NAME);
    if (openIdFedAuthn == null) {
        openIdFedAuthn = new FederatedAuthenticatorConfig();
        openIdFedAuthn.setName(IdentityApplicationConstants.Authenticator.OpenID.NAME);
    }
    propertiesList = new ArrayList<Property>(Arrays.asList(openIdFedAuthn.getProperties()));
    if (IdentityApplicationManagementUtil.getProperty(openIdFedAuthn.getProperties(),
            IdentityApplicationConstants.Authenticator.OpenID.OPEN_ID_URL) == null) {
        Property openIdUrlProp = new Property();
        openIdUrlProp.setName(IdentityApplicationConstants.Authenticator.OpenID.OPEN_ID_URL);
        openIdUrlProp.setValue(openIdUrl);
        propertiesList.add(openIdUrlProp);
    }
    openIdFedAuthn.setProperties(propertiesList.toArray(new Property[propertiesList.size()]));
    fedAuthnCofigs.add(openIdFedAuthn);

    FederatedAuthenticatorConfig saml2SSOFedAuthn = IdentityApplicationManagementUtil.getFederatedAuthenticator(
            identityProvider.getFederatedAuthenticatorConfigs(),
            IdentityApplicationConstants.Authenticator.SAML2SSO.NAME);
    if (saml2SSOFedAuthn == null) {
        saml2SSOFedAuthn = new FederatedAuthenticatorConfig();
        saml2SSOFedAuthn.setName(IdentityApplicationConstants.Authenticator.SAML2SSO.NAME);
    }
    propertiesList = new ArrayList<Property>(Arrays.asList(saml2SSOFedAuthn.getProperties()));
    if (IdentityApplicationManagementUtil.getProperty(saml2SSOFedAuthn.getProperties(),
            IdentityApplicationConstants.Authenticator.SAML2SSO.SSO_URL) == null) {
        Property ssoUrlProp = new Property();
        ssoUrlProp.setName(IdentityApplicationConstants.Authenticator.SAML2SSO.SSO_URL);
        ssoUrlProp.setValue(samlSSOUrl);
        propertiesList.add(ssoUrlProp);
    }
    if (IdentityApplicationManagementUtil.getProperty(saml2SSOFedAuthn.getProperties(),
            IdentityApplicationConstants.Authenticator.SAML2SSO.LOGOUT_REQ_URL) == null) {
        Property logoutReqUrlProp = new Property();
        logoutReqUrlProp.setName(IdentityApplicationConstants.Authenticator.SAML2SSO.LOGOUT_REQ_URL);
        logoutReqUrlProp.setValue(samlLogoutUrl);
        propertiesList.add(logoutReqUrlProp);
    }
    if (IdentityApplicationManagementUtil.getProperty(saml2SSOFedAuthn.getProperties(),
            IdentityApplicationConstants.Authenticator.SAML2SSO.IDP_ENTITY_ID) == null) {
        Property idPEntityIdProp = new Property();
        idPEntityIdProp.setName(IdentityApplicationConstants.Authenticator.SAML2SSO.IDP_ENTITY_ID);
        idPEntityIdProp.setValue(IdPManagementUtil.getResidentIdPEntityId());
        propertiesList.add(idPEntityIdProp);
    }
    saml2SSOFedAuthn.setProperties(propertiesList.toArray(new Property[propertiesList.size()]));
    fedAuthnCofigs.add(saml2SSOFedAuthn);

    FederatedAuthenticatorConfig oauth1FedAuthn = IdentityApplicationManagementUtil.getFederatedAuthenticator(
            identityProvider.getFederatedAuthenticatorConfigs(), IdentityApplicationConstants.OAuth10A.NAME);
    if (oauth1FedAuthn == null) {
        oauth1FedAuthn = new FederatedAuthenticatorConfig();
        oauth1FedAuthn.setName(IdentityApplicationConstants.OAuth10A.NAME);
    }
    propertiesList = new ArrayList<Property>(Arrays.asList(oauth1FedAuthn.getProperties()));
    if (IdentityApplicationManagementUtil.getProperty(oauth1FedAuthn.getProperties(),
            IdentityApplicationConstants.OAuth10A.OAUTH1_REQUEST_TOKEN_URL) == null) {
        Property oauth1ReqTokUrlProp = new Property();
        oauth1ReqTokUrlProp.setName(IdentityApplicationConstants.OAuth10A.OAUTH1_REQUEST_TOKEN_URL);
        oauth1ReqTokUrlProp.setValue(oauth1RequestTokenUrl);
        propertiesList.add(oauth1ReqTokUrlProp);
    }
    if (IdentityApplicationManagementUtil.getProperty(oauth1FedAuthn.getProperties(),
            IdentityApplicationConstants.OAuth10A.OAUTH1_AUTHORIZE_URL) == null) {
        Property oauth1AuthzUrlProp = new Property();
        oauth1AuthzUrlProp.setName(IdentityApplicationConstants.OAuth10A.OAUTH1_AUTHORIZE_URL);
        oauth1AuthzUrlProp.setValue(oauth1AuthorizeUrl);
        propertiesList.add(oauth1AuthzUrlProp);
    }
    if (IdentityApplicationManagementUtil.getProperty(oauth1FedAuthn.getProperties(),
            IdentityApplicationConstants.OAuth10A.OAUTH1_ACCESS_TOKEN_URL) == null) {
        Property oauth1AccessTokUrlProp = new Property();
        oauth1AccessTokUrlProp.setName(IdentityApplicationConstants.OAuth10A.OAUTH1_ACCESS_TOKEN_URL);
        oauth1AccessTokUrlProp.setValue(oauth1AccessTokenUrl);
        propertiesList.add(oauth1AccessTokUrlProp);
    }
    oauth1FedAuthn.setProperties(propertiesList.toArray(new Property[propertiesList.size()]));
    fedAuthnCofigs.add(oauth1FedAuthn);

    FederatedAuthenticatorConfig oidcFedAuthn = IdentityApplicationManagementUtil.getFederatedAuthenticator(
            identityProvider.getFederatedAuthenticatorConfigs(),
            IdentityApplicationConstants.Authenticator.OIDC.NAME);
    if (oidcFedAuthn == null) {
        oidcFedAuthn = new FederatedAuthenticatorConfig();
        oidcFedAuthn.setName(IdentityApplicationConstants.Authenticator.OIDC.NAME);
    }
    propertiesList = new ArrayList<Property>(Arrays.asList(oidcFedAuthn.getProperties()));
    if (IdentityApplicationManagementUtil.getProperty(oidcFedAuthn.getProperties(),
            IdentityApplicationConstants.Authenticator.OIDC.OAUTH2_AUTHZ_URL) == null) {
        Property authzUrlProp = new Property();
        authzUrlProp.setName(IdentityApplicationConstants.Authenticator.OIDC.OAUTH2_AUTHZ_URL);
        authzUrlProp.setValue(oauth2AuthzEPUrl);
        propertiesList.add(authzUrlProp);
    }
    if (IdentityApplicationManagementUtil.getProperty(oidcFedAuthn.getProperties(),
            IdentityApplicationConstants.Authenticator.OIDC.OAUTH2_TOKEN_URL) == null) {
        Property tokenUrlProp = new Property();
        tokenUrlProp.setName(IdentityApplicationConstants.Authenticator.OIDC.OAUTH2_TOKEN_URL);
        tokenUrlProp.setValue(oauth2TokenEPUrl);
        propertiesList.add(tokenUrlProp);
    }
    if (IdentityApplicationManagementUtil.getProperty(oidcFedAuthn.getProperties(),
            IdentityApplicationConstants.Authenticator.OIDC.OAUTH2_USER_INFO_EP_URL) == null) {
        Property userInfoUrlProp = new Property();
        userInfoUrlProp.setName(IdentityApplicationConstants.Authenticator.OIDC.OAUTH2_USER_INFO_EP_URL);
        userInfoUrlProp.setValue(oauth2UserInfoEPUrl);
        propertiesList.add(userInfoUrlProp);
    }
    oidcFedAuthn.setProperties(propertiesList.toArray(new Property[propertiesList.size()]));
    fedAuthnCofigs.add(oidcFedAuthn);

    FederatedAuthenticatorConfig passiveSTSFedAuthn = IdentityApplicationManagementUtil
            .getFederatedAuthenticator(identityProvider.getFederatedAuthenticatorConfigs(),
                    IdentityApplicationConstants.Authenticator.PassiveSTS.NAME);
    if (passiveSTSFedAuthn == null) {
        passiveSTSFedAuthn = new FederatedAuthenticatorConfig();
        passiveSTSFedAuthn.setName(IdentityApplicationConstants.Authenticator.PassiveSTS.NAME);
    }
    propertiesList = new ArrayList<Property>(Arrays.asList(passiveSTSFedAuthn.getProperties()));
    if (IdentityApplicationManagementUtil.getProperty(passiveSTSFedAuthn.getProperties(),
            IdentityApplicationConstants.Authenticator.PassiveSTS.IDENTITY_PROVIDER_URL) == null) {
        Property passiveSTSUrlProp = new Property();
        passiveSTSUrlProp.setName(IdentityApplicationConstants.Authenticator.PassiveSTS.IDENTITY_PROVIDER_URL);
        passiveSTSUrlProp.setValue(passiveStsUrl);
        propertiesList.add(passiveSTSUrlProp);
    }
    passiveSTSFedAuthn.setProperties(propertiesList.toArray(new Property[propertiesList.size()]));
    fedAuthnCofigs.add(passiveSTSFedAuthn);

    FederatedAuthenticatorConfig stsFedAuthn = IdentityApplicationManagementUtil.getFederatedAuthenticator(
            identityProvider.getFederatedAuthenticatorConfigs(),
            IdentityApplicationConstants.Authenticator.WSTrust.NAME);
    if (stsFedAuthn == null) {
        stsFedAuthn = new FederatedAuthenticatorConfig();
        stsFedAuthn.setName(IdentityApplicationConstants.Authenticator.WSTrust.NAME);
    }
    propertiesList = new ArrayList<Property>(Arrays.asList(stsFedAuthn.getProperties()));
    if (IdentityApplicationManagementUtil.getProperty(stsFedAuthn.getProperties(),
            IdentityApplicationConstants.Authenticator.WSTrust.IDENTITY_PROVIDER_URL) == null) {
        Property stsUrlProp = new Property();
        stsUrlProp.setName(IdentityApplicationConstants.Authenticator.WSTrust.IDENTITY_PROVIDER_URL);
        stsUrlProp.setValue(stsUrl);
        propertiesList.add(stsUrlProp);
    }
    stsFedAuthn.setProperties(propertiesList.toArray(new Property[propertiesList.size()]));
    fedAuthnCofigs.add(stsFedAuthn);

    FederatedAuthenticatorConfig sessionTimeoutConfig = IdentityApplicationManagementUtil
            .getFederatedAuthenticator(identityProvider.getFederatedAuthenticatorConfigs(),
                    IdentityApplicationConstants.Authenticator.IDPProperties.NAME);
    if (sessionTimeoutConfig == null) {
        sessionTimeoutConfig = new FederatedAuthenticatorConfig();
        sessionTimeoutConfig.setName(IdentityApplicationConstants.Authenticator.IDPProperties.NAME);
    }
    propertiesList = new ArrayList<Property>(Arrays.asList(sessionTimeoutConfig.getProperties()));
    if (IdentityApplicationManagementUtil.getProperty(sessionTimeoutConfig.getProperties(),
            IdentityApplicationConstants.Authenticator.IDPProperties.SESSION_IDLE_TIME_OUT) == null) {
        Property sessionIdletimeOutProp = new Property();
        sessionIdletimeOutProp
                .setName(IdentityApplicationConstants.Authenticator.IDPProperties.SESSION_IDLE_TIME_OUT);
        String idleTimeout = IdentityUtil.getProperty(IdentityConstants.ServerConfig.SESSION_IDLE_TIMEOUT);
        if (StringUtils.isBlank(idleTimeout)) {
            idleTimeout = IdentityApplicationConstants.Authenticator.IDPProperties.SESSION_IDLE_TIME_OUT_DEFAULT;
        } else if (!StringUtils.isNumeric(idleTimeout)) {
            log.warn("SessionIdleTimeout in identity.xml should be a numeric value");
            idleTimeout = IdentityApplicationConstants.Authenticator.IDPProperties.SESSION_IDLE_TIME_OUT_DEFAULT;
        }
        sessionIdletimeOutProp.setValue(idleTimeout);
        propertiesList.add(sessionIdletimeOutProp);
    }
    if (IdentityApplicationManagementUtil.getProperty(sessionTimeoutConfig.getProperties(),
            IdentityApplicationConstants.Authenticator.IDPProperties.REMEMBER_ME_TIME_OUT) == null) {
        Property rememberMeTimeOutProp = new Property();
        rememberMeTimeOutProp
                .setName(IdentityApplicationConstants.Authenticator.IDPProperties.REMEMBER_ME_TIME_OUT);
        String rememberMeTimeout = IdentityUtil
                .getProperty(IdentityConstants.ServerConfig.REMEMBER_ME_TIME_OUT);
        if (StringUtils.isBlank(rememberMeTimeout)) {
            rememberMeTimeout = IdentityApplicationConstants.Authenticator.IDPProperties.REMEMBER_ME_TIME_OUT_DEFAULT;
        } else if (!StringUtils.isNumeric(rememberMeTimeout)) {
            log.warn("RememberMeTimeout in identity.xml should be a numeric value");
            rememberMeTimeout = IdentityApplicationConstants.Authenticator.IDPProperties.REMEMBER_ME_TIME_OUT_DEFAULT;
        }
        rememberMeTimeOutProp.setValue(rememberMeTimeout);
        propertiesList.add(rememberMeTimeOutProp);
    }
    if (IdentityApplicationManagementUtil.getProperty(sessionTimeoutConfig.getProperties(),
            IdentityApplicationConstants.Authenticator.IDPProperties.CLEAN_UP_PERIOD) == null) {
        Property cleanUpPeriodProp = new Property();
        cleanUpPeriodProp.setName(IdentityApplicationConstants.Authenticator.IDPProperties.CLEAN_UP_PERIOD);
        String cleanUpPeriod = IdentityUtil.getProperty(IdentityConstants.ServerConfig.CLEAN_UP_PERIOD);
        if (StringUtils.isBlank(cleanUpPeriod)) {
            cleanUpPeriod = IdentityApplicationConstants.Authenticator.IDPProperties.CLEAN_UP_PERIOD_DEFAULT;
        } else if (!StringUtils.isNumeric(cleanUpPeriod)) {
            log.warn("PersistanceCleanUpPeriod in identity.xml should be a numeric value");
            cleanUpPeriod = IdentityApplicationConstants.Authenticator.IDPProperties.CLEAN_UP_PERIOD_DEFAULT;
        }
        cleanUpPeriodProp.setValue(cleanUpPeriod);
        propertiesList.add(cleanUpPeriodProp);
    }
    sessionTimeoutConfig.setProperties(propertiesList.toArray(new Property[propertiesList.size()]));
    fedAuthnCofigs.add(sessionTimeoutConfig);

    identityProvider.setFederatedAuthenticatorConfigs(
            fedAuthnCofigs.toArray(new FederatedAuthenticatorConfig[fedAuthnCofigs.size()]));

    ProvisioningConnectorConfig scimProvConn = IdentityApplicationManagementUtil
            .getProvisioningConnector(identityProvider.getProvisioningConnectorConfigs(), "scim");
    if (scimProvConn == null) {
        scimProvConn = new ProvisioningConnectorConfig();
        scimProvConn.setName("scim");
    }
    propertiesList = new ArrayList<Property>(Arrays.asList(scimProvConn.getProvisioningProperties()));
    if (IdentityApplicationManagementUtil.getProperty(scimProvConn.getProvisioningProperties(),
            "scimUserEndpoint") == null) {
        Property property = new Property();
        property.setName("scimUserEndpoint");
        property.setValue(scimUserEndpoint);
        propertiesList.add(property);
    }
    if (IdentityApplicationManagementUtil.getProperty(scimProvConn.getProvisioningProperties(),
            "scimUserEndpoint") == null) {
        Property property = new Property();
        property.setName("scimGroupEndpoint");
        property.setValue(scimGroupsEndpoint);
        propertiesList.add(property);
    }
    scimProvConn.setProvisioningProperties(propertiesList.toArray(new Property[propertiesList.size()]));
    identityProvider.setProvisioningConnectorConfigs(new ProvisioningConnectorConfig[] { scimProvConn });

    return identityProvider;
}

From source file:AuthSSLProtocolSocketFactory.java

private SSLContext createSSLContext() {
    try {/*w ww. j a  v  a 2s . co  m*/
        KeyManager[] keymanagers = null;
        TrustManager[] trustmanagers = null;
        if (this.keystoreUrl != null) {
            KeyStore keystore = createKeyStore(this.keystoreUrl, this.keystorePassword);
            Enumeration aliases = keystore.aliases();
            while (aliases.hasMoreElements()) {
                String alias = (String) aliases.nextElement();
                Certificate[] certs = keystore.getCertificateChain(alias);
                if (certs != null) {
                    System.out.println("Certificate chain '" + alias + "':");
                    for (int c = 0; c < certs.length; c++) {
                        if (certs[c] instanceof X509Certificate) {
                            X509Certificate cert = (X509Certificate) certs[c];
                            System.out.println(" Certificate " + (c + 1) + ":");
                            System.out.println("  Subject DN: " + cert.getSubjectDN());
                            System.out.println("  Signature Algorithm: " + cert.getSigAlgName());
                            System.out.println("  Valid from: " + cert.getNotBefore());
                            System.out.println("  Valid until: " + cert.getNotAfter());
                            System.out.println("  Issuer: " + cert.getIssuerDN());
                        }
                    }
                }
            }
            keymanagers = createKeyManagers(keystore, this.keystorePassword);
        }
        if (this.truststoreUrl != null) {
            KeyStore keystore = createKeyStore(this.truststoreUrl, this.truststorePassword);
            Enumeration aliases = keystore.aliases();
            while (aliases.hasMoreElements()) {
                String alias = (String) aliases.nextElement();
                System.out.println("Trusted certificate '" + alias + "':");
                Certificate trustedcert = keystore.getCertificate(alias);
                if (trustedcert != null && trustedcert instanceof X509Certificate) {
                    X509Certificate cert = (X509Certificate) trustedcert;
                    System.out.println("  Subject DN: " + cert.getSubjectDN());
                    System.out.println("  Signature Algorithm: " + cert.getSigAlgName());
                    System.out.println("  Valid from: " + cert.getNotBefore());
                    System.out.println("  Valid until: " + cert.getNotAfter());
                    System.out.println("  Issuer: " + cert.getIssuerDN());
                }
            }
            trustmanagers = createTrustManagers(keystore);
        }
        SSLContext sslcontext = SSLContext.getInstance("SSL");
        sslcontext.init(keymanagers, trustmanagers, null);
        return sslcontext;
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
        throw new AuthSSLInitializationError("Unsupported algorithm exception: " + e.getMessage());
    } catch (KeyStoreException e) {
        e.printStackTrace();
        throw new AuthSSLInitializationError("Keystore exception: " + e.getMessage());
    } catch (GeneralSecurityException e) {
        e.printStackTrace();
        throw new AuthSSLInitializationError("Key management exception: " + e.getMessage());
    } catch (IOException e) {
        e.printStackTrace();
        throw new AuthSSLInitializationError("I/O error reading keystore/truststore file: " + e.getMessage());
    }
}

From source file:com.mhise.util.MHISEUtil.java

public static boolean verifyP12StorePassword(String keyStorePath, String password, String serialNumber,
        Context ctx) {// w  w  w. j  av a2s. c  o  m
    boolean isInstalledCertificateValid = false;
    KeyStore trustStore = null;
    FileInputStream fin = null;
    try {
        trustStore = KeyStore.getInstance("PKCS12");
    } catch (KeyStoreException e2) {
        // TODO Auto-generated catch block
        e2.printStackTrace();
    }

    File file = new File(keyStorePath);
    if (file.exists()) {

        try {
            fin = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        try {
            trustStore.load(fin, password.toCharArray());
            fin.close();
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            MHISEUtil.displayDialog(ctx, "Invalid Password", null);
        } catch (CertificateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            MHISEUtil.displayDialog(ctx, "Invalid Password", null);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            MHISEUtil.displayDialog(ctx, "Invalid Password", null);
        }

        Enumeration<String> aliases = null;
        try {
            aliases = trustStore.aliases();
        } catch (KeyStoreException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        try {

            while (aliases.hasMoreElements()) {
                String alias = aliases.nextElement();
                java.security.cert.X509Certificate cert = null;
                try {
                    cert = (X509Certificate) trustStore.getCertificate(alias);
                } catch (KeyStoreException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                if (cert.getSerialNumber().toString().equals(serialNumber)) {
                    // isInstalledCertificateValid = true; 
                    SharedPreferences sharedPreferences = ctx.getSharedPreferences(Constants.PREFS_NAME,
                            Context.MODE_PRIVATE);
                    SharedPreferences.Editor editor = sharedPreferences.edit();

                    editor.putString(Constants.KEY_SERIAL_NUMBER, "" + cert.getSerialNumber().toString(16));
                    editor.commit();

                    return true;
                }
            }
        } catch (NullPointerException e) {
            // TODO: handle exception
            Logger.debug("password invalid", "" + e);
        }
    }

    return isInstalledCertificateValid;
}

From source file:gov.nist.toolkit.soap.axis2.AuthSSLProtocolSocketFactory.java

private SSLContext createSSLContext() throws IOException {
    try {//from  w w w. j a  v  a 2 s.c o  m
        KeyManager[] keymanagers = null;
        TrustManager[] trustmanagers = null;
        if (this.keystoreUrl != null) {
            KeyStore keystore = createKeyStore(this.keystoreUrl, this.keystorePassword);
            if (LOG.isDebugEnabled()) {
                Enumeration aliases = keystore.aliases();
                while (aliases.hasMoreElements()) {
                    String alias = (String) aliases.nextElement();
                    Certificate[] certs = keystore.getCertificateChain(alias);
                    if (certs != null) {
                        LOG.debug("Certificate chain '" + alias + "':");
                        for (int c = 0; c < certs.length; c++) {
                            if (certs[c] instanceof X509Certificate) {
                                X509Certificate cert = (X509Certificate) certs[c];
                                LOG.debug(" Certificate " + (c + 1) + ":");
                                LOG.debug("  Subject DN: " + cert.getSubjectDN());
                                LOG.debug("  Signature Algorithm: " + cert.getSigAlgName());
                                LOG.debug("  Valid from: " + cert.getNotBefore());
                                LOG.debug("  Valid until: " + cert.getNotAfter());
                                LOG.debug("  Issuer: " + cert.getIssuerDN());
                            }
                        }
                    }
                }
            }
            keymanagers = createKeyManagers(keystore, this.keystorePassword);
        }
        if (this.truststoreUrl != null) {
            KeyStore keystore = createKeyStore(this.truststoreUrl, this.truststorePassword);
            if (LOG.isDebugEnabled()) {
                Enumeration aliases = keystore.aliases();
                while (aliases.hasMoreElements()) {
                    String alias = (String) aliases.nextElement();
                    LOG.debug("Trusted certificate '" + alias + "':");
                    Certificate trustedcert = keystore.getCertificate(alias);
                    if (trustedcert != null && trustedcert instanceof X509Certificate) {
                        X509Certificate cert = (X509Certificate) trustedcert;
                        LOG.debug("  Subject DN: " + cert.getSubjectDN());
                        LOG.debug("  Signature Algorithm: " + cert.getSigAlgName());
                        LOG.debug("  Valid from: " + cert.getNotBefore());
                        LOG.debug("  Valid until: " + cert.getNotAfter());
                        LOG.debug("  Issuer: " + cert.getIssuerDN());
                    }
                }
            }
            trustmanagers = createTrustManagers(keystore);
        }
        SSLContext sslcontext = SSLContext.getInstance("SSL");
        sslcontext.init(keymanagers, trustmanagers, null);
        return sslcontext;
    } catch (NoSuchAlgorithmException e) {
        LOG.error(e.getMessage(), e);
        throw new IOException("Unsupported algorithm exception: " + e.getMessage());
    } catch (KeyStoreException e) {
        LOG.error(e.getMessage(), e);
        throw new IOException("Keystore exception: " + e.getMessage());
    } catch (GeneralSecurityException e) {
        LOG.error(e.getMessage(), e);
        throw new IOException("Key management exception: " + e.getMessage());
    } catch (IOException e) {
        LOG.error(e.getMessage(), e);
        throw new IOException("I/O error reading keystore/truststore file: " + e.getMessage());
    }
}

From source file:com.utest.webservice.client.rest.AuthSSLProtocolSocketFactory.java

@SuppressWarnings("unchecked")
private SSLContext createSSLContext() {
    try {/*from   ww w  .j av a  2s  .  c  o m*/
        KeyManager[] keymanagers = null;
        TrustManager[] trustmanagers = null;
        if (this.keystoreUrl != null) {
            KeyStore keystore = createKeyStore(this.keystoreUrl, this.keystorePassword);
            if (true) {
                Enumeration aliases = keystore.aliases();
                while (aliases.hasMoreElements()) {
                    String alias = (String) aliases.nextElement();
                    Certificate[] certs = keystore.getCertificateChain(alias);
                    if (certs != null) {
                        System.out.println("Certificate chain '" + alias + "':");
                        for (int c = 0; c < certs.length; c++) {
                            if (certs[c] instanceof X509Certificate) {
                                X509Certificate cert = (X509Certificate) certs[c];
                                System.out.println(" Certificate " + (c + 1) + ":");
                                System.out.println("  Subject DN: " + cert.getSubjectDN());
                                System.out.println("  Signature Algorithm: " + cert.getSigAlgName());
                                System.out.println("  Valid from: " + cert.getNotBefore());
                                System.out.println("  Valid until: " + cert.getNotAfter());
                                System.out.println("  Issuer: " + cert.getIssuerDN());
                            }
                        }
                    }
                }
            }
            keymanagers = createKeyManagers(keystore, this.keystorePassword);
        }
        if (this.truststoreUrl != null) {
            KeyStore keystore = createKeyStore(this.truststoreUrl, this.truststorePassword);
            if (true) {
                Enumeration aliases = keystore.aliases();
                while (aliases.hasMoreElements()) {
                    String alias = (String) aliases.nextElement();
                    System.out.println("Trusted certificate '" + alias + "':");
                    Certificate trustedcert = keystore.getCertificate(alias);
                    if (trustedcert != null && trustedcert instanceof X509Certificate) {
                        X509Certificate cert = (X509Certificate) trustedcert;
                        System.out.println("  Subject DN: " + cert.getSubjectDN());
                        System.out.println("  Signature Algorithm: " + cert.getSigAlgName());
                        System.out.println("  Valid from: " + cert.getNotBefore());
                        System.out.println("  Valid until: " + cert.getNotAfter());
                        System.out.println("  Issuer: " + cert.getIssuerDN());
                    }
                }
            }
            trustmanagers = createTrustManagers(keystore);
        }
        SSLContext sslcontext = SSLContext.getInstance("SSL");
        sslcontext.init(keymanagers, trustmanagers, null);
        return sslcontext;
    } catch (NoSuchAlgorithmException e) {
        System.out.println(e.getMessage());
        throw new AuthSSLInitializationError("Unsupported algorithm exception: " + e.getMessage());
    } catch (KeyStoreException e) {
        System.out.println(e.getMessage());
        throw new AuthSSLInitializationError("Keystore exception: " + e.getMessage());
    } catch (GeneralSecurityException e) {
        System.out.println(e.getMessage());
        throw new AuthSSLInitializationError("Key management exception: " + e.getMessage());
    } catch (IOException e) {
        System.out.println(e.getMessage());
        throw new AuthSSLInitializationError("I/O error reading keystore/truststore file: " + e.getMessage());
    }
}