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:be.agiv.security.AGIVSecurity.java

/**
 * Constructor for X509 credentials. The certificate and corresponding
 * private key are loaded from a PKCS#12 keystore file.
 * //ww  w  . j a  v a2 s. c  o m
 * @param ipStsLocation
 *            the location of the IP-STS WS-Trust web service.
 * @param rStsLocation
 *            the location of the R-STS WS-Trust web service.
 * @param rStsRealm
 *            the AGIV R-STS realm.
 * @param pkcs12File
 *            the PKCS#12 keystore file.
 * @param pkcs12Password
 *            the PKCS#12 keystore password.
 * @throws SecurityException
 *             gets thrown in case of a PKCS#12 keystore error.
 * @see AGIVSecurity#AGIVSecurity(String, String, X509Certificate,
 *      PrivateKey)
 */
public AGIVSecurity(String ipStsLocation, String rStsLocation, String rStsRealm, File pkcs12File,
        String pkcs12Password) throws SecurityException {
    this.ipStsLocation = ipStsLocation;
    this.rStsLocation = rStsLocation;
    this.rStsRealm = rStsRealm;
    this.username = null;
    this.password = null;

    InputStream pkcs12InputStream;
    try {
        pkcs12InputStream = new FileInputStream(pkcs12File);
    } catch (FileNotFoundException e) {
        throw new SecurityException("PKCS#12 file does not exist: " + pkcs12File.getAbsolutePath());
    }
    Provider sunJSSEProvider = Security.getProvider("SunJSSE");
    try {
        KeyStore keyStore;
        if (null != sunJSSEProvider) {
            // avoid older BouncyCastle implementations
            keyStore = KeyStore.getInstance("PKCS12", sunJSSEProvider);
        } else {
            keyStore = KeyStore.getInstance("PKCS12");
        }
        keyStore.load(pkcs12InputStream, pkcs12Password.toCharArray());
        Enumeration<String> aliases = keyStore.aliases();
        String alias = aliases.nextElement();
        this.certificate = (X509Certificate) keyStore.getCertificate(alias);
        this.privateKey = (PrivateKey) keyStore.getKey(alias, pkcs12Password.toCharArray());
    } catch (Exception e) {
        LOG.error("error loading PKCS#12 keystore: " + e.getMessage(), e);
        throw new SecurityException("error loading PKCS#12 certificate: " + e.getMessage(), e);
    }
    this.externalIpStsClient = null;
    this.secureConversationTokens = new ConcurrentHashMap<String, SecurityToken>();
    this.rStsSecurityTokens = new ConcurrentHashMap<String, SecurityToken>();
    this.stsListeners = new CopyOnWriteArrayList<STSListener>();
}

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

/**
 * Test method for {@link net.sf.taverna.t2.security.credentialmanager.impl.CredentialManagerImpl#exportKeyPair(java.lang.String, java.io.File, java.lang.String)}.
 * @throws CMException /*  w  w w  .  j a v a 2  s .c  o  m*/
 * @throws KeyStoreException 
 * @throws NoSuchAlgorithmException 
 * @throws UnrecoverableKeyException 
 */
@Test
public void testExportKeyPair()
        throws CMException, KeyStoreException, UnrecoverableKeyException, NoSuchAlgorithmException {
    String alias = credentialManager.addKeyPair(privateKey, privateKeyCertChain);
    File fileToExportTo = new File(credentialManagerDirectory, "test-export-key.p12");
    credentialManager.exportKeyPair(alias, fileToExportTo, privateKeyAndPKCS12KeystorePassword);
    assertTrue(fileToExportTo.exists());
    // Load it back from the file we just saved
    KeyStore ks = credentialManager.loadPKCS12Keystore(fileToExportTo, privateKeyAndPKCS12KeystorePassword);
    Enumeration<String> aliases = ks.aliases();
    Key newPrivateKey = null;
    Certificate[] newPrivateKeyCerts = null;
    while (aliases.hasMoreElements()) {
        // The test-private-key-cert.p12 file contains only one private key
        // and corresponding certificate entry
        alias = aliases.nextElement();
        if (ks.isKeyEntry(alias)) { // is it a (private) key entry?
            newPrivateKey = ks.getKey(alias, privateKeyAndPKCS12KeystorePassword.toCharArray());
            newPrivateKeyCerts = ks.getCertificateChain(alias);
            break;
        }
    }
    assertNotNull(newPrivateKey);
    assertNotNull(newPrivateKeyCerts);
    //assertTrue(Arrays.equals(newPrivateKey.getEncoded(), privateKey.getEncoded()));
    assertTrue(newPrivateKey.equals(privateKey));
    assertTrue(Arrays.equals(newPrivateKeyCerts, privateKeyCertChain));
}

From source file:ddf.test.itests.platform.TestSecurity.java

@Test
public void testAllowedCipherSuites() throws Exception {
    String[] supportedCipherSuites = { "TLS_DHE_RSA_WITH_AES_128_GCM_SHA256",
            "TLS_DHE_RSA_WITH_AES_128_CBC_SHA256", "TLS_DHE_RSA_WITH_AES_128_CBC_SHA",
            "TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256", "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256" };

    List<String> systemCipherSuites = Arrays.asList(System.getProperty("https.cipherSuites").split(","));
    assertThat("Missing a supported cipher suite", systemCipherSuites,
            equalTo(Arrays.asList(supportedCipherSuites)));

    // Used to filter out cipher's that don't use our current key algorithm
    KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
    keystore.load(new FileInputStream(KEY_STORE_PATH), "changeit".toCharArray());
    String keyAlgorithm = keystore.getKey("localhost", "changeit".toCharArray()).getAlgorithm();

    String url = SERVICE_ROOT.getUrl() + "/catalog/query?q=*&src=local";
    CredentialsProvider credentialsProvider = createBasicAuth("admin", "admin");
    for (String cipher : supportedCipherSuites) {
        if (cipher.contains("_" + keyAlgorithm + "_")) {
            HttpClient client = createHttpClient("TLSv1.2", new String[] { cipher }, credentialsProvider);
            assertBasicAuth(client, url, 200);
        }/*  ww  w.j  ava 2s.c om*/
    }
}

From source file:mitm.common.security.certificate.GenerateTestCertificates.java

private static void loadCA() throws Exception {
    KeyStore caKeyStore = securityFactory.createKeyStore("PKCS12");

    File file = new File("test/resources/testdata/keys/testCA.p12");

    FileInputStream input = new FileInputStream(file);

    caKeyStore.load(input, "test".toCharArray());

    rootCertificate = (X509Certificate) caKeyStore.getCertificate("root");
    caCertificate = (X509Certificate) caKeyStore.getCertificate("ca");
    caPrivateKey = (PrivateKey) caKeyStore.getKey("ca", null);

    assertNotNull(caCertificate);// ww w .  jav a  2 s  .c  o m
    assertNotNull(caPrivateKey);
}

From source file:org.votingsystem.web.ejb.SignatureBean.java

public void init() throws Exception {
    Properties properties = new Properties();
    URL res = Thread.currentThread().getContextClassLoader().getResource("KeyStore.properties");
    log.info("init - res: " + res.toURI());
    properties.load(res.openStream());/*from   w  w  w  .j  a  va 2 s . c  o m*/
    keyAlias = properties.getProperty("vs.signKeyAlias");
    password = properties.getProperty("vs.signKeyPassword");
    String keyStoreFileName = properties.getProperty("vs.keyStoreFile");
    res = Thread.currentThread().getContextClassLoader().getResource(keyStoreFileName);
    File keyStoreFile = FileUtils.getFileFromBytes(IOUtils.toByteArray(res.openStream()));
    signedMailGenerator = new SMIMESignedGeneratorVS(FileUtils.getBytesFromFile(keyStoreFile), keyAlias,
            password.toCharArray(), ContextVS.SIGN_MECHANISM);
    KeyStore keyStore = KeyStore.getInstance("JKS");
    keyStore.load(new FileInputStream(keyStoreFile), password.toCharArray());
    certChain = new ArrayList<>();
    for (java.security.cert.Certificate certificate : keyStore.getCertificateChain(keyAlias)) {
        checkAuthorityCertDB((X509Certificate) certificate);
        certChain.add((X509Certificate) certificate);
    }
    keyStorePEMCerts = CertUtils.getPEMEncoded(certChain);
    localServerCertSigner = (X509Certificate) keyStore.getCertificate(keyAlias);
    currencyAnchors = new HashSet<>();
    currencyAnchors.add(new TrustAnchor(localServerCertSigner, null));
    Query query = dao.getEM().createNamedQuery("findCertBySerialNumber").setParameter("serialNumber",
            localServerCertSigner.getSerialNumber().longValue());
    serverCertificateVS = dao.getSingleResult(CertificateVS.class, query);
    serverPrivateKey = (PrivateKey) keyStore.getKey(keyAlias, password.toCharArray());
    encryptor = new Encryptor(localServerCertSigner, serverPrivateKey);
    serverName = config.getServerName();
}

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

/**
 * Test method for {@link org.apache.taverna.security.credentialmanager.impl.CredentialManagerImpl#exportKeyPair(java.lang.String, java.io.File, java.lang.String)}.
 * @throws CMException /*from w  w w  . j  av a2 s .com*/
 * @throws KeyStoreException 
 * @throws NoSuchAlgorithmException 
 * @throws UnrecoverableKeyException 
 */
@Test
public void testExportKeyPair()
        throws CMException, KeyStoreException, UnrecoverableKeyException, NoSuchAlgorithmException {
    String alias = credentialManager.addKeyPair(privateKey, privateKeyCertChain);
    File fileToExportTo = new File(credentialManagerDirectory, "test-export-key.p12");
    credentialManager.exportKeyPair(alias, fileToExportTo.toPath(), privateKeyAndPKCS12KeystorePassword);
    assertTrue(fileToExportTo.exists());
    // Load it back from the file we just saved
    KeyStore ks = credentialManager.loadPKCS12Keystore(fileToExportTo.toPath(),
            privateKeyAndPKCS12KeystorePassword);
    Enumeration<String> aliases = ks.aliases();
    Key newPrivateKey = null;
    Certificate[] newPrivateKeyCerts = null;
    while (aliases.hasMoreElements()) {
        // The test-private-key-cert.p12 file contains only one private key
        // and corresponding certificate entry
        alias = aliases.nextElement();
        if (ks.isKeyEntry(alias)) { // is it a (private) key entry?
            newPrivateKey = ks.getKey(alias, privateKeyAndPKCS12KeystorePassword.toCharArray());
            newPrivateKeyCerts = ks.getCertificateChain(alias);
            break;
        }
    }
    assertNotNull(newPrivateKey);
    assertNotNull(newPrivateKeyCerts);
    //assertTrue(Arrays.equals(newPrivateKey.getEncoded(), privateKey.getEncoded()));
    assertTrue(newPrivateKey.equals(privateKey));
    assertTrue(Arrays.equals(newPrivateKeyCerts, privateKeyCertChain));
}

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

/**
 * Test method for {@link net.sf.taverna.t2.security.credentialmanager.impl.CredentialManagerImpl#loadPKCS12Keystore(java.io.File, java.lang.String)}.
 * @throws CMException // w ww  .  ja  v a 2  s .c  o m
 * @throws KeyStoreException 
 * @throws NoSuchAlgorithmException 
 * @throws UnrecoverableKeyException 
 */
@Test
public void testLoadPKCS12Keystore()
        throws CMException, KeyStoreException, UnrecoverableKeyException, NoSuchAlgorithmException {
    KeyStore pkcs12Keystore = credentialManager.loadPKCS12Keystore(new File(privateKeyFileURL.getPath()),
            privateKeyAndPKCS12KeystorePassword);

    Key privateKey2 = null;
    Certificate[] privateKeyCertChain2 = null;

    Enumeration<String> aliases = pkcs12Keystore.aliases();
    while (aliases.hasMoreElements()) {
        // The test-private-key-cert.p12 file contains only one private key
        // and corresponding certificate entry
        String alias = aliases.nextElement();
        if (pkcs12Keystore.isKeyEntry(alias)) { // is it a (private) key entry?
            privateKey2 = pkcs12Keystore.getKey(alias, privateKeyAndPKCS12KeystorePassword.toCharArray());
            privateKeyCertChain2 = pkcs12Keystore.getCertificateChain(alias);
            break;
        }
    }
    assertNotNull(privateKey2);
    assertNotNull(privateKeyCertChain2);
}

From source file:org.ejbca.extra.ra.ScepRAServlet.java

private void service(String operation, String message, String remoteAddr, HttpServletResponse response)
        throws IOException {
    try {/*  w  w w.java  2 s. c o m*/
        if ((operation == null) || (message == null)) {
            log.error("Got request missing operation and/or message parameters.");
            response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                    "Parameters 'operation' and 'message' must be supplied!");
            return;
        }
        log.debug("Got request '" + operation + "'");
        log.debug("Message: " + message);
        log.debug("Operation is : " + operation);

        String alias = scepraks.getAlias();
        log.debug("SCEP RA Keystore alias : " + alias);
        KeyStore raks = scepraks.getKeyStore();
        Certificate[] chain = raks.getCertificateChain(alias);
        X509Certificate cacert = null;
        if (chain.length > 1) {
            // This should absolutely be more than one!
            cacert = (X509Certificate) chain[1];
        } else {
            log.error(
                    "Certificate chain in RA keystore is only 1 certificate long! This is en error, because there should also be CA certificates.");
        }
        X509Certificate racert = (X509Certificate) raks.getCertificate(alias);
        String kspwd = ExtraConfiguration.instance()
                .getString(ExtraConfiguration.SCEPKEYSTOREPWD + keyStoreNumber);
        PrivateKey rapriv = (PrivateKey) raks.getKey(alias, kspwd.toCharArray());

        if (operation.equals("PKIOperation")) {
            byte[] scepmsg = Base64.decode(message.getBytes());

            // Read the message end get the cert, this also checks authorization
            boolean includeCACert = true;
            if (StringUtils.equals("0", getInitParameter("includeCACert"))) {
                includeCACert = false;
            }

            byte[] reply = null;
            ScepRequestMessage reqmsg = new ScepRequestMessage(scepmsg, includeCACert);
            String transId = reqmsg.getTransactionId();
            log.debug("Received a message of type: " + reqmsg.getMessageType());
            if (reqmsg.getMessageType() == ScepRequestMessage.SCEP_TYPE_GETCERTINITIAL) {
                log.info("Received a GetCertInitial message from host: " + remoteAddr);
                Message msg = null;
                try {
                    msg = msgHome.findByMessageId(transId);
                } catch (Exception e) {
                    // TODO: internal resources
                    log.info("Error looking for message with transId " + transId + " :", e);
                }
                if (msg != null) {
                    if (msg.getStatus().equals(Message.STATUS_PROCESSED)) {
                        log.debug("Request is processed with status: " + msg.getStatus());
                        SubMessages submessagesresp = msg.getSubMessages(null, null, null);
                        Iterator<ISubMessage> iter = submessagesresp.getSubMessages().iterator();
                        PKCS10Response resp = (PKCS10Response) iter.next();
                        // create proper ScepResponseMessage
                        IResponseMessage ret = reqmsg.createResponseMessage(
                                org.ejbca.core.protocol.scep.ScepResponseMessage.class, reqmsg, racert, rapriv,
                                cryptProvider);
                        ret.setCACert(cacert);
                        X509Certificate respCert = resp.getCertificate();
                        if (resp.isSuccessful() && (respCert != null)) {
                            ret.setCertificate(respCert);
                        } else {
                            ret.setStatus(ResponseStatus.FAILURE);
                            ret.setFailInfo(FailInfo.BAD_REQUEST);
                            String failText = resp.getFailInfo();
                            ret.setFailText(failText);
                        }
                        ret.create();
                        reply = ret.getResponseMessage();
                    } else {
                        log.debug("Request is not yet processed, status: " + msg.getStatus());
                        reply = createPendingResponseMessage(reqmsg, racert, rapriv, cryptProvider)
                                .getResponseMessage();
                        log.debug("Responding with pending response, still pending.");
                    }
                } else {
                    // User doesn't exist
                }
            } else {
                if (reqmsg.getMessageType() == ScepRequestMessage.SCEP_TYPE_PKCSREQ) {
                    log.debug("Received a PKCSReq message from host: " + remoteAddr);
                    // Decrypt the Scep message and extract the pkcs10 request
                    if (reqmsg.requireKeyInfo()) {
                        // scep encrypts message with the RAs certificate
                        reqmsg.setKeyInfo(racert, rapriv, cryptProvider);
                    }
                    // Verify the request
                    if (reqmsg.verify() == false) {
                        String msg = "POPO verification failed.";
                        log.error(msg);
                        throw new SignRequestSignatureException(msg);
                    }
                    String username = reqmsg.getUsername();
                    if (username == null) {
                        String msg = "No username in request, request DN: " + reqmsg.getRequestDN();
                        log.error(msg);
                        throw new SignRequestException(msg);
                    }
                    log.info("Received a SCEP/PKCS10 request for user: " + username + ", from host: "
                            + remoteAddr);
                    String authPwd = ExtraConfiguration.instance().getString(ExtraConfiguration.SCEPAUTHPWD);
                    if (StringUtils.isNotEmpty(authPwd) && !StringUtils.equals(authPwd, "none")) {
                        log.debug("Requiring authPwd in order to precess SCEP requests");
                        String pwd = reqmsg.getPassword();
                        if (!StringUtils.equals(authPwd, pwd)) {
                            log.error("Wrong auth password received in SCEP request: " + pwd);
                            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Auth pwd missmatch");
                            return;
                        }
                        log.debug("Request passed authPwd test.");
                    } else {
                        log.debug("Not requiring authPwd in order to precess SCEP requests");
                    }
                    // Try to find the CA name from the issuerDN, if we can't find it (i.e. not defined in web.xml) we use the default
                    String issuerDN = CertTools.stringToBCDNString(reqmsg.getIssuerDN());
                    String caName = ExtraConfiguration.instance().getString(issuerDN);
                    if (StringUtils.isEmpty(caName)) {
                        caName = ExtraConfiguration.instance().getString(ExtraConfiguration.SCEPDEFAULTCA);
                        log.info("Did not find a CA name from issuerDN: " + issuerDN
                                + ", using the default CA '" + caName + "'");
                    } else {
                        log.debug("Found a CA name '" + caName + "' from issuerDN: " + issuerDN);
                    }
                    // Get altNames if we can find them
                    String altNames = reqmsg.getRequestAltNames();

                    byte[] encoded = reqmsg.getCertificationRequest().getEncoded();
                    String pkcs10 = new String(Base64.encode(encoded, false));

                    // Create a pkcs10 request
                    String certificateProfile = ExtraConfiguration.instance()
                            .getString(ExtraConfiguration.SCEPCERTPROFILEKEY);
                    String entityProfile = ExtraConfiguration.instance()
                            .getString(ExtraConfiguration.SCEPENTITYPROFILEKEY);
                    boolean createOrEditUser = ExtraConfiguration.instance()
                            .getBoolean(ExtraConfiguration.SCEPEDITUSER);
                    PKCS10Request req = new PKCS10Request(100, username, reqmsg.getRequestDN(), altNames, null,
                            null, entityProfile, certificateProfile, caName, pkcs10);
                    req.setCreateOrEditUser(createOrEditUser);
                    SubMessages submessages = new SubMessages();
                    submessages.addSubMessage(req);
                    msgHome.create(transId, submessages);
                    reply = createPendingResponseMessage(reqmsg, racert, rapriv, cryptProvider)
                            .getResponseMessage();
                }
            }

            if (reply == null) {
                // This is probably a getCert message?
                log.debug("Sending HttpServletResponse.SC_NOT_IMPLEMENTED (501) response");
                response.sendError(HttpServletResponse.SC_NOT_IMPLEMENTED, "Can not handle request");
                return;
            }
            // Send back SCEP response, PKCS#7 which contains the end entity's certificate, or pending, or failure
            sendBinaryBytes(reply, response, "application/x-pki-message", null);
        } else if (operation.equals("GetCACert")) {
            // The response has the content type tagged as application/x-x509-ca-cert. 
            // The body of the response is a DER encoded binary X.509 certificate. 
            // For example: "Content-Type:application/x-x509-ca-cert\n\n"<BER-encoded X509>
            // IF we are not an RA, which in case we should return the same thing as GetCACertChain
            log.info("Got SCEP cert request for CA '" + message + "'");
            if (chain != null) {
                if (chain.length > 1) {
                    // We are an RA, so return the same as GetCACertChain, but with other content type
                    getCACertChain(message, remoteAddr, response, alias, raks, false);
                } else {
                    // The CA certificate is no 0
                    X509Certificate cert = (X509Certificate) chain[0];
                    if (chain.length > 1) {
                        cert = (X509Certificate) chain[1];
                    }
                    log.debug("Found cert with DN '" + cert.getSubjectDN().toString() + "'");
                    log.info("Sent certificate for CA '" + message + "' to SCEP client with ip " + remoteAddr);
                    sendBinaryBytes(cert.getEncoded(), response, "application/x-x509-ca-cert", null);
                }
            } else {
                log.error("No CA certificates found");
                response.sendError(HttpServletResponse.SC_NOT_FOUND, "No CA certificates found.");
            }
        } else if (operation.equals("GetCACertChain")) {
            // The response for GetCACertChain is a certificates-only PKCS#7 
            // SignedDatato carry the certificates to the end entity, with a 
            // Content-Type of application/x-x509-ca-ra-cert-chain.
            log.info("Got SCEP cert chain request for CA '" + message + "'");
            getCACertChain(message, remoteAddr, response, alias, raks, true);
        } else if (operation.equals("GetCACaps")) {
            // The response for GetCACaps is a <lf> separated list of capabilities

            /*
             "GetNextCACert"       CA Supports the GetNextCACert message.
             "POSTPKIOperation"    PKIOPeration messages may be sent via HTTP POST.
             "SHA-1"               CA Supports the SHA-1 hashing algorithm in 
                               signatures and fingerprints.  If present, the
                               client SHOULD use SHA-1.  If absent, the client
                               MUST use MD5 to maintain backward compatability.
             "Renewal"             Clients may use current certificate and key to
                               authenticate an enrollment request for a new
                               certificate.  
             */
            log.info("Got SCEP CACaps request for CA '" + message + "'");
            response.setContentType("text/plain");
            response.getOutputStream().print("POSTPKIOperation\nSHA-1");
        }
    } catch (java.lang.ArrayIndexOutOfBoundsException ae) {
        log.error("Empty or invalid request received.", ae);
        // TODO: Send back proper Failure Response
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, ae.getMessage());
    } catch (Exception e) {
        log.error("Error in ScepRAServlet:", e);
        // TODO: Send back proper Failure Response
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
    }
}

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

/**
 * Test method for {@link net.sf.taverna.t2.security.credentialmanager.impl.CredentialManagerImpl#loadPKCS12Keystore(java.io.File, java.lang.String)}.
 * @throws CMException //from  w w w. jav  a  2 s.  c o  m
 * @throws KeyStoreException 
 * @throws NoSuchAlgorithmException 
 * @throws UnrecoverableKeyException 
 */
@Test
public void testLoadPKCS12Keystore()
        throws CMException, KeyStoreException, UnrecoverableKeyException, NoSuchAlgorithmException {
    KeyStore pkcs12Keystore = credentialManager.loadPKCS12Keystore(
            new File(privateKeyFileURL.getPath()).toPath(), privateKeyAndPKCS12KeystorePassword);

    Key privateKey2 = null;
    Certificate[] privateKeyCertChain2 = null;

    Enumeration<String> aliases = pkcs12Keystore.aliases();
    while (aliases.hasMoreElements()) {
        // The test-private-key-cert.p12 file contains only one private key
        // and corresponding certificate entry
        String alias = aliases.nextElement();
        if (pkcs12Keystore.isKeyEntry(alias)) { // is it a (private) key entry?
            privateKey2 = pkcs12Keystore.getKey(alias, privateKeyAndPKCS12KeystorePassword.toCharArray());
            privateKeyCertChain2 = pkcs12Keystore.getCertificateChain(alias);
            break;
        }
    }
    assertNotNull(privateKey2);
    assertNotNull(privateKeyCertChain2);
}