Can I create a cert with the Java API only?

I'm building a client/server app that will use SSL and client certs for authenticating the client to the server. I'd like for each user to be able to create a keypair and an associated self-signed cert that they can provide to the server through some other means, to be included in the server's trust store.
I know how to generate a key pair with an associated self-signed cert via keytool, but I'd prefer to do it directly with the Java APIs. From looking at the Javadocs, I can see how to generate a keypair and how to generate a cert object using an encoded representation of the cert ( e.g. java.security.cert.CertificateFactory.generateCertififcate() ).
But how can I create this encoded representation of the certificate that I need to provide to generateCertificate()? I could do it with keytool and export the cert to a file, but is there no Java API that can accomplish the same thing?
I want to avoid having the user use keytool. Perhaps I can execute the appropriate keytool command from the java code, using Runtime.exec(), but again a pure java API approach would be better. Is there a way to do this all with Java? If not, is executing keytool via Runtime.exec() the best approach?

There is no solution available with the JDK. It's rather deficient wrt certificate management, as java.security.cert.CertificateFactory is a factory that only deals in re-treads. That is, it doesn't really create certs. Rather it converts a DER encoded byte stream into a Java Certificate object.
I found two ways to create a certificate from scratch. The first one is an all Java implementation of what keytool does. The second is to use Runtime.exec(), which you don't want to do.
1. Use BouncyCastle, a free open source cryptography library that you can find here: http://www.bouncycastle.org/ There are examples in the documentation that show you how to do just about anything you want to do. I chose not to use it, because my need was satisfied with a lighter approach, and I didn't want to add a dependency unnecessarily. Also Bouncy Castle requires you to use a distinct version with each version of the JDK. So if I wanted my app to work with JDK 1.4 or later, I would have to actually create three different versions, each bundled with the version of BouncyCastle that matches the version of the target JDK.
2. I created my cert by using Runtime.exec() to invoke the keytool program, which you say you don't want to do. This seemed like a hack to me, so I tried to avoid it; but actually I think it was the better choice for me, and I've been happy with how it works. It may have some backward compatibility issues. I tested it on Windows XP and Mac 10.4.9 with JDK 1.6. Some keytool arguments changed with JDK versions, but I think they maintained backward compatibility. I haven't checked it, and I don't know if I'm using the later or earlier version of the keytool arguments.
Here's my code.
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import javax.security.auth.x500.X500Principal;
import javax.swing.JOptionPane;
public class CreateCertDemo {
     private static void createKey() throws IOException,
      KeyStoreException, NoSuchAlgorithmException, CertificateException{
     X500Principal principal;
     String storeName = ".keystore";
     String alias = "keyAlias";
     principal = PrincipalInfo.getInstance().getPrincipal();
     String validity = "10000";
     String[] cmd = new String[]{ "keytool", "-genKey", "-alias", alias, "-keyalg", "RSA",
        "-sigalg", "SHA256WithRSA", "-dname", principal.getName(), "-validity",
        validity, "-keypass", "keyPassword", "-keystore",
        storeName, "-storepass", "storePassword"};
     int result = doExecCommand(cmd);
     if (result != 0){
          String msg = "An error occured while trying to generate\n" +
                              "the private key. The error code returned by\n" +
                              "the keytool command was " + result + ".";
          JOptionPane.showMessageDialog(null, msg, "Key Generation Error", JOptionPane.WARNING_MESSAGE);
     KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
     ks.load(new FileInputStream(storeName), "storePassword".toCharArray());
        //return ks from the method if needed
public static int doExecCommand(String[] cmd) throws IOException{
          Runtime r = Runtime.getRuntime();
          Process p = null;
          p = r.exec(cmd);
          FileOutputStream outFos = null;
          FileOutputStream errFos = null;
          File out = new File("keytool_exe.out");
          out.createNewFile();
          File err = new File("keytool_exe.err");
          err.createNewFile();
          outFos = new FileOutputStream(out);
          errFos = new FileOutputStream(err);
          StreamSink outSink = new StreamSink(p.getInputStream(),"Output", outFos );
          StreamSink errSink = new StreamSink(p.getErrorStream(),"Error", errFos );
          outSink.start();
          errSink.start();
          int exitVal = 0;;
          try {
               exitVal = p.waitFor();
          } catch (InterruptedException e) {
               return -100;
          System.out.println (exitVal==0 ?  "certificate created" :
               "A problem occured during certificate creation");
          outFos.flush();
          outFos.close();
          errFos.flush();
          errFos.close();
          out.delete();
          err.delete();
          return exitVal;
     public static void main (String[] args) throws
          KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException{
          createKey();
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
//Adapted from Mike Daconta's StreamGobbler at
//http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html?page=4
public class StreamSink extends Thread
    InputStream is;
    String type;
    OutputStream os;
    public StreamSink(InputStream is, String type)
        this(is, type, null);
    public StreamSink(InputStream is, String type, OutputStream redirect)
        this.is = is;
        this.type = type;
        this.os = redirect;
    public void run()
        try
            PrintWriter pw = null;
            if (os != null)
                pw = new PrintWriter(os);
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);
            String line=null;
            while ( (line = br.readLine()) != null)
                if (pw != null)
                    pw.println(line);
                System.out.println(type + ">" + line);   
            if (pw != null)
                pw.flush();
        } catch (IOException ioe)
            ioe.printStackTrace(); 
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.security.auth.x500.X500Principal;
public class PrincipalInfo {
     private static String defInfoString = "CN=Name, O=Organization";
     //make it a singleton.
     private static class PrincipalInfoHolder{
          private static PrincipalInfo instance = new PrincipalInfo();
     public static PrincipalInfo getInstance(){
          return PrincipalInfoHolder.instance;
     private PrincipalInfo(){
     public X500Principal getPrincipal(){
          String fileName = "principal.der";
          File file = new File(fileName);
          if (file.exists()){
               try {
                    return new X500Principal(new FileInputStream(file));
               } catch (FileNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    return null;
          }else{
               return new X500Principal(defInfoString);
     public void savePrincipal(X500Principal p) throws IOException{
          FileOutputStream fos = new FileOutputStream("principal.der");
          fos.write(p.getEncoded());
          fos.close();
}Message was edited by:
MidnightJava
Message was edited by:
MidnightJava

Similar Messages

  • How can I create a new User with the Java API like OIDDAS do?

    Hello,
    I'm currently working on an BPEL based process. And i need to create an OCS user. So far I can create an user in the OID. But I cant find any documentation about given this user an email account,calendar and content function etc.
    Did anybody know if there are some OIDDAS Webservices? Or did anybody know how to do this using the Java APIs?

    You are asking about a Database User I hope.
    You can look into the Oracle 8i Documentation and find various privillages listed.
    In particular, you may find:
    Chapter 27 Privileges, Roles, and Security Policies
    an intresting chapter.
    You may want to do this with the various tools included with 8i - including the
    Oracle DBA Studio - expand the Security node and you can create USERS and ROLES.
    Or use SQL*Plus. To create a
    user / password named John / Smith, you would login to SQL*Plus as System/manager (or other) and type in:
    Create user John identified by Smith;
    Grant CONNECT to John;
    Grant SELECT ANY TABLE to John;
    commit;
    There is much more you can do
    depending on your needs.
    Please read the documentation.
    -John
    null

  • Help with the Java API

    Search on an attribute of the custom class using the Java
    API.
    I taking one of the provided classes, a "VCARD Street Address."
    Inserted the XML for it. Added some documents of that class.
    Then I set City="Charlotte." Double-checked it in the database with
    sql*plus -- I see records matching city=charlotte.
    However, searching using the Java API, I comes up blank. Using the
    following classes:
    attributequalification
    searchclause
    search
    *************Query Tester.java************
    import java.util.*;
    import java.io.*;
    import java.text.*;
    import java.util.zip.*;
    import java.rmi.RemoteException;
    // Runner Specific Imports
    import oracle.ifs.common.*;
    import oracle.ifs.utils.common.*;
    import oracle.ifs.beans.*;
    import oracle.ifs.search.*;
    import oracle.ifs.adk.filesystem.IfsFileSystem;
    public class QueryTester {
    protected SearchClause getAttributeSearchClause(SearchClause
    searchClause) throws IfsException{
    try {
    AttributeQualification attributeQualification = new
    AttributeQualification();
    attributeQualification.setAttribute("VCARDSTREETADDRESS","CITY");
    attributeQualification.setOperatorType(AttributeQualification.LIKE);
    attributeQualification.setValue("C%");
    searchClause = new
    SearchClause(searchClause,attributeQualification, searchClause.AND);
    return searchClause;
    catch (RuntimeException ex) {
    String exceptionText = "RuntimeException in
    getAttributeSearchClause(). Nested Exception:" + ex;
    System.out.println (exceptionText);
    throw ex;
    catch (IfsException ex) {
    String exceptionText = "IfsException in
    getAttributeSearchClause(). Nested Exception:" + ex;
    System.out.println (exceptionText);
    throw ex;
    protected SearchClassSpecification getSearchClassSpecification()
    throws IfsException {
    try {
    String[] searchClasses = {"DOCUMENT","CONTENTOBJECT",
    "VCARDSTREETADDRESS"};
    SearchClassSpecification searchClassSpecification = new
    SearchClassSpecification(searchClasses);
    //searchClassSpecification.addResultClass("DOCUMENT");
    searchClassSpecification.addResultClass("VCARDSTREETADDRESS");
    return searchClassSpecification;
    catch (IfsException ex) {
    String exceptionText = "Error in getSearchClassSpecification :
    " + ex;
    System.out.println (exceptionText);
    throw ex;
    public static void main (String[] args) {
    try {
    QueryTester qt = new QueryTester();
    System.out.println ("Logging in.");
    IfsFileSystem IfsAPI = new IfsFileSystem("cvars", "cvars",
    "docrunner", "ifssys");
    System.out.println ("Got this far.");
    LibrarySession libSession = IfsAPI.getLibrarySession();
    // For every document that it a content object we want to
    search
    JoinQualification joinQualification = new JoinQualification();
    joinQualification.setLeftAttribute("DOCUMENT",
    "CONTENTOBJECT");
    joinQualification.setRightAttribute("CONTENTOBJECT", null);
    oracle.ifs.beans.Folder searchFolderObject = null;
    searchFolderObject = libSession.getRootFolder();
    FolderRestrictQualification folderRestrictQualification = new
    FolderRestrictQualification();
    folderRestrictQualification.setStartFolder(searchFolderObject);
    SearchClause searchClause = null;
    SearchClause baseSearchClause = new
    SearchClause(joinQualification, folderRestrictQualification,
    SearchClause.AND);
    searchClause = qt.getAttributeSearchClause(baseSearchClause);
    AttributeSearchSpecification attribSearchSpecification = new
    AttributeSearchSpecification();
    attribSearchSpecification.setSearchClassSpecification(qt.getSearchClassSpecification());
    System.out.println ("Set the Search Class Specificiation.");
    attribSearchSpecification.setSearchQualification(searchClause);
    Search attributeSearch = new Search(libSession,
    attribSearchSpecification);
    System.out.println ("About to open Attribute Search . ");
    attributeSearch.open();
    System.out.println ("Opened the search");
    SearchResultObject[] sro = attributeSearch.getItems();
    if (sro!=null)
    System.out.println ("Results : " + sro.length);
    libSession.disconnect();
    catch (IfsException ifsex) { System.out.println (ifsex); }
    catch (RuntimeException rux) { System.out.println (rux); }
    null

    You said 'Then I set City="Charlotte." Double-checked it in the database with
    sql*plus -- I see records matching city=charlotte.'
    Your description uses both 'Charlotte' and 'charlotte'.
    Does the word 'Charlotte' appear in the database in all lower case or mixed-case?
    null

  • Newbie :  How can i create 2 users with the same name on diff domain name ?

    I have two domains on my server
    exemple1.com
    exemple2.com
    and i want to create one user for each domain with the same name
    [email protected] and [email protected]
    curently i can create one user, and it's the same user for both domains :-/
    how ?
    thanks
    Hète

    I must say. I am equally curious about this. i've played a lot in Communigate and it is easy to do there but how does one do this in apple mail?

  • How can I create a universe with the BO repository tables?

    Hi. I need make a universe with the BO repository tables, in order to get user information .
    But, when I try to insert tables in designer, using a new conecction to BO repository. I can't see tables.
    Someone can help me?

    The CMS repository is organized into both physical and virtual tables. Only the CMS can access the virtual tables, therefore you cannot create a universe on the CMS repository. You can access the CMS repository information through the Enterprise SDK.
    https://www.sdn.sap.com/irj/boc/businessobjects-sdklibrary

  • How can I create a file with the excel file type?

    I work with forms 4.5 and I could create "TEXT_IO.FILE_TYPE", but with this I make a I/O TEXT file not a file with the characteristics from a excel file! Can somebody help me please?!?!?
    Best regards,
    Chris from Portugal

    The extension file must be 'CSV' and not 'CVS'. It's better to separate your items by a ';'
    The HOST command you have to execute after creating the file it's HOST(EXEL_PATH SPACE YOUR_FILE) OR Open the DOS PROMPT and type: Exel your_file_name.

  • How can I create a sample with the Flex data?

    Hi mates, I'm thinking about doing some stutter vocals with the ultrabeat so I've got a vocal and I have flexed it in time so it fits well on the song's tempo, the problem is that when I create an audio file of the part of the vocal I want to use on my ultrabeat, it creates an audio file that's not fitted in time.
    How can I create the audio file fitted in time?with the flex info?
    Thanks so much!

    psikonetik wrote:
    How can I create the audio file fitted in time?with the flex info?
    You need to create Apple Loop, REX etc.
    For example select the region that you have already flexed, right click ->Bounce Merge->Bounce Inplace. I will create a new audio track with the bounced Flex work.
    Select the new region and go to Audio menu ->Open in Apple Loop Utility and check "Loop" and other attributes to create an Apple Loop. Save the Apple Loop and close the utility. It's expected that the Apple Loop aif must be created in your Project path folder or have a look at the Audio Bin in Logic where is the aif path.
    Drug the Apple Loop in the Arrange audio track ( or it will create one ) and operate with any tempos.
    !http://img59.imageshack.us/img59/4967/aglogo45.gif!

  • Can't create free PO with the material which material type is UNBW

    When I create a free PO with the material which material type is UNBW , error happens as below:
    Account assignment mandatory for material *** (enter acc. ***. cat.)
    There is no provision for value-based inventory management for this material type in this plant. Account assignment is thus necessary.
    But I use UNBW material type just because it's only QTY updating, and no value update.
    So this PO should has no relationship to FI document and any GL account or cost center.
    How can I create PO and GR for UNBW material in SAP system?
    Please tell me the solution in detail, thanks!

    Dear,
           Same scenario i have done in SAP. when we create free P.O then condition tab is automatically remove from the item level.
          But Cost Center and G/L account will compulsory. May be because of inventory. Inventory should affect the cost center and G/L account.
    Regards,
    Sandip

  • Can I create a database with the same name and DBID that one is dropped?

    Hello,
    I need to restore a backup database, made with Oracle Enterprise Manager, in a new one, because the original is dropped. I've tried it with the recovery tools but fails, i suppose because the dbid's are not the same.
    Then, Is it possible create a new database with the same old database dbid to restore de backup?
    Thank you very much.
    P.D.: I've too THE OLD spfile---.ora y el pwd---.ora

    I think you are using the same Composition Class on both project. On the properties tab, you can change this number (e.g.: EDGE-1637270).

  • How can I create a box with the option of either a check or "N/A"?

    Hi there guys, just a quick question which has been bugging me for days now!
    I have a form in which I need to have a check box, but when the box is not checked I need it to show up as "N/A", is that possible?
    I have tried using a dropdown box instead. Making one of the options a capital "P" and setting the font to Wingdings 2 makes it appear as a check. This however makes it impossible for me to type in "N/A" as the other option because the font is set to Wingdings 2!
    Any help would be greatly appreciated
    I am using Adobe Acrobat X Pro on Windows 7
    Thank you
    Clint

    Have you ever seen a paper form work this way?
    Have you ever seen an electronic form work this way?
    You can have a text field next to the check box that show "N/A" when the check box is not selected.
    Or if you like to do a lot of coding, use a check box and then overlay the check box with a text box to display the "N/A" and you can work out how switch between the 2 fields if one wants to uncheck the item.

  • I can't create an App with the Folio Builder!

    Sorry, I'm trying to create my first App with Folio Builder but it always give me the following error message:
    Error during application startup DPS App Builder.
    The article '...' is not compatible with the viewer for what is published in the folio
    Please help me!

    Not sure of what the error message means. I'd like to investigate and report back here. Could you send an e-mail to the contact information I've PM you.
    Thanks
    Lohrii

  • How can I create a mailinglist with the new ipad?

    I want send a email to diffrent persons. In the mailprogramm on the mac is this possible with the right mousclick. But how does this work on the Ipad?

    I'm afraid not. If the list is long, best bet is to get it onto the iPad through Notes or a similar program, and copy & paste the whole list into the email.

  • Create Attribute Dimension via the JAVA api

    <p>Does anyone know how to create an attribute dimenions via theJava API ?</p><p> </p><p>I can set the dimension type to attribute via<b>setAttributeDimensionDataType</b> but I don't know how toassociate the attr. dimension with a sparse, normal dimension(which is mandatory).</p><p> </p><p> </p>

    Hi Marco,<BR><BR>It is in the IEssCubeOutline interface. Here is sample code from the CreateOutline.java sample code that ships with EDS:<BR><BR>   IEssCubeOutline otl = ... <BR><BR>   IEssDimension product = otl.findDimension("Product");<BR>   otl.associateAttributeDimension(product, caffeinated);<BR><BR>Tim<BR>

  • Create a node with the newest date only

    Hi, I want to create a node in the target, only by the newest date from the source. The source is an Idoc with, say, 3 segments of the same kind, with different dates. Only the segment with the newest date, should be created in the target.
    Any Ideas?

    Hi,
    it's easy but with user defined functions:
    - put all segments into the UDF
    - then inside this UDF choose the one with the
    latest date and put it into the array (global variable)
    - then take the values from the global variable
    to fill the sements (from new UDFs)
    you could also try with
    DateBefore and DateAfter functions
    and try to do it without UDFs
    with logic like
    if date1 DateBefore date2 then ....
    Regards,
    michal

  • How can i create a slideshow with the newest version of dreamweaver?

    I am trying to figure out how to create a slideshow but i cannot find any explanations for the new version of Dreamweaver. Can anyone help?

    DW doesn't make slideshows.  You'll need to use a jQuery plugin or a 3rd party commercial Extension.
    Do a web search for:
    jQuery Cycle2
    jQuery WOW Slider
    jQuery Fancybox2
    Primer for using jQuery Plugins
    Alt-Web Design & Publishing: Primer for Using jQuery Plug-Ins
    Nancy O.

Maybe you are looking for