Example usage for java.security.spec X509EncodedKeySpec X509EncodedKeySpec

List of usage examples for java.security.spec X509EncodedKeySpec X509EncodedKeySpec

Introduction

In this page you can find the example usage for java.security.spec X509EncodedKeySpec X509EncodedKeySpec.

Prototype

public X509EncodedKeySpec(byte[] encodedKey) 

Source Link

Document

Creates a new X509EncodedKeySpec with the given encoded key.

Usage

From source file:jef.tools.security.EncrypterUtil.java

/**
 * x509/*w ww . j  a  v  a 2s  .  c  o  m*/
 * 
 * @param f
 * @param algom
 *            ? getSupportedAlgorithmName (AlgorithmType.KeyFactory)
 * @param isPublic
 *            true?false??
 * @return
 */
public static Key loadX509Key(File f, String algom, boolean isPublic) {
    try {
        byte[] keyData = IOUtils.toByteArray(f);
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyData);
        KeyFactory keyFactory = KeyFactory.getInstance(algom);
        Key result = (isPublic) ? keyFactory.generatePublic(keySpec) : keyFactory.generatePrivate(keySpec);
        return result;
    } catch (IOException e) {
        throw new RuntimeException(e);
    } catch (GeneralSecurityException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.wso2telco.gsma.authenticators.OpCoCompositeAuthenticator.java

/**
 * Read public key from file.//w  w  w  .  j a  v a2s .com
 *
 * @param fileName the file name
 * @return the public key
 * @throws AuthenticationFailedException the authentication failed exception
 */
private PublicKey readPublicKeyFromFile(String fileName) throws AuthenticationFailedException {
    try {
        String publicK = readStringKey(fileName);
        byte[] keyBytes = Base64.decodeBase64(publicK.getBytes());
        ;
        X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        return keyFactory.generatePublic(spec);
    } catch (Exception e) {
        throw new AuthenticationFailedException(
                "Authentication Failed since reading public key from file failed.");
    }
}

From source file:com.torresbueno.RSAEncryptionDecryptionUtil.java

/**
 * Get a public key object from a string.
 * @param publicKey - A Base64 encoded string with a X509 encoded key spec.
 * @return a standard public key object.
 * @throws NoSuchAlgorithmException/*from  w w w  . j a va2s. co m*/
 * @throws InvalidKeySpecException
 */
public PublicKey getPublicKeyFromString(String publicKey)
        throws NoSuchAlgorithmException, InvalidKeySpecException, IOException {
    byte[] encodedPb = Base64.decodeBase64(publicKey);
    X509EncodedKeySpec keySpecPb = new X509EncodedKeySpec(encodedPb);
    return getKeyFactoryInstance().generatePublic(keySpecPb);
}

From source file:org.openhab.binding.loxone.internal.core.LxWsSecurityToken.java

private Cipher getRsaCipher(String key) {
    try {//  ww  w. j a  va2s  . co  m
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        String keyString = key.replace("-----BEGIN CERTIFICATE-----", "").replace("-----END CERTIFICATE-----",
                "");
        byte[] keyData = Base64.getDecoder().decode(keyString);
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyData);
        PublicKey publicKey = keyFactory.generatePublic(keySpec);
        logger.debug("[{}] Miniserver public key: {}", debugId, publicKey);
        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        cipher.init(Cipher.PUBLIC_KEY, publicKey);
        logger.debug("[{}] Initialized RSA public key cipher", debugId);
        return cipher;
    } catch (InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException
            | InvalidKeySpecException e) {
        setError(LxOfflineReason.INTERNAL_ERROR, "Exception enabling RSA cipher: " + e.getMessage());
        return null;
    }
}

From source file:net.sourceforge.msscodefactory.cfasterisk.v2_4.CFAsteriskSMWar.CFAsteriskSMWarAddDeviceHtml.java

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 *///w w w.  j a va  2s  . c  om
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    final String S_ProcName = "doPost";

    ICFAsteriskSchemaObj schemaObj;
    HttpSession sess = request.getSession(false);
    if (sess == null) {
        sess = request.getSession(true);
        schemaObj = new CFAsteriskSchemaPooledObj();
        sess.setAttribute("SchemaObj", schemaObj);
    } else {
        schemaObj = (ICFAsteriskSchemaObj) sess.getAttribute("SchemaObj");
        if (schemaObj == null) {
            response.sendRedirect("CFAsteriskSMWarLoginHtml");
            return;
        }
    }

    CFSecurityAuthorization auth = schemaObj.getAuthorization();
    if (auth == null) {
        response.sendRedirect("CFAsteriskSMWarLoginHtml");
        return;
    }

    ICFSecuritySecUserObj secUser = null;
    ICFSecurityClusterObj secCluster = null;
    String clusterDescription = "";

    ICFAsteriskSchema dbSchema = null;
    try {
        dbSchema = (ICFAsteriskSchema) CFAsteriskSchemaPool.getSchemaPool().getInstance();
        schemaObj.setBackingStore(dbSchema);
        schemaObj.beginTransaction();

        secUser = schemaObj.getSecUserTableObj().readSecUserByIdIdx(auth.getSecUserId());

        secCluster = schemaObj.getClusterTableObj().readClusterByIdIdx(auth.getSecClusterId());
        if (secCluster == null) {
            throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0,
                    "secCluster");
        }
        clusterDescription = secCluster.getRequiredDescription();

        String deviceName = request.getParameter("DeviceName");
        if ((deviceName == null) || (deviceName.length() <= 0)) {
            response.setContentType("text/html");
            PrintWriter out = response.getWriter();
            out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\">");
            out.println("<HTML>");
            out.println("<BODY>");
            out.println("<form method=\"post\" formaction=\"CFAsteriskSMWarAddDeviceHtml\">");
            out.println("<H1 style=\"text-align:center\">" + clusterDescription + " Security Manager</H1>");
            out.println("<H2 style=\"text-align:center\">ERROR</H2>");
            out.println("<p style=\"text-align:center\">Device Name must be specified.");
            out.println("<H2 style=\"text-align:center\">Add new device for "
                    + secUser.getRequiredEMailAddress() + "</H2>");
            out.println("<p>");
            out.println("<table style=\"width:90%\">");
            out.println(
                    "<tr><th style=\"text-align:left\">Device Name:</th><td><input type=\"text\" name=\"DeviceName\"/></td></tr>");
            out.println(
                    "<tr><th style=\"text-align:left\">Public Key:</th><td><textarea name=\"PublicKey\" cols=\"60\" rows=\"10\"></textarea></td></tr>");
            out.println("</table>");
            out.println(
                    "<p style=\"text-align:center\"><button type=\"submit\" name=\"Ok\"\">Add Device</button>&nbsp;&nbsp;&nbsp;&nbsp;<button type=\"button\" name=\"Cancel\"\" onclick=\"window.location.href='CFAsteriskSMWarSecurityMainHtml'\">Cancel</button>");
            out.println("</form>");
            out.println("</BODY>");
            out.println("</HTML>");
            return;
        }

        ICFSecuritySecDeviceObj secDev = schemaObj.getSecDeviceTableObj()
                .readSecDeviceByIdIdx(secUser.getRequiredSecUserId(), deviceName);
        if (secDev != null) {
            response.setContentType("text/html");
            PrintWriter out = response.getWriter();
            out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\">");
            out.println("<HTML>");
            out.println("<BODY>");
            out.println("<form method=\"post\" formaction=\"CFAsteriskSMWarAddDeviceHtml\">");
            out.println("<H1 style=\"text-align:center\">" + clusterDescription + " Security Manager</H1>");
            out.println("<H2 style=\"text-align:center\">ERROR</H2>");
            out.println("<p style=\"text-align:center\">Device Name \"" + deviceName + "\" already in use.");
            out.println("<H2 style=\"text-align:center\">Add new device for "
                    + secUser.getRequiredEMailAddress() + "</H2>");
            out.println("<p>");
            out.println("<table style=\"width:90%\">");
            out.println(
                    "<tr><th style=\"text-align:left\">Device Name:</th><td><input type=\"text\" name=\"DeviceName\"/></td></tr>");
            out.println(
                    "<tr><th style=\"text-align:left\">Public Key:</th><td><textarea name=\"PublicKey\" cols=\"60\" rows=\"10\"></textarea></td></tr>");
            out.println("</table>");
            out.println(
                    "<p style=\"text-align:center\"><button type=\"submit\" name=\"Ok\"\">Add Device</button>&nbsp;&nbsp;&nbsp;&nbsp;<button type=\"button\" name=\"Cancel\"\" onclick=\"window.location.href='CFAsteriskSMWarSecurityMainHtml'\">Cancel</button>");
            out.println("</form>");
            out.println("</BODY>");
            out.println("</HTML>");
            return;
        }

        String publicKey = request.getParameter("PublicKey");
        if ((publicKey == null) || (publicKey.length() <= 0)) {
            response.setContentType("text/html");
            PrintWriter out = response.getWriter();
            out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\">");
            out.println("<HTML>");
            out.println("<BODY>");
            out.println("<form method=\"post\" formaction=\"CFAsteriskSMWarAddDeviceHtml\">");
            out.println("<H1 style=\"text-align:center\">" + clusterDescription + " Security Manager</H1>");
            out.println("<p style=\"text-align:center\">Public Key must be specified.");
            out.println("<H2 style=\"text-align:center\">Add new device for "
                    + secUser.getRequiredEMailAddress() + "</H2>");
            out.println("<p>");
            out.println("<table style=\"width:90%\">");
            out.println(
                    "<tr><th style=\"text-align:left\">Device Name:</th><td><input type=\"text\" name=\"DeviceName\"/></td></tr>");
            out.println(
                    "<tr><th style=\"text-align:left\">Public Key:</th><td><textarea name=\"PublicKey\" cols=\"60\" rows=\"10\"></textarea></td></tr>");
            out.println("</table>");
            out.println(
                    "<p style=\"text-align:center\"><button type=\"submit\" name=\"Ok\"\">Add Device</button>&nbsp;&nbsp;&nbsp;&nbsp;<button type=\"button\" name=\"Cancel\"\" onclick=\"window.location.href='CFAsteriskSMWarSecurityMainHtml'\">Cancel</button>");
            out.println("</form>");
            out.println("</BODY>");
            out.println("</HTML>");
            return;
        }

        byte wrapped[] = Base64.decodeBase64(publicKey);

        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(wrapped);
        KeyFactory kf = KeyFactory.getInstance("RSA");
        if (kf == null) {
            throw CFLib.getDefaultExceptionFactory().newNullArgumentException(getClass(), S_ProcName, 0, "kf");
        }

        PublicKey decodedPublicKey = kf.generatePublic(x509KeySpec);
        if (decodedPublicKey == null) {
            response.setContentType("text/html");
            PrintWriter out = response.getWriter();
            out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\">");
            out.println("<HTML>");
            out.println("<BODY>");
            out.println("<form method=\"post\" formaction=\"CFAsteriskSMWarAddDeviceHtml\">");
            out.println("<H1 style=\"text-align:center\">" + clusterDescription + " Security Manager</H1>");
            out.println("<p style=\"text-align:center\">Public Key must be a valid RSA 2048 Key.");
            out.println("<H2 style=\"text-align:center\">Add new device for "
                    + secUser.getRequiredEMailAddress() + "</H2>");
            out.println("<p>");
            out.println("<table style=\"width:90%\">");
            out.println(
                    "<tr><th style=\"text-align:left\">Device Name:</th><td><input type=\"text\" name=\"DeviceName\"/></td></tr>");
            out.println(
                    "<tr><th style=\"text-align:left\">Public Key:</th><td><textarea name=\"PublicKey\" cols=\"60\" rows=\"10\"></textarea></td></tr>");
            out.println("</table>");
            out.println(
                    "<p style=\"text-align:center\"><button type=\"submit\" name=\"Ok\"\">Add Device</button>&nbsp;&nbsp;&nbsp;&nbsp;<button type=\"button\" name=\"Cancel\"\" onclick=\"window.location.href='CFAsteriskSMWarSecurityMainHtml'\">Cancel</button>");
            out.println("</form>");
            out.println("</BODY>");
            out.println("</HTML>");
            return;
        }

        ICFSecurityClusterObj systemCluster = schemaObj.getClusterTableObj()
                .readClusterByUDomainNameIdx("system");
        ICFSecurityTenantObj systemTenant = schemaObj.getTenantTableObj()
                .readTenantByUNameIdx(systemCluster.getRequiredId(), "system");
        ICFSecuritySecUserObj systemUser = schemaObj.getSecUserTableObj().readSecUserByULoginIdx("system");
        ICFSecuritySecSessionObj systemSession = schemaObj.getSecSessionTableObj().newInstance();
        ICFSecuritySecSessionEditObj editSystemSession = (ICFSecuritySecSessionEditObj) systemSession
                .beginEdit();
        editSystemSession.setRequiredContainerSecUser(systemUser);
        editSystemSession.setRequiredStart(Calendar.getInstance());
        systemSession = editSystemSession.create();
        editSystemSession.endEdit();

        CFSecurityAuthorization secAuth = new CFSecurityAuthorization();
        secAuth.setSecCluster(systemCluster);
        secAuth.setSecTenant(systemTenant);
        secAuth.setSecSession(systemSession);
        schemaObj.setAuthorization(secAuth);

        secDev = schemaObj.getSecDeviceTableObj().newInstance();
        ICFSecuritySecDeviceEditObj editDev = secDev.beginEdit();
        editDev.setRequiredContainerSecUser(secUser);
        editDev.setRequiredDevName(deviceName);
        editDev.setOptionalPubKey(publicKey);
        secDev = editDev.create();
        editDev.endEdit();

        if (null == secUser.getOptionalLookupDefDev()) {
            ICFSecuritySecUserEditObj editSecUser = secUser.beginEdit();
            editSecUser.setOptionalLookupDefDev(secDev);
            editSecUser.update();
            editSecUser.endEdit();
        }

        editSystemSession = (ICFSecuritySecSessionEditObj) systemSession.beginEdit();
        editSystemSession.setOptionalFinish(Calendar.getInstance());
        editSystemSession.update();
        editSystemSession.endEdit();

        schemaObj.commit();

        schemaObj.setAuthorization(auth);

        response.sendRedirect("CFAsteriskSMWarSecurityMainHtml");

    } catch (InvalidKeySpecException e) {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\">");
        out.println("<HTML>");
        out.println("<BODY>");
        out.println("<form method=\"post\" formaction=\"CFAsteriskSMWarAddDeviceHtml\">");
        out.println("<H1 style=\"text-align:center\">" + clusterDescription + " Security Manager</H1>");
        out.println("<p style=\"text-align:center\">Public Key must be a valid RSA 2048 Key.");
        out.println("<H2 style=\"text-align:center\">Add new device for " + secUser.getRequiredEMailAddress()
                + "</H2>");
        out.println("<p>");
        out.println("<table style=\"width:90%\">");
        out.println(
                "<tr><th style=\"text-align:left\">Device Name:</th><td><input type=\"text\" name=\"DeviceName\"/></td></tr>");
        out.println(
                "<tr><th style=\"text-align:left\">Public Key:</th><td><textarea name=\"PublicKey\" cols=\"60\" rows=\"10\"></textarea></td></tr>");
        out.println("</table>");
        out.println(
                "<p style=\"text-align:center\"><button type=\"submit\" name=\"Ok\"\">Add Device</button>&nbsp;&nbsp;&nbsp;&nbsp;<button type=\"button\" name=\"Cancel\"\" onclick=\"window.location.href='CFAsteriskSMWarSecurityMainHtml'\">Cancel</button>");
        out.println("</form>");
        out.println("</BODY>");
        out.println("</HTML>");
    } catch (NoSuchAlgorithmException e) {
        throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), S_ProcName,
                "Caught NoSuchAlgorithmException -- " + e.getMessage(), e);
    } catch (RuntimeException e) {
        throw CFLib.getDefaultExceptionFactory().newRuntimeException(getClass(), S_ProcName,
                "Caught RuntimeException -- " + e.getMessage(), e);
    } finally {
        schemaObj.setAuthorization(auth);
        if (dbSchema != null) {
            try {
                if (schemaObj.isTransactionOpen()) {
                    schemaObj.rollback();
                }
            } catch (RuntimeException e) {
            }
            schemaObj.setBackingStore(null);
            CFAsteriskSchemaPool.getSchemaPool().releaseInstance(dbSchema);
        }
    }
}

From source file:org.opendatakit.survey.android.utilities.EncryptionUtils.java

/**
 * Retrieve the encryption information for this row.
 * /*  w ww .j  a  va  2 s.c om*/
 * @param appName
 * @param tableId
 * @param xmlBase64RsaPublicKey
 * @param instanceId
 * @return
 */
public static EncryptedFormInformation getEncryptedFormInformation(String appName, String tableId,
        String xmlBase64RsaPublicKey, String instanceId) {

    // fetch the form information
    String base64RsaPublicKey = xmlBase64RsaPublicKey;
    PublicKey pk;
    Base64Wrapper wrapper;

    if (base64RsaPublicKey == null || base64RsaPublicKey.length() == 0) {
        return null; // this is legitimately not an encrypted form
    }

    // submission must have an OpenRosa metadata block with a non-null
    // instanceID value.
    if (instanceId == null) {
        WebLogger.getLogger(appName).e(t, "No OpenRosa metadata block or no instanceId defined in that block");
        return null;
    }

    int version = android.os.Build.VERSION.SDK_INT;
    if (version < 8) {
        WebLogger.getLogger(appName).e(t, "Phone does not support encryption.");
        return null; // save unencrypted
    }

    // this constructor will throw an exception if we are not
    // running on version 8 or above (if Base64 is not found).
    try {
        wrapper = new Base64Wrapper();
    } catch (ClassNotFoundException e) {
        WebLogger.getLogger(appName).e(t, "Phone does not have Base64 class but API level is " + version);
        WebLogger.getLogger(appName).printStackTrace(e);
        return null; // save unencrypted
    }

    // OK -- Base64 decode (requires API Version 8 or higher)
    byte[] publicKey = wrapper.decode(base64RsaPublicKey);
    X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(publicKey);
    KeyFactory kf;
    try {
        kf = KeyFactory.getInstance(RSA_ALGORITHM);
    } catch (NoSuchAlgorithmException e) {
        WebLogger.getLogger(appName).e(t, "Phone does not support RSA encryption.");
        WebLogger.getLogger(appName).printStackTrace(e);
        return null;
    }
    try {
        pk = kf.generatePublic(publicKeySpec);
    } catch (InvalidKeySpecException e) {
        WebLogger.getLogger(appName).printStackTrace(e);
        WebLogger.getLogger(appName).e(t, "Invalid RSA public key.");
        return null;
    }
    return new EncryptedFormInformation(appName, tableId, xmlBase64RsaPublicKey, instanceId, pk, wrapper);
}

From source file:com.trsst.Common.java

/**
 * Converts a X509-encoded EC key to a PublicKey.
 *//*w ww.j a va  2 s.com*/
public static PublicKey toPublicKeyFromX509(String stored) throws GeneralSecurityException {
    KeyFactory factory = KeyFactory.getInstance("EC");
    byte[] data = Base64.decodeBase64(stored);
    X509EncodedKeySpec spec = new X509EncodedKeySpec(data);
    return factory.generatePublic(spec);

}

From source file:org.opendatakit.services.utilities.EncryptionUtils.java

/**
 * Retrieve the encryption information for this row.
 * //w  w  w .  ja  v  a 2  s .c om
 * @param appName
 * @param tableId
 * @param xmlBase64RsaPublicKey
 * @param instanceId
 * @return
 */
public static EncryptedFormInformation getEncryptedFormInformation(String appName, String tableId,
        String xmlBase64RsaPublicKey, String instanceId) {

    // fetch the form information
    String base64RsaPublicKey = xmlBase64RsaPublicKey;
    PublicKey pk;
    Base64Wrapper wrapper;

    if (base64RsaPublicKey == null || base64RsaPublicKey.length() == 0) {
        return null; // this is legitimately not an encrypted form
    }

    // submission must have an OpenRosa metadata block with a non-null
    // instanceID value.
    if (instanceId == null) {
        WebLogger.getLogger(appName).e(t, "No OpenRosa metadata block or no instanceId defined in that block");
        return null;
    }

    int version = android.os.Build.VERSION.SDK_INT;
    if (version < 8) {
        WebLogger.getLogger(appName).e(t, "Phone does not support encryption.");
        return null; // save unencrypted
    }

    // this constructor will throw an exception if we are not
    // running on version 8 or above (if Base64 is not found).
    try {
        wrapper = new Base64Wrapper(appName);
    } catch (ClassNotFoundException e) {
        WebLogger.getLogger(appName).e(t, "Phone does not have Base64 class but API level is " + version);
        WebLogger.getLogger(appName).printStackTrace(e);
        return null; // save unencrypted
    }

    // OK -- Base64 decode (requires API Version 8 or higher)
    byte[] publicKey = wrapper.decode(base64RsaPublicKey);
    X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(publicKey);
    KeyFactory kf;
    try {
        kf = KeyFactory.getInstance(RSA_ALGORITHM);
    } catch (NoSuchAlgorithmException e) {
        WebLogger.getLogger(appName).e(t, "Phone does not support RSA encryption.");
        WebLogger.getLogger(appName).printStackTrace(e);
        return null;
    }
    try {
        pk = kf.generatePublic(publicKeySpec);
    } catch (InvalidKeySpecException e) {
        WebLogger.getLogger(appName).printStackTrace(e);
        WebLogger.getLogger(appName).e(t, "Invalid RSA public key.");
        return null;
    }
    return new EncryptedFormInformation(appName, tableId, xmlBase64RsaPublicKey, instanceId, pk, wrapper);
}

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

/**
 * Creates a new instance of {@code PublicKey}. Convert the string formatted
 * public key into {@code PublicKey} type.
 * //from w w  w  .  j a v  a2s  .  c om
 * @param key
 *            the string formated public key.
 * @return the new {@code PublicKey} instance.
 * @throws NoSuchAlgorithmException
 *             if no provider provides the requested algorithm.
 * @throws InvalidKeyException
 *             if the specified keySpec is invalid.
 * 
 */
// Converting the Server Public key format to Java compatible from
private PublicKey getServerPublicKey(String key) throws NoSuchAlgorithmException, InvalidKeySpecException {

    // Converting the Server Public key format to Java compatible from
    key = key.replace("-----BEGIN PUBLIC KEY-----\n", "");
    key = key.replace("\n-----END PUBLIC KEY-----", "");

    // Creating the public key from the string format received from server
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    PublicKey serverPublicKeySig = keyFactory
            .generatePublic(new X509EncodedKeySpec(Base64.decode(key.toString(), Base64.DEFAULT)));
    return serverPublicKeySig;
}

From source file:com.intuit.s3encrypt.S3Encrypt.java

public static void saveKeyPair(String filename, KeyPair keyPair) throws IOException {
    PublicKey publicKey = keyPair.getPublic();
    PrivateKey privateKey = keyPair.getPrivate();

    // Save public key to file.
    X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(publicKey.getEncoded());
    FileOutputStream keyfos = new FileOutputStream(filename + ".pub");
    keyfos.write(x509EncodedKeySpec.getEncoded());
    keyfos.close();/*from   w w  w. j  a v a2  s.c om*/

    // Save private key to file.
    PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(privateKey.getEncoded());
    keyfos = new FileOutputStream(filename);
    keyfos.write(pkcs8EncodedKeySpec.getEncoded());
    keyfos.close();

}