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.ejbca.core.model.ca.caadmin.extendedcaservices.CmsCAService.java

public CmsCAService(final HashMap<Object, Object> data) throws IllegalArgumentException {
    super(data);/*from  w  ww.ja va2s .co  m*/
    CryptoProviderTools.installBCProviderIfNotAvailable();
    loadData(data);
    if (this.data.get(KEYSTORE) != null) {
        // lookup keystore passwords      
        final String keystorepass = StringTools.passwordDecryption(EjbcaConfiguration.getCaCmsKeyStorePass(),
                "ca.cmskeystorepass");
        int status = ExtendedCAServiceInfo.STATUS_INACTIVE;
        try {
            if (log.isDebugEnabled()) {
                log.debug("Loading CMS keystore");
            }
            final KeyStore keystore = KeyStore.getInstance("PKCS12", "BC");
            keystore.load(
                    new ByteArrayInputStream(Base64.decode(((String) this.data.get(KEYSTORE)).getBytes())),
                    keystorepass.toCharArray());
            if (log.isDebugEnabled()) {
                log.debug("Finished loading CMS keystore");
            }
            String alias = PRIVATESIGNKEYALIAS;
            privKey = (PrivateKey) keystore.getKey(alias, null);
            if (privKey == null) {
                if (log.isDebugEnabled()) {
                    log.debug(
                            "privKey was null for alias " + alias + ", trying with " + OLDPRIVATESIGNKEYALIAS);
                }
                alias = OLDPRIVATESIGNKEYALIAS;
                privKey = (PrivateKey) keystore.getKey(alias, null);
            }
            // Due to a bug in Glassfish v1 (fixed in v2), we used to have to make sure all certificates in this 
            // Array were of SUNs own provider, using CertTools.SYSTEM_SECURITY_PROVIDER.
            // As of EJBCA 3.9.3 we decided that we don't have to support Glassfish v1 anymore.
            Collection<Certificate> coll = CertTools
                    .getCertCollectionFromArray(keystore.getCertificateChain(alias), null);
            this.certificatechain = new ArrayList<Certificate>(coll);
            status = getStatus();
        } catch (Exception e) {
            log.error(
                    "Could not load keystore or certificate for CA CMS service. Perhaps the password was changed? "
                            + e.getMessage(),
                    e);
        } finally {
            info = new CmsCAServiceInfo(status, getSubjectDN(), getSubjectAltName(),
                    (String) this.data.get(KEYSPEC), (String) this.data.get(KEYALGORITHM),
                    this.certificatechain);
        }
        data.put(EXTENDEDCASERVICETYPE, Integer.valueOf(ExtendedCAServiceTypes.TYPE_CMSEXTENDEDSERVICE));
    } else {
        if (log.isDebugEnabled()) {
            log.debug("KEYSTORE is null when creating CmsCAService");
        }
    }
}

From source file:org.kuali.kra.s2s.service.impl.S2SConnectorServiceBase.java

/**
 * This method is to confgiure KeyStore and Truststore for Grants.Gov webservice client
 * @param tlsConfig/*from  w ww . j  a  va2s.  c om*/
 * @param alias
 * @param mulitCampusEnabled
 * @throws S2SException
 */
protected void configureKeyStoreAndTrustStore(TLSClientParameters tlsConfig, String alias,
        boolean mulitCampusEnabled) throws S2SException {
    KeyStore keyStore = s2sCertificateReader.getKeyStore();
    KeyManagerFactory keyManagerFactory;
    try {
        keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        if (alias != null && mulitCampusEnabled) {
            KeyStore keyStoreAlias;
            keyStoreAlias = KeyStore.getInstance(s2sCertificateReader.getJksType());
            Certificate[] certificates = keyStore.getCertificateChain(alias);
            Key key = keyStore.getKey(alias,
                    s2SUtilService.getProperty(s2sCertificateReader.getKeyStorePassword()).toCharArray());
            keyStoreAlias.load(null, null);
            keyStoreAlias.setKeyEntry(alias, key,
                    s2SUtilService.getProperty(s2sCertificateReader.getKeyStorePassword()).toCharArray(),
                    certificates);
            keyManagerFactory.init(keyStoreAlias,
                    s2SUtilService.getProperty(s2sCertificateReader.getKeyStorePassword()).toCharArray());
        } else {
            keyManagerFactory.init(keyStore,
                    s2SUtilService.getProperty(s2sCertificateReader.getKeyStorePassword()).toCharArray());
        }
        KeyManager[] km = keyManagerFactory.getKeyManagers();
        tlsConfig.setKeyManagers(km);
        KeyStore trustStore = s2sCertificateReader.getTrustStore();
        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(trustStore);
        TrustManager[] tm = trustManagerFactory.getTrustManagers();
        tlsConfig.setTrustManagers(tm);
    } catch (NoSuchAlgorithmException e) {
        LOG.error(e);
        throw new S2SException(KeyConstants.ERROR_KEYSTORE_CONFIG, e.getMessage());
    } catch (KeyStoreException e) {
        LOG.error(e);
        throw new S2SException(KeyConstants.ERROR_KEYSTORE_CONFIG, e.getMessage());
    } catch (UnrecoverableKeyException e) {
        LOG.error(e);
        throw new S2SException(KeyConstants.ERROR_KEYSTORE_CONFIG, e.getMessage());
    } catch (CertificateException e) {
        LOG.error(e);
        throw new S2SException(KeyConstants.ERROR_KEYSTORE_CONFIG, e.getMessage());
    } catch (IOException e) {
        LOG.error(e);
        throw new S2SException(KeyConstants.ERROR_KEYSTORE_CONFIG, e.getMessage());
    }
}

From source file:org.wso2.carbon.mdm.mobileservices.windowspc.services.wstep.impl.CertificateEnrollmentServiceImpl.java

/**
 * Method for setting privateKey and rootCACertificate variables.
 *
 * @throws KeyStoreGenerationException/*from w  w w . j  av a2 s  . c  om*/
 * @throws org.wso2.carbon.mdm.mobileservices.windows.common.exceptions
 * .XMLFileOperationException
 * @throws CertificateGenerationException
 */
public void setRootCertAndKey(String storePassword, String keyPassword)
        throws KeyStoreGenerationException, XMLFileOperationException, CertificateGenerationException {

    File JKSFile = new File(getClass().getClassLoader()
            .getResource(Constants.CertificateEnrollment.WSO2_MDM_JKS_FILE).getFile());
    String JKSFilePath = JKSFile.getPath();
    KeyStore securityJKS;
    try {
        securityJKS = KeyStoreGenerator.getKeyStore();
    } catch (KeyStoreGenerationException e) {
        throw new KeyStoreGenerationException("Cannot retrieve the MDM key store.", e);
    }

    try {
        KeyStoreGenerator.loadToStore(securityJKS, storePassword.toCharArray(), JKSFilePath);
    } catch (KeyStoreGenerationException e) {
        throw new KeyStoreGenerationException("Cannot load the MDM key store.", e);
    }

    PrivateKey CAPrivateKey;
    try {
        CAPrivateKey = (PrivateKey) securityJKS.getKey(Constants.CertificateEnrollment.CA_CERT,
                keyPassword.toCharArray());
    } catch (KeyStoreException e) {
        throw new CertificateGenerationException("Cannot generate private key due to Key store error.", e);
    } catch (NoSuchAlgorithmException e) {
        throw new CertificateGenerationException(
                "Requested cryptographic algorithm is not available in the environment.", e);
    } catch (UnrecoverableKeyException e) {
        throw new CertificateGenerationException("Cannot recover private key.", e);
    }

    privateKey = CAPrivateKey;
    Certificate CACertificate;
    try {
        CACertificate = securityJKS.getCertificate(Constants.CertificateEnrollment.CA_CERT);
    } catch (KeyStoreException e) {
        throw new KeyStoreGenerationException("Keystore cannot be accessed.", e);
    }
    CertificateFactory certificateFactory;

    try {
        certificateFactory = CertificateFactory.getInstance(Constants.CertificateEnrollment.X_509);
    } catch (CertificateException e) {
        throw new CertificateGenerationException("Cannot initiate certificate factory.", e);
    }

    ByteArrayInputStream byteArrayInputStream;
    try {
        byteArrayInputStream = new ByteArrayInputStream(CACertificate.getEncoded());
    } catch (CertificateEncodingException e) {
        throw new CertificateGenerationException("CA certificate cannot be encoded.", e);
    }

    X509Certificate X509CACertificate;
    try {
        X509CACertificate = (X509Certificate) certificateFactory.generateCertificate(byteArrayInputStream);
    } catch (CertificateException e) {
        throw new CertificateGenerationException("X509 CA certificate cannot be generated.", e);
    }
    rootCACertificate = X509CACertificate;
}

From source file:com.t2tierp.controller.nfe.StatusServico.java

public String verificaStatusServico(KeyStore ks, String alias, char[] senha) {
    try {//ww  w  .j a  v  a 2  s  .c o  m
        String codigoUf = "52";
        String ambiente = "2";
        String versaoDados = "3.10";
        String url = "https://homolog.sefaz.go.gov.br/nfe/services/v2/NfeStatusServico2?wsdl";

        //cria o xml de requisicao
        String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<consStatServ versao=\"" + versaoDados
                + "\" xmlns=\"http://www.portalfiscal.inf.br/nfe\">" + "<tpAmb>" + ambiente + "</tpAmb>"
                + "<cUF>" + codigoUf + "</cUF>" + "<xServ>STATUS</xServ>" + "</consStatServ>";

        //busca os dados do certificado digital
        X509Certificate certificate = (X509Certificate) ks.getCertificate(alias);
        PrivateKey privatekey = (PrivateKey) ks.getKey(alias, senha);
        SocketFactoryDinamico socketFactory = new SocketFactoryDinamico(certificate, privatekey);
        //arquivo que contm a cadeia de certificados do servio a ser consumido
        socketFactory
                .setFileCacerts(this.getClass().getResourceAsStream("/br/inf/portalfiscal/nfe/jssecacerts"));

        //define o protocolo a ser utilizado na conexao
        Protocol protocol = new Protocol("https", socketFactory, 443);
        Protocol.registerProtocol("https", protocol);

        //cria os dados da mensagem
        OMElement omeElement = AXIOMUtil.stringToOM(xml);
        NfeStatusServico2Stub.NfeDadosMsg nfeDadosMsg = new NfeStatusServico2Stub.NfeDadosMsg();
        nfeDadosMsg.setExtraElement(omeElement);

        //define os dados do cabecalho da mensagem
        NfeStatusServico2Stub.NfeCabecMsg nfeCabecMsg = new NfeStatusServico2Stub.NfeCabecMsg();
        nfeCabecMsg.setCUF(codigoUf);
        nfeCabecMsg.setVersaoDados(versaoDados);
        NfeStatusServico2Stub.NfeCabecMsgE nfeCabecMsgE = new NfeStatusServico2Stub.NfeCabecMsgE();
        nfeCabecMsgE.setNfeCabecMsg(nfeCabecMsg);

        //cria o servico
        NfeStatusServico2Stub stub = new NfeStatusServico2Stub(url);

        //busca o resutado
        NfeStatusServico2Stub.NfeStatusServicoNF2Result result = stub.nfeStatusServicoNF2(nfeDadosMsg,
                nfeCabecMsgE);

        //processa o resultado
        ByteArrayInputStream in = new ByteArrayInputStream(
                result.getExtraElement().toString().getBytes("UTF-8"));

        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        Document doc = dbf.newDocumentBuilder().parse(in);

        NodeList nodeList = doc.getDocumentElement().getElementsByTagName("xMotivo");

        String retorno = "Status: ";
        for (int i = 0; i < nodeList.getLength(); i++) {
            Element element = (Element) nodeList.item(i);
            retorno += element.getTextContent();
        }

        return retorno;

    } catch (Exception e) {
        e.printStackTrace();
    }
    return "Erro ao consultar o status do servio!";
}

From source file:org.codice.ddf.security.certificate.keystore.editor.KeystoreEditor.java

private synchronized void addToStore(String alias, String keyPassword, String storePassword, String data,
        String type, String fileName, String path, String storepass, KeyStore store)
        throws KeystoreEditorException {
    OutputStream fos = null;//  ww  w  .j  a va2  s. c  om
    try (InputStream inputStream = new ByteArrayInputStream(Base64.getDecoder().decode(data))) {
        if (StringUtils.isBlank(alias)) {
            throw new IllegalArgumentException("Alias cannot be null.");
        }
        Path storeFile = Paths.get(path);
        //check the two most common key/cert stores first (pkcs12 and jks)
        if (PKCS12_TYPE.equals(type) || StringUtils.endsWithIgnoreCase(fileName, ".p12")) {
            //priv key + cert chain
            KeyStore pkcs12Store = KeyStore.getInstance("PKCS12");
            pkcs12Store.load(inputStream, storePassword.toCharArray());
            Certificate[] chain = pkcs12Store.getCertificateChain(alias);
            Key key = pkcs12Store.getKey(alias, keyPassword.toCharArray());
            if (key != null) {
                store.setKeyEntry(alias, key, keyPassword.toCharArray(), chain);
                fos = Files.newOutputStream(storeFile);
                store.store(fos, storepass.toCharArray());
            }
        } else if (JKS_TYPE.equals(type) || StringUtils.endsWithIgnoreCase(fileName, ".jks")) {
            //java keystore file
            KeyStore jks = KeyStore.getInstance("jks");
            jks.load(inputStream, storePassword.toCharArray());
            Enumeration<String> aliases = jks.aliases();

            //we are going to store all entries from the jks regardless of the passed in alias
            while (aliases.hasMoreElements()) {
                String jksAlias = aliases.nextElement();

                if (jks.isKeyEntry(jksAlias)) {
                    Key key = jks.getKey(jksAlias, keyPassword.toCharArray());
                    Certificate[] certificateChain = jks.getCertificateChain(jksAlias);
                    store.setKeyEntry(jksAlias, key, keyPassword.toCharArray(), certificateChain);
                } else {
                    Certificate certificate = jks.getCertificate(jksAlias);
                    store.setCertificateEntry(jksAlias, certificate);
                }
            }

            fos = Files.newOutputStream(storeFile);
            store.store(fos, storepass.toCharArray());
            //need to parse der separately from pem, der has the same mime type but is binary hence checking both
        } else if (DER_TYPE.equals(type) && StringUtils.endsWithIgnoreCase(fileName, ".der")) {
            ASN1InputStream asn1InputStream = new ASN1InputStream(inputStream);
            ASN1Primitive asn1Primitive = asn1InputStream.readObject();
            X509CertificateHolder x509CertificateHolder = new X509CertificateHolder(asn1Primitive.getEncoded());
            CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509", "BC");
            Certificate certificate = certificateFactory
                    .generateCertificate(new ByteArrayInputStream(x509CertificateHolder.getEncoded()));
            X500Name x500name = new JcaX509CertificateHolder((X509Certificate) certificate).getSubject();
            RDN cn = x500name.getRDNs(BCStyle.CN)[0];
            String cnStr = IETFUtils.valueToString(cn.getFirst().getValue());
            if (!store.isCertificateEntry(cnStr) && !store.isKeyEntry(cnStr)) {
                store.setCertificateEntry(cnStr, certificate);
            }
            store.setCertificateEntry(alias, certificate);
            fos = Files.newOutputStream(storeFile);
            store.store(fos, storepass.toCharArray());
            //if it isn't one of the stores we support, it might be a key or cert by itself
        } else if (isPemParsable(type, fileName)) {
            //This is the catch all case for PEM, P7B, etc. with common file extensions if the mime type isn't read correctly in the browser
            Reader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
            PEMParser pemParser = new PEMParser(reader);
            Object object;
            boolean setEntry = false;
            while ((object = pemParser.readObject()) != null) {
                if (object instanceof PEMEncryptedKeyPair || object instanceof PEMKeyPair) {
                    PEMKeyPair pemKeyPair;
                    if (object instanceof PEMEncryptedKeyPair) {
                        PEMEncryptedKeyPair pemEncryptedKeyPairKeyPair = (PEMEncryptedKeyPair) object;
                        JcePEMDecryptorProviderBuilder jcePEMDecryptorProviderBuilder = new JcePEMDecryptorProviderBuilder();
                        pemKeyPair = pemEncryptedKeyPairKeyPair.decryptKeyPair(
                                jcePEMDecryptorProviderBuilder.build(keyPassword.toCharArray()));
                    } else {
                        pemKeyPair = (PEMKeyPair) object;
                    }

                    KeyPair keyPair = new JcaPEMKeyConverter().setProvider("BC").getKeyPair(pemKeyPair);
                    PrivateKey privateKey = keyPair.getPrivate();
                    Certificate[] chain = store.getCertificateChain(alias);
                    if (chain == null) {
                        chain = buildCertChain(alias, store);
                    }
                    store.setKeyEntry(alias, privateKey, keyPassword.toCharArray(), chain);
                    setEntry = true;
                } else if (object instanceof X509CertificateHolder) {
                    X509CertificateHolder x509CertificateHolder = (X509CertificateHolder) object;
                    CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509", "BC");
                    Certificate certificate = certificateFactory
                            .generateCertificate(new ByteArrayInputStream(x509CertificateHolder.getEncoded()));
                    X500Name x500name = new JcaX509CertificateHolder((X509Certificate) certificate)
                            .getSubject();
                    RDN cn = x500name.getRDNs(BCStyle.CN)[0];
                    String cnStr = IETFUtils.valueToString(cn.getFirst().getValue());
                    if (!store.isCertificateEntry(cnStr) && !store.isKeyEntry(cnStr)) {
                        store.setCertificateEntry(cnStr, certificate);
                    }
                    store.setCertificateEntry(alias, certificate);
                    setEntry = true;
                } else if (object instanceof ContentInfo) {
                    ContentInfo contentInfo = (ContentInfo) object;
                    if (contentInfo.getContentType().equals(CMSObjectIdentifiers.envelopedData)) {
                        CMSEnvelopedData cmsEnvelopedData = new CMSEnvelopedData(contentInfo);
                        OriginatorInfo originatorInfo = cmsEnvelopedData.getOriginatorInfo().toASN1Structure();
                        ASN1Set certificates = originatorInfo.getCertificates();
                        setEntry = importASN1CertificatesToStore(store, setEntry, certificates);
                    } else if (contentInfo.getContentType().equals(CMSObjectIdentifiers.signedData)) {
                        SignedData signedData = SignedData.getInstance(contentInfo.getContent());
                        ASN1Set certificates = signedData.getCertificates();
                        setEntry = importASN1CertificatesToStore(store, setEntry, certificates);
                    }
                } else if (object instanceof PKCS8EncryptedPrivateKeyInfo) {
                    PKCS8EncryptedPrivateKeyInfo pkcs8EncryptedPrivateKeyInfo = (PKCS8EncryptedPrivateKeyInfo) object;
                    Certificate[] chain = store.getCertificateChain(alias);
                    if (chain == null) {
                        chain = buildCertChain(alias, store);
                    }
                    try {
                        store.setKeyEntry(alias, pkcs8EncryptedPrivateKeyInfo.getEncoded(), chain);
                        setEntry = true;
                    } catch (KeyStoreException keyEx) {
                        try {
                            PKCS8Key pkcs8Key = new PKCS8Key(pkcs8EncryptedPrivateKeyInfo.getEncoded(),
                                    keyPassword.toCharArray());
                            store.setKeyEntry(alias, pkcs8Key.getPrivateKey(), keyPassword.toCharArray(),
                                    chain);
                            setEntry = true;
                        } catch (GeneralSecurityException e) {
                            LOGGER.error(
                                    "Unable to add PKCS8 key to keystore with secondary method. Throwing original exception.",
                                    e);
                            throw keyEx;
                        }
                    }
                }
            }
            if (setEntry) {
                fos = Files.newOutputStream(storeFile);
                store.store(fos, storepass.toCharArray());
            }
        }
    } catch (Exception e) {
        LOGGER.error("Unable to add entry {} to store", alias, e);
        throw new KeystoreEditorException("Unable to add entry " + alias + " to store", e);
    } finally {
        if (fos != null) {
            try {
                fos.close();
            } catch (IOException ignore) {
            }
        }
    }
    init();
}

From source file:org.guanxi.sp.engine.form.RegisterGuardFormController.java

/**
 * Creates an authenticated certificate chain for the specified X509 name
 *
 * @param x509DN X509 name to for which to create a certificate chain
 * @param keyType The type of the key, e.g. "RSA", "DSA"
 * @return Returns a CABean instance encapsulating certificate chain and key information
 * or null if an error occurred/* www  .  ja  va  2s .  c om*/
 */
private CABean createSignedCertificateChain(String x509DN, String keyType) {
    try {
        // Create a public/private keypair...
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance(keyType);
        keyGen.initialize(1024, new SecureRandom());
        KeyPair keypair = keyGen.generateKeyPair();
        PrivateKey clientPrivateKey = keypair.getPrivate();
        PublicKey clientPublicKey = keypair.getPublic();

        // ...and a CSR from them...
        PKCS10CertificationRequest csr = generateRequest(x509DN, clientPublicKey, clientPrivateKey, keyType);

        // ...sign it
        KeyStore rootKS = loadRootKeyStore();
        X509Certificate rootCert = (X509Certificate) rootKS.getCertificate(rootCAKeystoreAlias);
        if (rootCert == null) {
            logger.error("Can't get root certificate from CA keystore");
            return null;
        }
        PrivateKey rootPrivKey = (PrivateKey) rootKS.getKey(rootCAKeystoreAlias,
                rootCAKeystorePassword.toCharArray());
        X509Certificate[] signedChain = createSignedCert(rootCert, rootPrivKey, csr, keyType);

        //...package up the result...
        CABean caBean = new CABean();
        caBean.setChain(signedChain);
        caBean.setCSRPrivateKey(clientPrivateKey);
        caBean.setSubjectDN(x509DN);

        // ...and send it back
        return caBean;
    } catch (Exception e) {
        logger.error(e);
        return null;
    }
}

From source file:org.digidoc4j.impl.BDocContainerTest.java

static byte[] getExternalSignature(Container container, final X509Certificate signerCert,
        SignedInfo prepareSigningSignature, final DigestAlgorithm digestAlgorithm) {
    Signer externalSigner = new ExternalSigner(signerCert) {
        @Override/*from  w  w  w.j  av a  2 s  .com*/
        public byte[] sign(Container container, byte[] dataToSign) {
            try {
                KeyStore keyStore = KeyStore.getInstance("PKCS12");
                try (FileInputStream stream = new FileInputStream("testFiles/signout.p12")) {
                    keyStore.load(stream, "test".toCharArray());
                }
                PrivateKey privateKey = (PrivateKey) keyStore.getKey("1", "test".toCharArray());
                final String javaSignatureAlgorithm = "NONEwith" + privateKey.getAlgorithm();

                return DSSUtils.encrypt(javaSignatureAlgorithm, privateKey, addPadding(dataToSign));
            } catch (Exception e) {
                throw new DigiDoc4JException("Loading private key failed");
            }
        }

        private byte[] addPadding(byte[] digest) {
            byte[] signatureDigest;
            switch (digestAlgorithm) {
            case SHA512:
                signatureDigest = Constants.SHA512_DIGEST_INFO_PREFIX;
                break;
            case SHA256:
                signatureDigest = Constants.SHA256_DIGEST_INFO_PREFIX;
                break;
            default:
                throw new NotYetImplementedException();
            }
            return ArrayUtils.addAll(signatureDigest, digest);
        }
    };

    return externalSigner.sign(container, prepareSigningSignature.getDigest());
}

From source file:org.wildfly.security.sasl.entity.EntityTest.java

@Test
public void testMutualAuthenticationWithDNSInCNField() throws Exception {
    // Although specifying a DNS name using the Common Name field has been deprecated, it is
    // still used in practice (e.g., see http://tools.ietf.org/html/rfc2818). This test makes
    // sure that general name matching during authentication still works in this case.
    final SaslClientFactory clientFactory = obtainSaslClientFactory(EntitySaslClientFactory.class);
    assertNotNull(clientFactory);//from  w w  w. j a v  a2s  . com

    final KeyStore keyStore = loadKeyStore(serverKeyStore);
    final Certificate[] certificateChain = keyStore.getCertificateChain("dnsInCNServer");
    final SaslServer saslServer = createSaslServer(SaslMechanismInformation.Names.IEC_ISO_9798_M_DSA_SHA1,
            "testserver2.example.com", serverTrustStore,
            (PrivateKey) keyStore.getKey("dnsInCNServer", KEYSTORE_PASSWORD),
            Arrays.copyOf(certificateChain, certificateChain.length, X509Certificate[].class));

    final String[] mechanisms = new String[] { SaslMechanismInformation.Names.IEC_ISO_9798_M_DSA_SHA1 };
    CallbackHandler cbh = createClientCallbackHandler(mechanisms, clientKeyStore, "dnsInCNClient",
            KEYSTORE_PASSWORD, getX509TrustManager(clientTrustStore));
    final SaslClient saslClient = clientFactory.createSaslClient(mechanisms, null, "test",
            "testserver2.example.com", Collections.<String, Object>emptyMap(), cbh);
    assertFalse(saslServer.isComplete());
    assertFalse(saslClient.isComplete());

    byte[] message = saslServer.evaluateResponse(new byte[0]);
    assertFalse(saslServer.isComplete());
    assertFalse(saslClient.isComplete());

    message = saslClient.evaluateChallenge(message);
    assertFalse(saslServer.isComplete());
    assertFalse(saslClient.isComplete());

    message = saslServer.evaluateResponse(message);
    assertNotNull(message);

    message = saslClient.evaluateChallenge(message);
    assertNull(message);
    assertTrue(saslClient.isComplete());
    assertTrue(saslServer.isComplete());
    assertEquals("cn=testclient2.example.com,ou=jboss,o=red hat,l=raleigh,st=north carolina,c=us",
            saslServer.getAuthorizationID());
}

From source file:org.codice.ddf.admin.insecure.defaults.service.KeystoreValidator.java

private void validateKeyPasswords(KeyStore keystore) {
    try {/*from   w w w .j ava  2s.c  o m*/
        Enumeration<String> aliases = keystore.aliases();
        while (aliases.hasMoreElements()) {
            String alias = (String) aliases.nextElement();
            if (keystore.entryInstanceOf(alias, KeyStore.PrivateKeyEntry.class)
                    || keystore.entryInstanceOf(alias, KeyStore.SecretKeyEntry.class)) {
                if (StringUtils.isNotBlank(defaultKeyPassword)) {
                    // See if we can access the key using the default key password. If we
                    // cannot, we
                    // know that we are using a non-default password.
                    Key key = keystore.getKey(alias, defaultKeyPassword.toCharArray());
                    if (key != null) {
                        alerts.add(new Alert(Level.WARN, String.format(DEFAULT_KEY_PASSWORD_USED_MSG, alias,
                                keystorePath, defaultKeyPassword)));
                    }
                } else {
                    alerts.add(new Alert(Level.WARN, String.format(GENERIC_INSECURE_DEFAULTS_MSG, keystorePath)
                            + "No key password provided."));
                }
            }
        }
    } catch (UnrecoverableKeyException e) {
        // Key is not using default key password.
    } catch (KeyStoreException | NoSuchAlgorithmException e) {
        LOGGER.warn(String.format(GENERIC_INSECURE_DEFAULTS_MSG, keystorePath), e);
        alerts.add(new Alert(Level.WARN,
                String.format(GENERIC_INSECURE_DEFAULTS_MSG, keystorePath) + e.getMessage() + "."));
    }
}