Example usage for java.security KeyPairGenerator initialize

List of usage examples for java.security KeyPairGenerator initialize

Introduction

In this page you can find the example usage for java.security KeyPairGenerator initialize.

Prototype

public void initialize(AlgorithmParameterSpec params, SecureRandom random)
        throws InvalidAlgorithmParameterException 

Source Link

Document

Initializes the key pair generator with the given parameter set and source of randomness.

Usage

From source file:be.e_contract.mycarenet.common.SessionKey.java

/**
 * Generator constructor. Creates a new MyCareNet session key.
 * //  w  ww  .  ja  v a 2 s.  c om
 * @param keySize
 *            the RSA key size.
 */
public SessionKey(int keySize) {
    KeyPairGenerator keyPairGenerator;
    try {
        keyPairGenerator = KeyPairGenerator.getInstance("RSA");
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException("RSA algo not available", e);
    }
    SecureRandom random = new SecureRandom();
    try {
        keyPairGenerator.initialize(new RSAKeyGenParameterSpec(keySize, RSAKeyGenParameterSpec.F4), random);
    } catch (InvalidAlgorithmParameterException e) {
        throw new RuntimeException("unsupported key size: " + keySize);
    }
    this.keyPair = keyPairGenerator.generateKeyPair();
}

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

private synchronized KeyPair generateKeyPair(int keyLength)
        throws NoSuchAlgorithmException, NoSuchProviderException {
    KeyPairGenerator keyPairGenerator = securityFactory.createKeyPairGenerator("RSA");

    keyPairGenerator.initialize(keyLength, randomSource);

    return keyPairGenerator.generateKeyPair();
}

From source file:net.solarnetwork.node.setup.impl.DefaultKeystoreService.java

private X509Certificate createSelfSignedCertificate(KeyStore keyStore, String dn, String alias) {
    try {/*w ww. j a  v  a  2s.  c o  m*/
        // create new key pair for the node
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
        keyGen.initialize(keySize, new SecureRandom());
        KeyPair keypair = keyGen.generateKeyPair();
        PublicKey publicKey = keypair.getPublic();
        PrivateKey privateKey = keypair.getPrivate();

        Certificate cert = certificateService.generateCertificate(dn, publicKey, privateKey);
        keyStore.setKeyEntry(alias, privateKey, getKeyStorePassword().toCharArray(),
                new Certificate[] { cert });
        saveKeyStore(keyStore);
        return (X509Certificate) cert;
    } catch (NoSuchAlgorithmException e) {
        throw new CertificateException("Error setting up node key pair", e);
    } catch (KeyStoreException e) {
        throw new CertificateException("Error setting up node key pair", e);
    }
}

From source file:qauth.djd.qauthclient.main.ContentFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

    Bundle args = getArguments();/*from   w w w  .ja  v a 2  s  .  c  om*/
    if (args.getCharSequence(KEY_TITLE).toString().equals("Providers")) {

        View rootView = inflater.inflate(R.layout.providers_view_frag, container, false);

        mRecyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerView);
        mLayoutManager = new LinearLayoutManager(getActivity());
        mCurrentLayoutManagerType = LayoutManagerType.LINEAR_LAYOUT_MANAGER;

        if (savedInstanceState != null) {
            // Restore saved layout manager type.
            mCurrentLayoutManagerType = (LayoutManagerType) savedInstanceState
                    .getSerializable(KEY_LAYOUT_MANAGER);
        }
        setRecyclerViewLayoutManager(mCurrentLayoutManagerType);

        pAdapter = new ProviderAdapter(pDataset);
        mRecyclerView.setAdapter(pAdapter);

        final PackageManager pm = getActivity().getPackageManager();
        List<ApplicationInfo> packages = pm.getInstalledApplications(PackageManager.GET_META_DATA);

        for (ApplicationInfo packageInfo : packages) {
            //Log.i(TAG, "Installed package :" + packageInfo.packageName);
            //Log.i(TAG, "Source dir : " + packageInfo.sourceDir);
            //Log.i(TAG, "Launch Activity :" + pm.getLaunchIntentForPackage(packageInfo.packageName));

            if (packageInfo.packageName.equals("qauth.djd.dummyclient")) {
                Provider provider = new Provider("DummyClient", packageInfo.packageName);
                pDataset.add(provider);
                pAdapter.notifyDataSetChanged();
            }

        }

        //get local package names and cross reference with providers on server ("/provider/available")
        //display package names in listview
        //allow user to click on item to activate or deactivate
        // '-> have check box with progress bar indicating status

        return rootView;

    } else {

        View rootView = inflater.inflate(R.layout.recycler_view_frag, container, false);
        mRecyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerView);
        mLayoutManager = new LinearLayoutManager(getActivity());
        mCurrentLayoutManagerType = LayoutManagerType.LINEAR_LAYOUT_MANAGER;

        if (savedInstanceState != null) {
            // Restore saved layout manager type.
            mCurrentLayoutManagerType = (LayoutManagerType) savedInstanceState
                    .getSerializable(KEY_LAYOUT_MANAGER);
        }
        setRecyclerViewLayoutManager(mCurrentLayoutManagerType);

        wAdapter = new WatchAdapter(wDataset);
        mRecyclerView.setAdapter(wAdapter);

        FloatingActionButton fab = (FloatingActionButton) rootView.findViewById(R.id.fab);
        fab.attachToRecyclerView(mRecyclerView);

        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.i("test", "clicked!");

                AlertDialog.Builder builderSingle = new AlertDialog.Builder(getActivity());
                builderSingle.setIcon(R.drawable.ic_launcher);
                builderSingle.setTitle("Select Bluetooth Device");
                final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(getActivity(),
                        android.R.layout.select_dialog_singlechoice);
                new Thread(new Runnable() {
                    public void run() {
                        for (String s : getNodes()) {
                            arrayAdapter.add(s);
                        }
                    }
                }).start();
                builderSingle.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
                builderSingle.setAdapter(arrayAdapter, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        String nodeId = arrayAdapter.getItem(which);
                        String privKey = null;
                        String pubKey = null;

                        try {
                            SecureRandom random = new SecureRandom();
                            RSAKeyGenParameterSpec spec = new RSAKeyGenParameterSpec(1024,
                                    RSAKeyGenParameterSpec.F4);
                            KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA", "SC");
                            generator.initialize(spec, random);
                            KeyPair pair = generator.generateKeyPair();
                            privKey = Base64.encodeToString(pair.getPrivate().getEncoded(), Base64.DEFAULT);
                            pubKey = Base64.encodeToString(pair.getPublic().getEncoded(), Base64.DEFAULT);
                        } catch (Exception e) {
                            Log.i("generate", "error: " + e);
                        }

                        //Log.i("keys", "priv key : " + privKey);

                        //String privKey = Base64.encodeToString(MainTabsActivity.privKey.getEncoded(), Base64.DEFAULT);
                        //String pubKey = Base64.encodeToString(MainTabsActivity.pubKey.getEncoded(), Base64.DEFAULT);

                        Keys keys = new Keys(privKey, pubKey);
                        ByteArrayOutputStream bos = new ByteArrayOutputStream();
                        ObjectOutput out = null;
                        try {
                            out = new ObjectOutputStream(bos);
                        } catch (Exception e) {
                        }
                        try {
                            out.writeObject(keys);
                        } catch (Exception e) {
                        }
                        byte b[] = bos.toByteArray();
                        try {
                            out.close();
                        } catch (Exception e) {
                        }
                        try {
                            bos.close();
                        } catch (Exception e) {
                        }

                        Wearable.MessageApi.sendMessage(mGoogleApiClient, nodeId, "REGISTER", b)
                                .setResultCallback(new ResultCallback<MessageApi.SendMessageResult>() {
                                    @Override
                                    public void onResult(MessageApi.SendMessageResult sendMessageResult) {
                                        if (!sendMessageResult.getStatus().isSuccess()) {
                                            Log.i("MessageApi", "Failed to send message with status code: "
                                                    + sendMessageResult.getStatus().getStatusCode());
                                        } else if (sendMessageResult.getStatus().isSuccess()) {
                                            Log.i("MessageApi", "onResult successful!");
                                        }
                                    }
                                });

                    }
                });
                builderSingle.show();

            }
        });

        mGoogleApiClient = new GoogleApiClient.Builder(getActivity()).addConnectionCallbacks(this)
                .addOnConnectionFailedListener(
                        new com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener() {
                            @Override
                            public void onConnectionFailed(ConnectionResult result) {
                                Log.i("mGoogleApiClient", "onConnectionFailed: " + result);
                            }
                        })
                // Request access only to the Wearable API
                .addApi(Wearable.API).build();
        mGoogleApiClient.connect();

        /*BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
                
        for(BluetoothDevice bt : pairedDevices)
        Log.i("BluetoothDevice", "pairedDevice: " + bt.toString());*/

        return rootView;

    }

}

From source file:com.eucalyptus.crypto.DefaultCryptoProvider.java

/**
 * @see com.eucalyptus.crypto.CertificateProvider#generateKeyPair()
 *//*  w w  w  .  j  ava 2  s .  co m*/
@Override
public KeyPair generateKeyPair() {
    KeyPairGenerator keyGen = null;
    try {
        EventRecord.caller(DefaultCryptoProvider.class, EventType.GENERATE_KEYPAIR);
        keyGen = KeyPairGenerator.getInstance(KEY_ALGORITHM, PROVIDER);
        SecureRandom random = Crypto.getSecureRandomSupplier().get();
        //TODO: RELEASE: see line:110
        keyGen.initialize(KEY_SIZE, random);
        KeyPair keyPair = keyGen.generateKeyPair();
        return keyPair;
    } catch (Exception e) {
        LOG.fatal(e, e);
        return null;
    }
}

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//from  w ww  .  j a  va2s .com
 */
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.xdi.oxauth.model.crypto.OxAuthCryptoProvider.java

@Override
public JSONObject generateKey(SignatureAlgorithm signatureAlgorithm, Long expirationTime) throws Exception {

    KeyPairGenerator keyGen = null;

    if (signatureAlgorithm == null) {
        throw new RuntimeException("The signature algorithm parameter cannot be null");
    } else if (SignatureAlgorithmFamily.RSA.equals(signatureAlgorithm.getFamily())) {
        keyGen = KeyPairGenerator.getInstance(signatureAlgorithm.getFamily(), "BC");
        keyGen.initialize(2048, new SecureRandom());
    } else if (SignatureAlgorithmFamily.EC.equals(signatureAlgorithm.getFamily())) {
        ECGenParameterSpec eccgen = new ECGenParameterSpec(signatureAlgorithm.getCurve().getAlias());
        keyGen = KeyPairGenerator.getInstance(signatureAlgorithm.getFamily(), "BC");
        keyGen.initialize(eccgen, new SecureRandom());
    } else {/*  w  w  w.  j a v a 2s  . co m*/
        throw new RuntimeException("The provided signature algorithm parameter is not supported");
    }

    // Generate the key
    KeyPair keyPair = keyGen.generateKeyPair();
    java.security.PrivateKey pk = keyPair.getPrivate();

    // Java API requires a certificate chain
    X509Certificate cert = generateV3Certificate(keyPair, dnName, signatureAlgorithm.getAlgorithm(),
            expirationTime);
    X509Certificate[] chain = new X509Certificate[1];
    chain[0] = cert;

    String alias = UUID.randomUUID().toString();

    keyStore.setKeyEntry(alias, pk, keyStoreSecret.toCharArray(), chain);
    FileOutputStream stream = new FileOutputStream(keyStoreFile);
    keyStore.store(stream, keyStoreSecret.toCharArray());

    PublicKey publicKey = keyPair.getPublic();

    JSONObject jsonObject = new JSONObject();
    jsonObject.put(KEY_TYPE, signatureAlgorithm.getFamily());
    jsonObject.put(KEY_ID, alias);
    jsonObject.put(KEY_USE, Use.SIGNATURE);
    jsonObject.put(ALGORITHM, signatureAlgorithm.getName());
    jsonObject.put(EXPIRATION_TIME, expirationTime);
    if (publicKey instanceof RSAPublicKey) {
        RSAPublicKey rsaPublicKey = (RSAPublicKey) publicKey;
        jsonObject.put(MODULUS, Base64Util.base64urlencodeUnsignedBigInt(rsaPublicKey.getModulus()));
        jsonObject.put(EXPONENT, Base64Util.base64urlencodeUnsignedBigInt(rsaPublicKey.getPublicExponent()));
    } else if (publicKey instanceof ECPublicKey) {
        ECPublicKey ecPublicKey = (ECPublicKey) publicKey;
        jsonObject.put(CURVE, signatureAlgorithm.getCurve());
        jsonObject.put(X, Base64Util.base64urlencodeUnsignedBigInt(ecPublicKey.getW().getAffineX()));
        jsonObject.put(Y, Base64Util.base64urlencodeUnsignedBigInt(ecPublicKey.getW().getAffineY()));
    }
    JSONArray x5c = new JSONArray();
    x5c.put(Base64.encodeBase64String(cert.getEncoded()));
    jsonObject.put(CERTIFICATE_CHAIN, x5c);

    return jsonObject;
}

From source file:test.integ.be.agiv.security.IPSTSTest.java

private KeyPair generateKeyPair() throws Exception {
    KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
    SecureRandom random = new SecureRandom();
    keyPairGenerator.initialize(new RSAKeyGenParameterSpec(1024, RSAKeyGenParameterSpec.F4), random);
    KeyPair keyPair = keyPairGenerator.generateKeyPair();
    return keyPair;
}

From source file:org.bedework.util.security.pki.PKITools.java

/**
 * @return RSAKeys//  w  w  w  . j ava 2s . c  om
 * @throws PKIException
 */
public RSAKeys genRSAKeys() throws PKIException {
    RSAKeys keys = new RSAKeys();

    try {
        SecureRandom secureRandom = new SecureRandom();
        secureRandom.nextBytes(new byte[1]);
        KeyPairGenerator rsaKeyGen;

        if (curSchema.pName == null) {
            rsaKeyGen = KeyPairGenerator.getInstance(curSchema.keyFactory);
        } else {
            rsaKeyGen = KeyPairGenerator.getInstance(curSchema.keyFactory, curSchema.pName);
        }

        rsaKeyGen.initialize(1024, secureRandom);

        if (trace()) {
            trace("Generating keys...");
        }

        KeyPair rsaKeyPair = rsaKeyGen.generateKeyPair();

        if (trace()) {
            trace("Saving Public Key...");
        }

        keys.privateKey = rsaKeyPair.getPrivate().getEncoded();
        keys.publicKey = rsaKeyPair.getPublic().getEncoded();

        if (trace()) {
            trace("Done...");
        }

        return keys;
    } catch (Throwable t) {
        throw new PKIException(t);
    }
}

From source file:com.cws.esolutions.security.dao.certmgmt.impl.CertificateManagerImpl.java

/**
 * @see com.cws.esolutions.security.dao.certmgmt.interfaces.ICertificateManager#createCertificateRequest(List, String, int, int)
 *//* w  w  w  . j  a  v a  2  s.  c  o  m*/
public synchronized File createCertificateRequest(final List<String> subjectData, final String storePassword,
        final int validityPeriod, final int keySize) throws CertificateManagementException {
    final String methodName = ICertificateManager.CNAME
            + "#createCertificateRequest(final List<String> subjectData, final String storePassword, final int validityPeriod, final int keySize) throws CertificateManagementException";

    if (DEBUG) {
        DEBUGGER.debug(methodName);
        DEBUGGER.debug("Value: {}", subjectData);
        DEBUGGER.debug("Value: {}", validityPeriod);
        DEBUGGER.debug("Value: {}", keySize);
    }

    final File rootDirectory = certConfig.getRootDirectory();
    final String signatureAlgorithm = certConfig.getSignatureAlgorithm();
    final String certificateAlgorithm = certConfig.getCertificateAlgorithm();
    final File privateKeyDirectory = FileUtils
            .getFile(certConfig.getPrivateKeyDirectory() + "/" + subjectData.get(0));
    final File publicKeyDirectory = FileUtils
            .getFile(certConfig.getPublicKeyDirectory() + "/" + subjectData.get(0));
    final File csrDirectory = FileUtils.getFile(certConfig.getCsrDirectory() + "/" + subjectData.get(0));
    final File storeDirectory = FileUtils.getFile(certConfig.getStoreDirectory() + "/" + subjectData.get(0));
    final X500Name x500Name = new X500Name("CN=" + subjectData.get(0) + ",OU=" + subjectData.get(1) + ",O="
            + subjectData.get(2) + ",L=" + subjectData.get(3) + ",ST=" + subjectData.get(4) + ",C="
            + subjectData.get(5) + ",E=" + subjectData.get(6));

    if (DEBUG) {
        DEBUGGER.debug("rootDirectory: {}", rootDirectory);
        DEBUGGER.debug("signatureAlgorithm: {}", signatureAlgorithm);
        DEBUGGER.debug("certificateAlgorithm: {}", certificateAlgorithm);
        DEBUGGER.debug("privateKeyDirectory: {}", privateKeyDirectory);
        DEBUGGER.debug("publicKeyDirectory: {}", publicKeyDirectory);
        DEBUGGER.debug("csrDirectory: {}", csrDirectory);
        DEBUGGER.debug("storeDirectory: {}", storeDirectory);
        DEBUGGER.debug("x500Name: {}", x500Name);
    }

    File csrFile = null;
    JcaPEMWriter csrPemWriter = null;
    JcaPEMWriter publicKeyWriter = null;
    JcaPEMWriter privateKeyWriter = null;
    FileOutputStream csrFileStream = null;
    FileOutputStream keyStoreStream = null;
    FileOutputStream publicKeyFileStream = null;
    FileOutputStream privateKeyFileStream = null;
    OutputStreamWriter csrFileStreamWriter = null;
    OutputStreamWriter privateKeyStreamWriter = null;
    OutputStreamWriter publicKeyStreamWriter = null;

    try {
        KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
        keyStore.load(null, storePassword.toCharArray());

        if (DEBUG) {
            DEBUGGER.debug("KeyStore: {}", keyStore);
        }

        SecureRandom random = new SecureRandom();
        KeyPairGenerator keyGenerator = KeyPairGenerator.getInstance(certificateAlgorithm);
        keyGenerator.initialize(keySize, random);

        if (DEBUG) {
            DEBUGGER.debug("KeyGenerator: {}", keyGenerator);
        }

        KeyPair keyPair = keyGenerator.generateKeyPair();

        if (DEBUG) {
            DEBUGGER.debug("KeyPair: {}", keyPair);
        }

        if (keyPair != null) {
            final Signature sig = Signature.getInstance(signatureAlgorithm);
            final PrivateKey privateKey = keyPair.getPrivate();
            final PublicKey publicKey = keyPair.getPublic();

            if (DEBUG) {
                DEBUGGER.debug("Signature: {}", sig);
                DEBUGGER.debug("PrivateKey: {}", privateKey);
                DEBUGGER.debug("PublicKey: {}", publicKey);
            }

            sig.initSign(privateKey, random);
            ContentSigner signGen = new JcaContentSignerBuilder(signatureAlgorithm).build(privateKey);

            if (DEBUG) {
                DEBUGGER.debug("ContentSigner: {}", signGen);
            }

            Calendar expiry = Calendar.getInstance();
            expiry.add(Calendar.DAY_OF_YEAR, validityPeriod);

            if (DEBUG) {
                DEBUGGER.debug("Calendar: {}", expiry);
            }

            CertificateFactory certFactory = CertificateFactory.getInstance(certConfig.getCertificateType());

            if (DEBUG) {
                DEBUGGER.debug("CertificateFactory: {}", certFactory);
            }

            X509Certificate[] issuerCert = new X509Certificate[] { (X509Certificate) certFactory
                    .generateCertificate(new FileInputStream(certConfig.getIntermediateCertificateFile())) };

            if (DEBUG) {
                DEBUGGER.debug("X509Certificate[]: {}", (Object) issuerCert);
            }

            keyStore.setCertificateEntry(certConfig.getRootCertificateName(), certFactory.generateCertificate(
                    new FileInputStream(FileUtils.getFile(certConfig.getRootCertificateFile()))));
            keyStore.setCertificateEntry(certConfig.getIntermediateCertificateName(),
                    certFactory.generateCertificate(new FileInputStream(
                            FileUtils.getFile(certConfig.getIntermediateCertificateFile()))));

            PKCS10CertificationRequestBuilder builder = new JcaPKCS10CertificationRequestBuilder(x500Name,
                    publicKey);

            if (DEBUG) {
                DEBUGGER.debug("PKCS10CertificationRequestBuilder: {}", builder);
            }

            PKCS10CertificationRequest csr = builder.build(signGen);

            if (DEBUG) {
                DEBUGGER.debug("PKCS10CertificationRequest: {}", csr);
            }

            // write private key
            File privateKeyFile = FileUtils.getFile(privateKeyDirectory + "/" + subjectData.get(0)
                    + SecurityServiceConstants.PRIVATEKEY_FILE_EXT);

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

            if (!(privateKeyFile.createNewFile())) {
                throw new IOException("Failed to store private file");
            }

            privateKeyFileStream = new FileOutputStream(privateKeyFile);
            privateKeyStreamWriter = new OutputStreamWriter(privateKeyFileStream);

            if (DEBUG) {
                DEBUGGER.debug("privateKeyFileStream: {}", privateKeyFileStream);
                DEBUGGER.debug("privateKeyStreamWriter: {}", privateKeyStreamWriter);
            }

            privateKeyWriter = new JcaPEMWriter(privateKeyStreamWriter);
            privateKeyWriter.writeObject(privateKey);
            privateKeyWriter.flush();
            privateKeyStreamWriter.flush();
            privateKeyFileStream.flush();

            // write public key
            File publicKeyFile = FileUtils.getFile(publicKeyDirectory + "/" + subjectData.get(0)
                    + SecurityServiceConstants.PUBLICKEY_FILE_EXT);

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

            if (!(publicKeyFile.createNewFile())) {
                throw new IOException("Failed to store public key file");
            }

            publicKeyFileStream = new FileOutputStream(publicKeyFile);
            publicKeyStreamWriter = new OutputStreamWriter(publicKeyFileStream);

            if (DEBUG) {
                DEBUGGER.debug("publicKeyFileStream: {}", publicKeyFileStream);
                DEBUGGER.debug("publicKeyStreamWriter: {}", publicKeyStreamWriter);
            }

            publicKeyWriter = new JcaPEMWriter(publicKeyStreamWriter);
            publicKeyWriter.writeObject(publicKey);
            publicKeyWriter.flush();
            publicKeyStreamWriter.flush();
            publicKeyFileStream.flush();

            // write csr
            csrFile = FileUtils
                    .getFile(csrDirectory + "/" + subjectData.get(0) + SecurityServiceConstants.CSR_FILE_EXT);

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

            if (!(csrFile.createNewFile())) {
                throw new IOException("Failed to store CSR file");
            }

            csrFileStream = new FileOutputStream(csrFile);
            csrFileStreamWriter = new OutputStreamWriter(csrFileStream);

            if (DEBUG) {
                DEBUGGER.debug("publicKeyFileStream: {}", publicKeyFileStream);
                DEBUGGER.debug("publicKeyStreamWriter: {}", publicKeyStreamWriter);
            }

            csrPemWriter = new JcaPEMWriter(csrFileStreamWriter);
            csrPemWriter.writeObject(csr);
            csrPemWriter.flush();
            csrFileStreamWriter.flush();
            csrFileStream.flush();

            File keyStoreFile = FileUtils
                    .getFile(storeDirectory + "/" + subjectData.get(0) + "." + KeyStore.getDefaultType());

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

            keyStoreStream = FileUtils.openOutputStream(keyStoreFile);

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

            keyStore.setKeyEntry(subjectData.get(0), (Key) keyPair.getPrivate(), storePassword.toCharArray(),
                    issuerCert);
            keyStore.store(keyStoreStream, storePassword.toCharArray());
            keyStoreStream.flush();

            if (DEBUG) {
                DEBUGGER.debug("KeyStore: {}", keyStore);
            }
        } else {
            throw new CertificateManagementException("Failed to generate keypair. Cannot continue.");
        }
    } catch (FileNotFoundException fnfx) {
        throw new CertificateManagementException(fnfx.getMessage(), fnfx);
    } catch (IOException iox) {
        throw new CertificateManagementException(iox.getMessage(), iox);
    } catch (NoSuchAlgorithmException nsax) {
        throw new CertificateManagementException(nsax.getMessage(), nsax);
    } catch (IllegalStateException isx) {
        throw new CertificateManagementException(isx.getMessage(), isx);
    } catch (InvalidKeyException ikx) {
        throw new CertificateManagementException(ikx.getMessage(), ikx);
    } catch (OperatorCreationException ocx) {
        throw new CertificateManagementException(ocx.getMessage(), ocx);
    } catch (KeyStoreException ksx) {
        throw new CertificateManagementException(ksx.getMessage(), ksx);
    } catch (CertificateException cx) {
        throw new CertificateManagementException(cx.getMessage(), cx);
    } finally {
        if (csrFileStreamWriter != null) {
            IOUtils.closeQuietly(csrFileStreamWriter);
        }

        if (csrFileStream != null) {
            IOUtils.closeQuietly(csrFileStream);
        }

        if (csrPemWriter != null) {
            IOUtils.closeQuietly(csrPemWriter);
        }

        if (publicKeyFileStream != null) {
            IOUtils.closeQuietly(publicKeyFileStream);
        }

        if (publicKeyStreamWriter != null) {
            IOUtils.closeQuietly(publicKeyStreamWriter);
        }

        if (publicKeyWriter != null) {
            IOUtils.closeQuietly(publicKeyWriter);
        }

        if (privateKeyFileStream != null) {
            IOUtils.closeQuietly(privateKeyFileStream);
        }

        if (privateKeyStreamWriter != null) {
            IOUtils.closeQuietly(privateKeyStreamWriter);
        }

        if (privateKeyWriter != null) {
            IOUtils.closeQuietly(privateKeyWriter);
        }

        if (keyStoreStream != null) {
            IOUtils.closeQuietly(keyStoreStream);
        }
    }

    return csrFile;
}