Example usage for java.security KeyPair getPrivate

List of usage examples for java.security KeyPair getPrivate

Introduction

In this page you can find the example usage for java.security KeyPair getPrivate.

Prototype

public PrivateKey getPrivate() 

Source Link

Document

Returns a reference to the private key component of this key pair.

Usage

From source file:cherry.goods.crypto.RSASignatureTest.java

private RSASignature create2(char[] password) throws Exception {

    KeyPairGenerator keygen = KeyPairGenerator.getInstance("RSA");
    keygen.initialize(2048);/*from ww w  .  j a  v a 2  s.co m*/
    KeyPair key = keygen.generateKeyPair();

    String pbeAlgName = "PBEWithMD5AndDES";
    PBEKeySpec pbeKeySpec = new PBEKeySpec(password);
    PBEParameterSpec pbeParamSpec = new PBEParameterSpec(RandomUtils.nextBytes(8), 20);
    SecretKey pbeKey = SecretKeyFactory.getInstance(pbeAlgName).generateSecret(pbeKeySpec);
    AlgorithmParameters pbeParam = AlgorithmParameters.getInstance(pbeAlgName);
    pbeParam.init(pbeParamSpec);
    Cipher cipher = Cipher.getInstance(pbeAlgName);
    cipher.init(Cipher.ENCRYPT_MODE, pbeKey, pbeParam);
    EncryptedPrivateKeyInfo encryptedKeyInfo = new EncryptedPrivateKeyInfo(pbeParam,
            cipher.doFinal(key.getPrivate().getEncoded()));

    RSASignature impl = new RSASignature();
    impl.setAlgorithm("SHA256withRSA");
    impl.setPublicKeyBytes(key.getPublic().getEncoded());
    impl.setPrivateKeyBytes(encryptedKeyInfo.getEncoded(), password);
    return impl;
}

From source file:cherry.goods.crypto.RSACryptoTest.java

private RSACrypto create2(char[] password) throws Exception {

    KeyPairGenerator keygen = KeyPairGenerator.getInstance("RSA");
    keygen.initialize(2048);//from ww  w.j  a  v  a 2s .c o  m
    KeyPair key = keygen.generateKeyPair();

    String pbeAlgName = "PBEWithMD5AndDES";
    PBEKeySpec pbeKeySpec = new PBEKeySpec(password);
    PBEParameterSpec pbeParamSpec = new PBEParameterSpec(RandomUtils.nextBytes(8), 20);
    SecretKey pbeKey = SecretKeyFactory.getInstance(pbeAlgName).generateSecret(pbeKeySpec);
    AlgorithmParameters pbeParam = AlgorithmParameters.getInstance(pbeAlgName);
    pbeParam.init(pbeParamSpec);
    Cipher cipher = Cipher.getInstance(pbeAlgName);
    cipher.init(Cipher.ENCRYPT_MODE, pbeKey, pbeParam);
    EncryptedPrivateKeyInfo encryptedKeyInfo = new EncryptedPrivateKeyInfo(pbeParam,
            cipher.doFinal(key.getPrivate().getEncoded()));

    RSACrypto impl = new RSACrypto();
    impl.setAlgorithm("RSA/ECB/PKCS1Padding");
    impl.setPublicKeyBytes(key.getPublic().getEncoded());
    impl.setPrivateKeyBytes(encryptedKeyInfo.getEncoded(), password);
    return impl;
}

From source file:cybervillains.ca.KeyStoreManager.java

/**
 * Creates, writes and loads a new keystore and CA root certificate.
 *//* w  w  w  . j  a  v a 2  s  . c  o m*/
protected void createKeystore() {

    Certificate signingCert = null;
    PrivateKey caPrivKey = null;

    if (_caCert == null || _caPrivKey == null) {
        try {
            log.debug("Keystore or signing cert & keypair not found.  Generating...");

            KeyPair caKeypair = getRSAKeyPair();
            caPrivKey = caKeypair.getPrivate();
            signingCert = CertificateCreator.createTypicalMasterCert(caKeypair);

            log.debug("Done generating signing cert");
            log.debug(signingCert);

            _ks.load(null, _keystorepass);

            _ks.setCertificateEntry(_caCertAlias, signingCert);
            _ks.setKeyEntry(_caPrivKeyAlias, caPrivKey, _keypassword, new Certificate[] { signingCert });

            File caKsFile = new File(root, _caPrivateKeystore);

            OutputStream os = new FileOutputStream(caKsFile);
            _ks.store(os, _keystorepass);

            log.debug("Wrote JKS keystore to: " + caKsFile.getAbsolutePath());

            // also export a .cer that can be imported as a trusted root
            // to disable all warning dialogs for interception

            File signingCertFile = new File(root, EXPORTED_CERT_NAME);

            FileOutputStream cerOut = new FileOutputStream(signingCertFile);

            byte[] buf = signingCert.getEncoded();

            log.debug("Wrote signing cert to: " + signingCertFile.getAbsolutePath());

            cerOut.write(buf);
            cerOut.flush();
            cerOut.close();

            _caCert = (X509Certificate) signingCert;
            _caPrivKey = caPrivKey;
        } catch (Exception e) {
            log.error("Fatal error creating/storing keystore or signing cert.", e);
            throw new Error(e);
        }
    } else {
        log.debug("Successfully loaded keystore.");
        log.debug(_caCert);

    }

}

From source file:mitm.common.security.ca.handlers.comodo.ApplyCustomClientCertTest.java

@Test
public void testApply() throws Exception {
    KeyPair keyPair = generateKeyPair();

    X500PrincipalBuilder principalBuilder = new X500PrincipalBuilder();

    principalBuilder.setCommonName("Martijn Brinkers");
    principalBuilder.setOrganisation("Djigzo");
    principalBuilder.setEmail("martijn@djigzo.com");

    PKCS10CertificationRequestBuilder requestBuilder = new PKCS10CertificationRequestBuilder(
            X500PrincipalUtils.toX500Name(principalBuilder.buildPrincipal()),
            SubjectPublicKeyInfo.getInstance(keyPair.getPublic().getEncoded()));

    PKCS10CertificationRequest pkcs10 = requestBuilder
            .build(getContentSigner("SHA1WithRSA", keyPair.getPrivate()));

    String csr = MiscStringUtils.toAsciiString(Base64.encodeBase64(pkcs10.getEncoded()));

    ComodoConnectionSettings connectionSettings = new ComodoConnectionSettingsImpl(60000, null);

    ApplyCustomClientCert requestor = new ApplyCustomClientCert(connectionSettings);

    requestor.setAP("CHANGE");
    requestor.setDays(365);//from www .java  2 s  .c  o m
    requestor.setPkcs10(csr);
    //requestor.setCACertificateID(1);

    assertFalse(requestor.apply());
    assertTrue(requestor.isError());
    assertEquals(CustomClientStatusCode.ARGUMENT_IS_INVALID, requestor.getErrorCode());
    assertEquals("The value of the 'ap' argument is invalid!", requestor.getErrorMessage());
}

From source file:com.ibm.iotf.client.AbstractClient.java

static SSLSocketFactory getSocketFactory(final String caCrtFile, final String crtFile, final String keyFile,
        final String password) throws IOException, KeyStoreException, NoSuchAlgorithmException,
        CertificateException, UnrecoverableKeyException, KeyManagementException {
    Security.addProvider(new BouncyCastleProvider());
    X509Certificate caCert = null;

    if (caCrtFile != null) {
        // load CA certificate
        PEMReader reader = new PEMReader(
                new InputStreamReader(new ByteArrayInputStream(Files.readAllBytes(Paths.get(caCrtFile)))));
        caCert = (X509Certificate) reader.readObject();
        reader.close();/*from  w  w w.  j ava 2 s .  c  om*/
    } else {
        ClassLoader classLoader = AbstractClient.class.getClassLoader();
        PEMReader reader = new PEMReader(
                new InputStreamReader(classLoader.getResource(SERVER_MESSAGING_PEM).openStream()));
        caCert = (X509Certificate) reader.readObject();
        reader.close();
    }

    PEMReader reader = new PEMReader(
            new InputStreamReader(new ByteArrayInputStream(Files.readAllBytes(Paths.get(crtFile)))));
    X509Certificate cert = (X509Certificate) reader.readObject();
    reader.close();

    // load client private key
    reader = new PEMReader(
            new InputStreamReader(new ByteArrayInputStream(Files.readAllBytes(Paths.get(keyFile)))));
    KeyPair key = (KeyPair) reader.readObject();
    reader.close();

    TrustManagerFactory tmf = null;
    if (caCert != null) {
        // CA certificate is used to authenticate server
        KeyStore caKs = KeyStore.getInstance("JKS");
        //caKs.load(null, null);
        caKs.load(null, null);
        caKs.setCertificateEntry("ca-certificate", caCert);
        tmf = TrustManagerFactory.getInstance("PKIX");
        tmf.init(caKs);
    }
    // client key and certificates are sent to server so it can authenticate us
    KeyStore ks = KeyStore.getInstance("JKS");
    ks.load(null, null);
    ks.setCertificateEntry("certificate", cert);
    ks.setKeyEntry("private-key", key.getPrivate(), password.toCharArray(),
            new java.security.cert.Certificate[] { cert });
    KeyManagerFactory kmf = KeyManagerFactory.getInstance("PKIX");
    kmf.init(ks, password.toCharArray());

    // finally, create SSL socket factory
    SSLContext context = SSLContext.getInstance("TLSv1.2");
    if (tmf != null) {
        context.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
    } else {
        context.init(kmf.getKeyManagers(), null, null);
    }

    return context.getSocketFactory();
}

From source file:com.streamsets.pipeline.stage.origin.tcp.TestTCPServerSource.java

@Test
public void initMethod() throws Exception {

    final TCPServerSourceConfig configBean = createConfigBean(Charsets.ISO_8859_1);

    initSourceAndValidateIssues(configBean);

    // empty ports
    configBean.ports = new LinkedList<>();
    initSourceAndValidateIssues(configBean, Errors.TCP_02);

    // invalid ports
    // too large//from w  ww.  j ava  2  s.  c om
    configBean.ports = Arrays.asList("123456789");
    initSourceAndValidateIssues(configBean, Errors.TCP_03);

    // not a number
    configBean.ports = Arrays.asList("abcd");
    initSourceAndValidateIssues(configBean, Errors.TCP_03);

    // start TLS config tests
    configBean.ports = randomSinglePort();
    configBean.tlsConfigBean.tlsEnabled = true;
    configBean.tlsConfigBean.keyStoreFilePath = "non-existent-file-path";
    initSourceAndValidateIssues(configBean, TlsConfigErrors.TLS_01);

    File blankTempFile = File.createTempFile("blank", "txt");
    blankTempFile.deleteOnExit();
    configBean.tlsConfigBean.keyStoreFilePath = blankTempFile.getAbsolutePath();
    initSourceAndValidateIssues(configBean, TlsConfigErrors.TLS_21);

    // now, try with real keystore
    String hostname = TLSTestUtils.getHostname();
    File testDir = new File("target", UUID.randomUUID().toString()).getAbsoluteFile();
    testDir.deleteOnExit();
    final File keyStore = new File(testDir, "keystore.jks");
    keyStore.deleteOnExit();
    Assert.assertTrue(testDir.mkdirs());
    final String keyStorePassword = "keystore";
    KeyPair keyPair = TLSTestUtils.generateKeyPair();
    Certificate cert = TLSTestUtils.generateCertificate("CN=" + hostname, keyPair, 30);
    TLSTestUtils.createKeyStore(keyStore.toString(), keyStorePassword, "web", keyPair.getPrivate(), cert);

    configBean.tlsConfigBean.keyStoreFilePath = keyStore.getAbsolutePath();
    configBean.tlsConfigBean.keyStorePassword = () -> "invalid-password";

    initSourceAndValidateIssues(configBean, TlsConfigErrors.TLS_21);

    // finally, a valid certificate/config
    configBean.tlsConfigBean.keyStorePassword = () -> keyStorePassword;
    initSourceAndValidateIssues(configBean);

    // ack ELs
    configBean.recordProcessedAckMessage = "${invalid EL)";
    initSourceAndValidateIssues(configBean, Errors.TCP_30);
    configBean.recordProcessedAckMessage = "${time:now()}";
    configBean.batchCompletedAckMessage = "${another invalid EL]";
    initSourceAndValidateIssues(configBean, Errors.TCP_31);
    configBean.batchCompletedAckMessage = "${record:value('/first')}";

    // syslog mode
    configBean.tcpMode = TCPMode.SYSLOG;
    configBean.syslogFramingMode = SyslogFramingMode.NON_TRANSPARENT_FRAMING;
    configBean.nonTransparentFramingSeparatorCharStr = "";
    initSourceAndValidateIssues(configBean, Errors.TCP_40);
    configBean.syslogFramingMode = SyslogFramingMode.OCTET_COUNTING;
    initSourceAndValidateIssues(configBean);

    // separated records
    configBean.tcpMode = TCPMode.DELIMITED_RECORDS;
    configBean.dataFormatConfig.charset = Charsets.UTF_8.name();
    initSourceAndValidateIssues(configBean, Errors.TCP_41);
    configBean.recordSeparatorStr = "";
    initSourceAndValidateIssues(configBean, Errors.TCP_40);
    configBean.recordSeparatorStr = "x";
    initSourceAndValidateIssues(configBean, DataFormatErrors.DATA_FORMAT_12);
    configBean.dataFormat = DataFormat.TEXT;
    initSourceAndValidateIssues(configBean);

}

From source file:com.cws.esolutions.security.processors.impl.FileSecurityProcessorImpl.java

/**
 * @see com.cws.esolutions.security.processors.interfaces.IFileSecurityProcessor#signFile(com.cws.esolutions.security.processors.dto.FileSecurityRequest)
 *///w w  w  .j  av a  2s .c o  m
public synchronized FileSecurityResponse signFile(final FileSecurityRequest request)
        throws FileSecurityException {
    final String methodName = IFileSecurityProcessor.CNAME
            + "#signFile(final FileSecurityRequest request) throws FileSecurityException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("FileSecurityRequest: {}", request);
    }

    FileSecurityResponse response = new FileSecurityResponse();

    final RequestHostInfo reqInfo = request.getHostInfo();
    final UserAccount userAccount = request.getUserAccount();
    final KeyManager keyManager = KeyManagementFactory.getKeyManager(keyConfig.getKeyManager());

    if (DEBUG) {
        DEBUGGER.debug("RequestHostInfo: {}", reqInfo);
        DEBUGGER.debug("UserAccount", userAccount);
        DEBUGGER.debug("KeyManager: {}", keyManager);
    }

    try {
        KeyPair keyPair = keyManager.returnKeys(userAccount.getGuid());

        if (keyPair != null) {
            Signature signature = Signature.getInstance(fileSecurityConfig.getSignatureAlgorithm());
            signature.initSign(keyPair.getPrivate());
            signature.update(IOUtils.toByteArray(new FileInputStream(request.getUnsignedFile())));

            if (DEBUG) {
                DEBUGGER.debug("Signature: {}", signature);
            }

            byte[] sig = signature.sign();

            if (DEBUG) {
                DEBUGGER.debug("Signature: {}", sig);
            }

            IOUtils.write(sig, new FileOutputStream(request.getSignedFile()));

            if ((request.getSignedFile().exists()) && (request.getSignedFile().length() != 0)) {
                response.setSignedFile(request.getSignedFile());
                response.setRequestStatus(SecurityRequestStatus.SUCCESS);
            } else {
                response.setRequestStatus(SecurityRequestStatus.FAILURE);
            }
        } else {
            response.setRequestStatus(SecurityRequestStatus.FAILURE);
        }
    } catch (NoSuchAlgorithmException nsax) {
        ERROR_RECORDER.error(nsax.getMessage(), nsax);

        throw new FileSecurityException(nsax.getMessage(), nsax);
    } catch (FileNotFoundException fnfx) {
        ERROR_RECORDER.error(fnfx.getMessage(), fnfx);

        throw new FileSecurityException(fnfx.getMessage(), fnfx);
    } catch (InvalidKeyException ikx) {
        ERROR_RECORDER.error(ikx.getMessage(), ikx);

        throw new FileSecurityException(ikx.getMessage(), ikx);
    } catch (SignatureException sx) {
        ERROR_RECORDER.error(sx.getMessage(), sx);

        throw new FileSecurityException(sx.getMessage(), sx);
    } catch (IOException iox) {
        ERROR_RECORDER.error(iox.getMessage(), iox);

        throw new FileSecurityException(iox.getMessage(), iox);
    } catch (KeyManagementException kmx) {
        ERROR_RECORDER.error(kmx.getMessage(), kmx);

        throw new FileSecurityException(kmx.getMessage(), kmx);
    } finally {
        // audit
        try {
            AuditEntry auditEntry = new AuditEntry();
            auditEntry.setHostInfo(reqInfo);
            auditEntry.setAuditType(AuditType.SIGNFILE);
            auditEntry.setUserAccount(userAccount);
            auditEntry.setAuthorized(Boolean.TRUE);
            auditEntry.setApplicationId(request.getApplicationId());
            auditEntry.setApplicationName(request.getAppName());

            if (DEBUG) {
                DEBUGGER.debug("AuditEntry: {}", auditEntry);
            }

            AuditRequest auditRequest = new AuditRequest();

            if (DEBUG) {
                DEBUGGER.debug("AuditRequest: {}", auditRequest);
            }

            auditor.auditRequest(auditRequest);
        } catch (AuditServiceException asx) {
            ERROR_RECORDER.error(asx.getMessage(), asx);
        }
    }

    return response;
}

From source file:com.mytalentfolio.h_daforum.CconnectToServer.java

/**
 * {@code connect} is for forming the secure connection between server and
 * android, sending and receiving of the data.
 * /*from www  . ja  va 2 s .  co m*/
 * @param arg0
 *            data which is to be sent to server.
 * 
 * @return data in string format, received from the server.
 */
public String connect(String... arg0) {

    int nrOfDataToSendToServer = arg0.length;
    nrOfDataToSendToServer = nrOfDataToSendToServer - 1;
    boolean valid = false;
    String dataFromServer = "unverified", serverPublicKeySigStr, serverDataSig;

    try {
        //Creating the server certificate
        Certificate serverCertificate = getServerCertificate();

        KeyStore keyStore = getKeyStore(serverCertificate);

        TrustManagerFactory tmf = getTrustManager(keyStore);

        SSLContext sslContext = getSSLContext(tmf);

        HostnameVerifier hostnameVerifier = new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        };

        HttpsURLConnection urlConnection = getURLConnection(sslContext, hostnameVerifier);

        // Converting the data into JSONObject
        JSONObject obj = new JSONObject();
        for (int i = 0; i <= nrOfDataToSendToServer; i++) {
            obj.put("param" + i, arg0[i]);
        }

        // Converting the JSONObject into string
        String dataToSend = obj.toString();

        KeyPairGenerator keyGen = getKeyPairGenerator();

        KeyPair keyPair = keyGen.generateKeyPair();
        //Public key for verifying the digital signature
        PublicKey clientPublicKeySig = keyPair.getPublic();
        //Private key for signing the data
        PrivateKey clientPrivateKeySig = keyPair.getPrivate();

        // Get signed data
        String sigData = getDataSig(clientPrivateKeySig, dataToSend);

        // Creating URL Format
        String urlData = URLEncoder.encode("clientPublicKeySig", "UTF-8") + "=" + URLEncoder
                .encode(Base64.encodeToString(clientPublicKeySig.getEncoded(), Base64.DEFAULT), "UTF-8");
        urlData += "&" + URLEncoder.encode("clientData", "UTF-8") + "="
                + URLEncoder.encode(dataToSend, "UTF-8");
        urlData += "&" + URLEncoder.encode("clientDataSig", "UTF-8") + "="
                + URLEncoder.encode(sigData, "UTF-8");

        // Sending the data to the server
        OutputStreamWriter wr = new OutputStreamWriter(urlConnection.getOutputStream());
        wr.write(urlData);
        wr.flush();
        wr.close();

        // Receiving the data from server
        BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
        StringBuilder sb = new StringBuilder();
        String line = null;

        // Read Server Response
        while ((line = reader.readLine()) != null) {
            // Append server response in string
            sb.append(line + "\n");
            // sb.append(line);
        }
        String text = sb.toString();
        reader.close();

        // Extracting the data, public key and signature received from
        // server
        Vector<String> storeExtractedValues = new Vector<String>();

        storeExtractedValues = extractDataFromJson(text, "data");
        dataFromServer = storeExtractedValues.get(0);

        storeExtractedValues = extractDataFromJson(text, "serverPublicKeySig");
        serverPublicKeySigStr = storeExtractedValues.get(0);

        storeExtractedValues = extractDataFromJson(text, "serverDataSig");
        serverDataSig = storeExtractedValues.get(0);

        // Converting the Server Public key format to Java compatible from
        PublicKey serverPublicKeySig = getServerPublicKey(serverPublicKeySigStr);

        // Verify the received data
        valid = getDataValidity(serverPublicKeySig, dataFromServer, serverDataSig);

        // Disconnect the url connection
        urlConnection.disconnect();

        if (dataFromServer.equalsIgnoreCase("unverified")) {
            CExceptionHandling.ExceptionState = ExceptionSet.SENT_DATA_UNVERIFIED;
            return "-1";
        } else if (valid == false) {
            CExceptionHandling.ExceptionState = ExceptionSet.RECEIVED_DATA_UNVERIFIED;
            return "-1";
        } else {
            return dataFromServer;
        }

    } catch (Exception e) {
        CExceptionHandling.ExceptionMsg = e.getMessage();

        if (e.toString().equals("java.net.SocketException: Network unreachable")) {
            CExceptionHandling.ExceptionState = ExceptionSet.NO_DATA_CONNECTION;
        } else if (e.toString().equals(
                "java.net.SocketTimeoutException: failed to connect to /10.0.2.2 (port 443) after 10000ms")) {
            CExceptionHandling.ExceptionState = ExceptionSet.CONNECTION_TIMEOUT;
        } else {
            CExceptionHandling.ExceptionState = ExceptionSet.OTHER_EXCEPTIONS;
        }
        return "-1";
    }

}

From source file:org.kaaproject.kaa.client.KaaClientTest.java

protected void initStorageMock(PersistentStorage storage) throws NoSuchAlgorithmException, IOException {
    KeyPair kp = KeyUtil.generateKeyPair();
    Mockito.when(storage.exists(KaaClientProperties.CLIENT_PUBLIC_KEY_NAME_DEFAULT)).thenReturn(true);
    Mockito.when(storage.exists(KaaClientProperties.CLIENT_PRIVATE_KEY_NAME_DEFAULT)).thenReturn(true);
    Mockito.when(storage.openForRead(KaaClientProperties.CLIENT_PUBLIC_KEY_NAME_DEFAULT))
            .thenReturn(new ByteArrayInputStream(kp.getPublic().getEncoded()));
    Mockito.when(storage.openForRead(KaaClientProperties.CLIENT_PRIVATE_KEY_NAME_DEFAULT))
            .thenReturn(new ByteArrayInputStream(kp.getPrivate().getEncoded()));
    Mockito.when(storage.openForWrite(Mockito.anyString())).thenReturn(Mockito.mock(OutputStream.class));
}

From source file:org.forgerock.openidm.security.impl.SecurityResourceProvider.java

/**
 * Generates a CSR request./*from  w  w  w. ja v  a  2 s.  c o  m*/
 * 
 * @param alias
 * @param algorithm
 * @param signatureAlgorithm
 * @param keySize
 * @param params
 * @return
 * @throws Exception
 */
protected Pair<PKCS10CertificationRequest, PrivateKey> generateCSR(String alias, String algorithm,
        String signatureAlgorithm, int keySize, JsonValue params) throws Exception {

    // Construct the distinguished name
    StringBuilder sb = new StringBuilder();
    sb.append("CN=").append(params.get("CN").required().asString().replaceAll(",", "\\\\,"));
    sb.append(", OU=").append(params.get("OU").defaultTo("None").asString().replaceAll(",", "\\\\,"));
    sb.append(", O=").append(params.get("O").defaultTo("None").asString().replaceAll(",", "\\\\,"));
    sb.append(", L=").append(params.get("L").defaultTo("None").asString().replaceAll(",", "\\\\,"));
    sb.append(", ST=").append(params.get("ST").defaultTo("None").asString().replaceAll(",", "\\\\,"));
    sb.append(", C=").append(params.get("C").defaultTo("None").asString().replaceAll(",", "\\\\,"));

    // Create the principle subject name
    X509Principal subjectName = new X509Principal(sb.toString());

    //store.getStore().

    // Generate the key pair
    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance(algorithm);
    keyPairGenerator.initialize(keySize);
    KeyPair keyPair = keyPairGenerator.generateKeyPair();
    PublicKey publicKey = keyPair.getPublic();
    PrivateKey privateKey = keyPair.getPrivate();

    // Generate the certificate request
    PKCS10CertificationRequest cr = new PKCS10CertificationRequest(signatureAlgorithm, subjectName, publicKey,
            null, privateKey);

    // Store the private key to use when the signed cert is return and updated
    logger.debug("Storing private key with alias {}", alias);
    storeKeyPair(alias, keyPair);

    return Pair.of(cr, privateKey);
}