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:io.atomix.cluster.messaging.impl.NettyMessagingService.java

private void logKeyStore(KeyStore ks, String ksLocation, char[] ksPwd) {
    if (log.isInfoEnabled()) {
        log.info("Loaded cluster key store from: {}", ksLocation);
        try {/*from w w w  .  j  a v a2 s.  co m*/
            for (Enumeration<String> e = ks.aliases(); e.hasMoreElements();) {
                String alias = e.nextElement();
                Key key = ks.getKey(alias, ksPwd);
                Certificate[] certs = ks.getCertificateChain(alias);
                log.debug("{} -> {}", alias, certs);
                final byte[] encodedKey;
                if (certs != null && certs.length > 0) {
                    encodedKey = certs[0].getEncoded();
                } else {
                    log.info("Could not find cert chain for {}, using fingerprint of key instead...", alias);
                    encodedKey = key.getEncoded();
                }
                // Compute the certificate's fingerprint (use the key if certificate cannot be found)
                MessageDigest digest = MessageDigest.getInstance("SHA1");
                digest.update(encodedKey);
                StringJoiner fingerprint = new StringJoiner(":");
                for (byte b : digest.digest()) {
                    fingerprint.add(String.format("%02X", b));
                }
                log.info("{} -> {}", alias, fingerprint);
            }
        } catch (Exception e) {
            log.warn("Unable to print contents of key store: {}", ksLocation, e);
        }
    }
}

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 {/*from ww  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.alfresco.encryption.AlfrescoKeyStoreImpl.java

protected KeyMap cacheKeys(KeyStore ks, KeyInfoManager keyInfoManager)
        throws UnrecoverableKeyException, KeyStoreException, NoSuchAlgorithmException {
    KeyMap keys = new KeyMap();

    // load and cache the keys
    for (Entry<String, KeyInformation> keyEntry : keyInfoManager.getKeyInfo().entrySet()) {
        String keyAlias = keyEntry.getKey();

        KeyInformation keyInfo = keyInfoManager.getKeyInformation(keyAlias);
        String passwordStr = keyInfo != null ? keyInfo.getPassword() : null;

        // Null is an acceptable value (means no key)
        Key key = null;//from  w w w .  ja v  a  2 s  .  c om

        // Attempt to get the key
        key = ks.getKey(keyAlias, passwordStr == null ? null : passwordStr.toCharArray());
        if (key != null) {
            keys.setKey(keyAlias, key);
        }
        // Key loaded
        if (logger.isDebugEnabled()) {
            logger.debug(
                    "Retrieved key from keystore: \n" + "   Location: " + getKeyStoreParameters().getLocation()
                            + "\n" + "   Provider: " + getKeyStoreParameters().getProvider() + "\n"
                            + "   Type:     " + getKeyStoreParameters().getType() + "\n" + "   Alias:    "
                            + keyAlias + "\n" + "   Password?: " + (passwordStr != null));

            Certificate[] certs = ks.getCertificateChain(keyAlias);
            if (certs != null) {
                logger.debug("Certificate chain '" + keyAlias + "':");
                for (int c = 0; c < certs.length; c++) {
                    if (certs[c] instanceof X509Certificate) {
                        X509Certificate cert = (X509Certificate) certs[c];
                        logger.debug(" Certificate " + (c + 1) + ":");
                        logger.debug("  Subject DN: " + cert.getSubjectDN());
                        logger.debug("  Signature Algorithm: " + cert.getSigAlgName());
                        logger.debug("  Valid from: " + cert.getNotBefore());
                        logger.debug("  Valid until: " + cert.getNotAfter());
                        logger.debug("  Issuer: " + cert.getIssuerDN());
                    }
                }
            }
        }
    }

    return keys;
}

From source file:org.wso2.carbon.security.keystore.KeyStoreAdmin.java

public void addKeyStore(byte[] content, String filename, String password, String provider, String type,
        String pvtkeyPass) throws SecurityConfigException {
    if (filename == null) {
        throw new SecurityConfigException("Key Store name can't be null");
    }/*from   ww  w  . j  a  v a2s. c  om*/
    try {
        if (KeyStoreUtil.isPrimaryStore(filename)) {
            throw new SecurityConfigException("Key store " + filename + " already available");
        }

        String path = SecurityConstants.KEY_STORES + "/" + filename;
        if (registry.resourceExists(path)) {
            throw new SecurityConfigException("Key store " + filename + " already available");
        }

        KeyStore keyStore = KeyStore.getInstance(type);
        keyStore.load(new ByteArrayInputStream(content), password.toCharArray());

        // check for more private keys
        Enumeration enumeration = keyStore.aliases();
        String pvtKeyAlias = null;
        while (enumeration.hasMoreElements()) {
            String alias = (String) enumeration.nextElement();
            if (keyStore.isKeyEntry(alias)) {
                if (pvtKeyAlias == null) {
                    pvtKeyAlias = alias;
                } else {
                    // more than one private key
                    throw new SecurityConfigException("more than one private key");
                }
            }
        }

        // just to test weather pvt key password is correct.
        keyStore.getKey(pvtKeyAlias, pvtkeyPass.toCharArray());

        CryptoUtil cryptoUtil = CryptoUtil.getDefaultCryptoUtil();

        Resource resource = registry.newResource();
        resource.addProperty(SecurityConstants.PROP_PASSWORD,
                cryptoUtil.encryptAndBase64Encode(password.getBytes()));
        resource.addProperty(SecurityConstants.PROP_PROVIDER, provider);
        resource.addProperty(SecurityConstants.PROP_TYPE, type);

        if (pvtKeyAlias != null) {
            resource.addProperty(SecurityConstants.PROP_PRIVATE_KEY_ALIAS, pvtKeyAlias);
            resource.addProperty(SecurityConstants.PROP_PRIVATE_KEY_PASS,
                    cryptoUtil.encryptAndBase64Encode(pvtkeyPass.getBytes()));
        }

        resource.setContent(content);
        registry.put(path, resource);
    } catch (SecurityConfigException e) {
        throw e;
    } catch (Exception e) {
        String msg = "Error when adding a keyStore";
        log.error(msg, e);
        throw new SecurityConfigException(msg, e);
    }
}

From source file:org.wso2.carbon.device.mgt.iot.virtualfirealarm.agent.enrollment.EnrollmentManager.java

public void setEnrollmentStatus() {
    KeyStore keyStore;
    try {//from   ww w. jav a  2 s .  c o  m
        keyStore = KeyStore.getInstance(AgentConstants.DEVICE_KEYSTORE_TYPE);

        this.isEnrolled = (keyStore.containsAlias(AgentConstants.DEVICE_CERT_ALIAS)
                && keyStore.containsAlias(AgentConstants.DEVICE_PRIVATE_KEY_ALIAS)
                && keyStore.containsAlias(AgentConstants.SERVER_CA_CERT_ALIAS));

    } catch (KeyStoreException e) {
        log.error(AgentConstants.LOG_APPENDER + "An error occurred whilst accessing the device KeyStore '"
                + AgentConstants.DEVICE_KEYSTORE + "' with keystore type ["
                + AgentConstants.DEVICE_KEYSTORE_TYPE + "] to ensure enrollment status.");
        log.error(AgentConstants.LOG_APPENDER + e);
        log.warn(AgentConstants.LOG_APPENDER + "Device will be re-enrolled.");
        return;
    }
    try {
        if (this.isEnrolled) {
            this.SCEPCertificate = (X509Certificate) keyStore.getCertificate(AgentConstants.DEVICE_CERT_ALIAS);
            this.privateKey = (PrivateKey) keyStore.getKey(AgentConstants.DEVICE_PRIVATE_KEY_ALIAS,
                    AgentConstants.DEVICE_KEYSTORE_PASSWORD.toCharArray());
            this.publicKey = SCEPCertificate.getPublicKey();

            X509Certificate serverCACert = (X509Certificate) keyStore
                    .getCertificate(AgentConstants.SERVER_CA_CERT_ALIAS);
            this.serverPublicKey = serverCACert.getPublicKey();
            log.info(AgentConstants.LOG_APPENDER
                    + "Device has already been enrolled. Hence, loaded certificate information from device"
                    + " trust-store.");
        }
    } catch (UnrecoverableKeyException | NoSuchAlgorithmException | KeyStoreException e) {
        log.error(AgentConstants.LOG_APPENDER + "An error occurred whilst accessing the device KeyStore '"
                + AgentConstants.DEVICE_KEYSTORE + "' to ensure enrollment status.");
        log.error(AgentConstants.LOG_APPENDER + e);
        log.warn(AgentConstants.LOG_APPENDER + "Device will be re-enrolled.");
        this.isEnrolled = false;
    }
}

From source file:edu.vt.middleware.crypt.KeyStoreCli.java

/**
 * Exports a certificate or key pair from the keystore.
 *
 * @param  line  Parsed command line arguments container.
 *
 * @throws  Exception  On errors.//from  w w  w  .ja  v a2s. c o m
 */
protected void doExport(final CommandLine line) throws Exception {
    validateOptions(line);

    final KeyStore store = readKeyStore(line);
    final String alias = line.getOptionValue(OPT_ALIAS);
    boolean wroteData = false;
    if (line.hasOption(OPT_CERT)) {
        final File certFile = new File(line.getOptionValue(OPT_CERT));
        final Certificate[] certs = store.getCertificateChain(alias);
        if (certs != null) {
            if (certFile.getName().endsWith(PEM_SUFFIX)) {
                CryptWriter.writePemCertificates(certs, certFile);
            } else {
                CryptWriter.writeEncodedCertificates(certs, certFile);
            }
        } else {
            // Null cert chain indicates trusted cert entry
            // with single cert
            final Certificate cert = store.getCertificate(alias);
            if (certFile.getName().endsWith(PEM_SUFFIX)) {
                CryptWriter.writePemCertificate(cert, certFile);
            } else {
                CryptWriter.writeEncodedCertificate(cert, certFile);
            }
        }
        System.err.println("Wrote certificate to " + certFile);
        wroteData = true;
    }
    if (line.hasOption(OPT_KEY)) {
        final File keyFile = new File(line.getOptionValue(OPT_KEY));
        final PrivateKey key = (PrivateKey) store.getKey(alias, line.getOptionValue(OPT_PASS).toCharArray());
        if (keyFile.getName().endsWith(PEM_SUFFIX)) {
            CryptWriter.writePemKey(key, null, null, keyFile);
        } else {
            CryptWriter.writeEncodedKey(key, keyFile);
        }
        System.err.println("Wrote key to " + keyFile);
        wroteData = true;
    }
    if (!wroteData) {
        System.err.println("No data was written because neither -cert nor -key was specified.");
    }
}

From source file:org.wso2.carbon.identity.relyingparty.RelyingPartyData.java

/**
 * This method read parameters from web.xml. Step 1 : Read my private key Step 2 : Read the
 * token validation policy Step 3 : Read parameters that is needed perform token validation
 * if(promiscuous) ->read nothing else if(blackList) ->read the blacklist and key store details
 * else if (whiteList)->read the white-list and key store details
 */// www.  ja  va  2  s.  c o  m
private void loadData() throws IdentityException {

    ServerConfiguration serverConfig = null;
    KeyStore store = null;
    FileInputStream stream = null;

    serverConfig = ServerConfiguration.getInstance();
    String keyStore = serverConfig.getFirstProperty("Security.KeyStore.Location");
    String storeType = serverConfig.getFirstProperty("Security.KeyStore.Type");
    String storePass = serverConfig.getFirstProperty("Security.KeyStore.Password");
    String keyAlias = serverConfig.getFirstProperty("Security.KeyStore.KeyAlias");
    String keyPass = serverConfig.getFirstProperty("Security.KeyStore.KeyPassword");

    issuerPolicy = IdentityUtil.getProperty(ServerConfig.ISSUER_POLICY);

    if (issuerPolicy == null || issuerPolicy.trim().length() == 0) {
        // Set the default value
        issuerPolicy = TokenVerifierConstants.SELF_AND_MANGED;
    } else if (!(issuerPolicy.equals(TokenVerifierConstants.SELF_ONLY)
            || issuerPolicy.equals(TokenVerifierConstants.MANGED_ONLY)
            || issuerPolicy.equals(TokenVerifierConstants.SELF_AND_MANGED))) {
        throw new IdentityException("Invalid Issuer Policy!");
    }

    try {
        store = KeyStore.getInstance(storeType);
        stream = new FileInputStream(keyStore);
        store.load(stream, storePass.toCharArray());
        privateKey = (PrivateKey) store.getKey(keyAlias, keyPass.toCharArray());
        trustStore = store;
    } catch (Exception e) {
        throw new IdentityException("Cannot load the private key", e);
    } finally {
        if (stream != null) {
            try {
                stream.close();
            } catch (IOException e) {
                log.error("Error while closing system keystore file", e);
            }
        }
    }

    // Step 2: Reading Token validate policy - Promiscuous/BlackList/WhiteList/CertValidate

    // Promiscuous - In this mode, all tokens that has a valid signature are allowed
    // CertValidate - In this mode, all tokens that has a valid signature by an IdP who has a
    // trusted certificate are allowed
    // WhiteList - First CertValidity checked and after that if the issuer
    // DN is in the white list, the token is allowed
    // BlackList - First CertValidity checked and after that if the issuer
    // DN is not listed in the BlackList, the token is allowed

    validatePolicy = IdentityUtil.getProperty(ServerConfig.TOKEN_VALIDATE_POLICY);

    if (validatePolicy == null || validatePolicy.trim().length() == 0) {
        validatePolicy = TokenVerifierConstants.CERT_VALIDATE;
    }

    // Step 3: Reading parameters of each policy

    if (validatePolicy.equals(TokenVerifierConstants.BLACK_LIST)) {
        String value = IdentityUtil.getProperty(ServerConfig.BLACK_LIST);
        if (value != null) {
            blackList = readBlackWhiteList(value);
        }
    } else if (validatePolicy.equals(TokenVerifierConstants.WHITE_LIST)) {
        String value = IdentityUtil.getProperty(ServerConfig.WHITE_LIST);
        if (value != null) {
            whiteList = readBlackWhiteList(value);
        }
    }

    if (validatePolicy.equals(TokenVerifierConstants.WHITE_LIST)
            || validatePolicy.equals(TokenVerifierConstants.BLACK_LIST)
            || validatePolicy.equals(TokenVerifierConstants.CERT_VALIDATE)) {

        String javaHome = null;
        String defaultKeyStore = null;
        FileInputStream fileStream = null;
        KeyStore sysKS = null;

        String defaultStorePass = IdentityUtil.getProperty(ServerConfig.SYSTEM_KEY_STORE_PASS);
        if (defaultStorePass == null) {
            // assume that it hasn't been changed
            defaultStorePass = "changeit";
        }

        javaHome = System.getenv("JAVA_HOME");

        if (javaHome == null) {
            throw new IdentityException("Cannot find JAVA_HOME");
        }

        defaultKeyStore = IdentityUtil.getProperty(ServerConfig.SYSTEM_KEY_STORE);

        if (defaultKeyStore != null && defaultKeyStore.trim().length() > 0) {
            defaultKeyStore = javaHome + defaultKeyStore;
        } else {
            if (File.separator.equals("/")) {
                defaultKeyStore = javaHome + TokenVerifierConstants.CACERTS_STORE_UNIX;
            } else {
                defaultKeyStore = javaHome + TokenVerifierConstants.CACERTS_STORE_WIN;
            }
        }

        try {
            fileStream = new FileInputStream(defaultKeyStore);
            sysKS = KeyStore.getInstance("JKS");
            sysKS.load(fileStream, defaultStorePass.toCharArray());
            this.systemStore = sysKS;
        } catch (RuntimeException e) {
            throw e;
        } catch (Exception e) {
            throw new IdentityException("Cannot load system key store");
        } finally {
            if (fileStream != null) {
                try {
                    fileStream.close();
                } catch (IOException e) {
                    log.error("Error while closing system keystore file", e);
                }
            }
        }
    }
}

From source file:org.wildfly.security.x500.cert.acme.AcmeClientSpiTest.java

@BeforeClass
public static void setUp() throws Exception {
    mockRetryAfter(); // no need to sleep in between polling attempts during testing
    KeyStore keyStore = KeyStore.getInstance("jks");
    try (InputStream is = AcmeClientSpiTest.class.getResourceAsStream(KEYSTORE)) {
        keyStore.load(is, KEYSTORE_PASSWORD);
    }/*from   ww  w . j  a  v a 2 s.co m*/

    int numAliases = keyStore.size();
    aliasToCertificateMap = new HashMap<>(numAliases);
    aliasToPrivateKeyMap = new HashMap<>(numAliases);
    final Enumeration<String> aliases = keyStore.aliases();
    while (aliases.hasMoreElements()) {
        String alias = aliases.nextElement();
        aliasToCertificateMap.put(alias, (X509Certificate) keyStore.getCertificate(alias));
        aliasToPrivateKeyMap.put(alias, (PrivateKey) keyStore.getKey(alias, KEYSTORE_PASSWORD));
    }
    server = new ClientAndServer(4001);
    client = new MockWebServer();
    client.start(5002); // this is the port our mock Let's Encrypt server will use to access the client
}

From source file:com.osbitools.ws.shared.auth.SamlSecurityProvider.java

@Override
public void init(ServletContext ctx, Properties properties) throws RuntimeException {
    super.init(ctx, properties);

    // Read keystore password
    String kpwd = properties.getProperty("keystore.pwd");
    if (Utils.isEmpty(kpwd))
        throw new RuntimeException("Keystore password is not found");
    byte[] bkpwd = Base64.decode(kpwd);

    // Read default service provider name which is same as servlet context
    String cpath = properties.getProperty("cpath").substring(1);

    // Read actual service provider name (if defined)
    _sname = properties.getProperty("saml." + cpath + ".sp_name", cpath);

    // Read service location
    _sloc = properties.getProperty("saml." + cpath + ".sp_loc");

    // Read service provider keystore password
    String spwd = properties.getProperty("keystore." + cpath + ".pwd");
    if (Utils.isEmpty(spwd))
        throw new RuntimeException("Keystore password for '" + cpath + "' key is not found");
    byte[] bspwd = Base64.decode(spwd);

    // Initialize internal variables
    try {//from  w ww  .  ja va  2  s.  c o  m
        DefaultBootstrap.bootstrap();
    } catch (ConfigurationException e) {
        throw new RuntimeException(e);
    }

    _bf = Configuration.getBuilderFactory();

    // Read servlet config directory
    String cdir = properties.getProperty("cdir");

    // Load service provider certificates
    KeyStore ks;
    try {
        ks = KeyStore.getInstance(KeyStore.getDefaultType());
    } catch (KeyStoreException e) {
        throw new RuntimeException(e);
    }

    FileInputStream fis;
    try {
        fis = new FileInputStream(cdir + File.separator + Constants.KEYSTORE_FILE);
    } catch (FileNotFoundException e) {
        throw new RuntimeException(e);
    }

    try {
        ks.load(fis, new String(bkpwd).toCharArray());
    } catch (NoSuchAlgorithmException | CertificateException | IOException e) {
        throw new RuntimeException(e);
    }

    // Remember private key for sign request
    try {
        _key = (PrivateKey) ks.getKey(cpath, new String(bspwd).toCharArray());
    } catch (UnrecoverableKeyException | KeyStoreException | NoSuchAlgorithmException e) {
        throw new RuntimeException("Error loading key for alias '" + cpath + "'. ERROR: " + e.getMessage());
    }

    if (_key == null)
        throw new RuntimeException("Key for alias '" + cpath + "' not found in keystore ");

    try {
        fis.close();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    Map<String, String> passwordMap = new HashMap<String, String>();
    passwordMap.put(cpath, new String(bspwd));
    KeyStoreCredentialResolver resolver = new KeyStoreCredentialResolver(ks, passwordMap);

    Criteria criteria = new EntityIDCriteria(cpath);
    CriteriaSet criteriaSet = new CriteriaSet(criteria);

    try {
        _scred = (X509Credential) resolver.resolveSingle(criteriaSet);
    } catch (SecurityException e) {
        throw new RuntimeException(e);
    }

    // Load IDP Metadata
    // Get parser pool manager
    _pmgr = new BasicParserPool();
    _pmgr.setNamespaceAware(true);

    // Parse metadata file
    InputStream in;
    try {
        in = new FileInputStream(cdir + File.separator + Constants.IDP_METADATA_FILE);
    } catch (FileNotFoundException e) {
        throw new RuntimeException(e);
    }

    Document doc;
    try {
        doc = _pmgr.parse(in);
    } catch (XMLParserException e) {
        throw new RuntimeException(e);
    }

    try {
        in.close();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    Element root = doc.getDocumentElement();

    UnmarshallerFactory unmarshallerFactory = Configuration.getUnmarshallerFactory();
    Unmarshaller unmarshaller = unmarshallerFactory.getUnmarshaller(root);

    EntityDescriptor eds;
    try {
        eds = (EntityDescriptor) unmarshaller.unmarshall(root);
    } catch (UnmarshallingException e) {
        throw new RuntimeException(e);
    }
    _idp = eds.getEntityID();

    DOMMetadataProvider mp = new DOMMetadataProvider(root);
    mp.setRequireValidMetadata(true);
    // mp.setParserPool(new BasicParserPool());
    try {
        mp.initialize();
    } catch (MetadataProviderException e) {
        throw new RuntimeException(e);
    }

    MetadataCredentialResolverFactory crf = MetadataCredentialResolverFactory.getFactory();

    MetadataCredentialResolver cr = crf.getInstance(mp);

    // Look for signing key
    CriteriaSet cs = new CriteriaSet();
    cs.add((Criteria) new MetadataCriteria(IDPSSODescriptor.DEFAULT_ELEMENT_NAME, SAMLConstants.SAML20P_NS));
    cs.add(new EntityIDCriteria(_idp));
    cs.add(new UsageCriteria(UsageType.SIGNING));

    try {
        _cred = (X509Credential) cr.resolveSingle(cs);
    } catch (SecurityException e) {
        throw new RuntimeException(e);
    }

    if (_cred == null)
        throw new RuntimeException("Signing Key Descriptors " + "not found in IDP Entity Descriptor");

    IDPSSODescriptor idps = eds.getIDPSSODescriptor(SAMLConstants.SAML20P_NS);

    for (SingleSignOnService sss : idps.getSingleSignOnServices()) {
        if (sss.getBinding().equals(SAMLConstants.SAML2_POST_BINDING_URI)) {
            _login = sss.getLocation();
            break;
        }
    }

    if (_login == null)
        throw new RuntimeException("IDP SSO POST Redirecting " + "Location not found in IDP Entity Descriptor");

    // Get Single Logout Service
    for (SingleLogoutService slo : idps.getSingleLogoutServices()) {
        if (slo.getBinding().equals(SAMLConstants.SAML2_SOAP11_BINDING_URI))
            _logout = slo.getLocation();
    }

    if (_logout == null)
        throw new RuntimeException("IDP SLO SOAP " + "Location not found in IDP Entity Descriptor");
}

From source file:com.sun.identity.console.user.model.UMChangeUserPasswordModelImpl.java

public void changePwd(String userId, String oldPassword, String newPassword) throws AMConsoleException {
    String[] params = { userId, AMAdminConstants.ATTR_USER_OLD_PASSWORD };
    try {/*from  w  ww.j  av a  2  s. c o  m*/
        logEvent("ATTEMPT_MODIFY_IDENTITY_ATTRIBUTE_VALUE", params);
        AMIdentity amIdentity = IdUtils.getIdentity(getUserSSOToken(), userId);
        boolean verified = verifyOldPassword(amIdentity, userId, oldPassword.toCharArray());
        if (!verified) {
            String strError = "Authorized for password changed denied";
            String[] paramsEx = { userId, AMAdminConstants.ATTR_USER_OLD_PASSWORD, strError };
            logEvent("SSO_EXCEPTION_MODIFY_IDENTITY_ATTRIBUTE_VALUE", paramsEx);
            throw new AMConsoleException(strError);
        }
        Map passwordMap = new AMHashMap(2);
        Set set = new HashSet(2);
        set.add(newPassword);
        passwordMap.put(AMAdminConstants.ATTR_USER_PASSWORD, set);
        Set<String> attributeNames = new HashSet<String>();
        attributeNames.add(USERPKCS12_BINARY_ATTRNAME);
        Map<String, byte[][]> userPKCS12Map = amIdentity.getBinaryAttributes(attributeNames);
        if (userPKCS12Map != null && userPKCS12Map.get(USERPKCS12_BINARY_ATTRNAME) != null) {
            KeyStore keyStore = null;
            try {
                keyStore = KeyStore.getInstance(TOLVEN_CREDENTIAL_FORMAT_PKCS12);
            } catch (Exception e) {
                String strError = "Could not get an instance of KeyStore to create user KeyStore: "
                        + getErrorString(e);
                String[] paramsEx = { userId, AMAdminConstants.ATTR_USER_OLD_PASSWORD, strError };
                logEvent("SSO_EXCEPTION_MODIFY_IDENTITY_ATTRIBUTE_VALUE", paramsEx);
                throw new AMConsoleException(strError);
            }
            byte[][] oldUserPKCS12ByteArrs = (byte[][]) userPKCS12Map.get(USERPKCS12_BINARY_ATTRNAME);
            byte[] oldUserPKCS12 = oldUserPKCS12ByteArrs[0];
            ByteArrayInputStream bais = new ByteArrayInputStream(oldUserPKCS12);
            try {
                keyStore.load(bais, oldPassword.toCharArray());
            } catch (Exception e) {
                String strError = "Could not get user KeyStore using old password: " + getErrorString(e);
                String[] paramsEx = { userId, AMAdminConstants.ATTR_USER_OLD_PASSWORD, strError };
                logEvent("SSO_EXCEPTION_MODIFY_IDENTITY_ATTRIBUTE_VALUE", paramsEx);
                throw new AMConsoleException(strError);
            }
            ByteArrayOutputStream baos = null;
            try {
                String alias = keyStore.aliases().nextElement();
                PrivateKey privateKey = (PrivateKey) keyStore.getKey(alias, oldPassword.toCharArray());
                keyStore.setKeyEntry(alias, privateKey, newPassword.toCharArray(),
                        keyStore.getCertificateChain(alias));
                baos = new ByteArrayOutputStream();
            } catch (Exception e) {
                String strError = "Could not get Key from user KeyStore: " + getErrorString(e);
                String[] paramsEx = { userId, AMAdminConstants.ATTR_USER_OLD_PASSWORD, strError };
                logEvent("SSO_EXCEPTION_MODIFY_IDENTITY_ATTRIBUTE_VALUE", paramsEx);
                throw new AMConsoleException(strError);
            }
            try {
                keyStore.store(baos, newPassword.toCharArray());
            } catch (Exception e) {
                String strError = "Could not save user KeyStore: " + getErrorString(e);
                String[] paramsEx = { userId, AMAdminConstants.ATTR_USER_OLD_PASSWORD, strError };
                logEvent("SSO_EXCEPTION_MODIFY_IDENTITY_ATTRIBUTE_VALUE", paramsEx);
                throw new AMConsoleException(strError);
            }
            byte[] newUserPKCS12 = baos.toByteArray();
            byte[][] newUserPKCS12ByteArrs = new byte[1][];
            newUserPKCS12ByteArrs[0] = newUserPKCS12;
            Map<String, byte[][]> newUserPKCS12Map = newUserPKCS12Map = new HashMap<String, byte[][]>();
            newUserPKCS12Map.put(USERPKCS12_BINARY_ATTRNAME, newUserPKCS12ByteArrs);
            // Ensure that the following two lines are never out of sync (one would expect store() to be a transaction)
            amIdentity.setBinaryAttributes(newUserPKCS12Map);
            amIdentity.setAttributes(passwordMap);
            amIdentity.store();
        } else {
            amIdentity.setAttributes(passwordMap);
            amIdentity.store();
        }
        logEvent("SUCCEED_MODIFY_IDENTITY_ATTRIBUTE_VALUE", params);
    } catch (SSOException e) {
        String strError = getErrorString(e);
        String[] paramsEx = { userId, AMAdminConstants.ATTR_USER_OLD_PASSWORD, strError };
        logEvent("SSO_EXCEPTION_MODIFY_IDENTITY_ATTRIBUTE_VALUE", paramsEx);
        throw new AMConsoleException(strError);
    } catch (IdRepoException e) {
        String strError = getErrorString(e);
        String[] paramsEx = { userId, AMAdminConstants.ATTR_USER_OLD_PASSWORD, strError };
        logEvent("IDM_EXCEPTION_MODIFY_IDENTITY_ATTRIBUTE_VALUE", paramsEx);
        throw new AMConsoleException(strError);
    }
}