Creating keystore file programmatically

Hi,
Wondering if you will be able to help me. I would like to find out how you can create a keystore file programmatically without using the keytool command.
What I'm trying to do is generate KeyPairs for the SSL connections. After the keys are signed, I would like to insert the keys into a new keystore file. Is that possible and if it is do you perhaps know how?
Thanks
Julia

Hi Julia,
keytool does not allow you to import private keys into a keystore but, I bypassed this problem this way:
after creating your key pair convert them into the pkcs12 format
openssl pkcs12 -inkey privatekey.key -in certificate.crt -export -out somename.p12
fortunately using the following code that was already posted in the forum, you will be able to create a new keystore with your private key :)
import java.security.*;
import java.io.*;
// assumes you are using a 3rd party keystore library
// for pkcs12 key stores. For some reason, JDK 1.4 won't
// read pkcs12 files exported from MIE / Netscape
class Convert {
static public void main(String[] args) throws Exception {
try {
//pkcs12 keystore
KeyStore ks = KeyStore.getInstance("pkcs12");
//jks keystore
KeyStore ks2 = KeyStore.getInstance("jks");
// load the pkcs12 file
ks.load(new FileInputStream("C:\\insurance.p12"),"insurance123".toCharArray());
// load the jks file (have to have an existing one)
ks2.load(new FileInputStream("C:\\.temp"),"temp123".toCharArray());
//read the p12 certificate
java.security.cert.Certificate [] cc = ks.getCertificateChain("1");
//gets the private key having as alias "1" and as password "insurance123"
Key k = ks.getKey("1", "insurance123".toCharArray());
// add to keystore and save
ks2.setKeyEntry("insurance", k, "insurance123".toCharArray(),cc);
FileOutputStream out = new FileOutputStream("C:\\newstore.keystore");
ks2.store(out, "insurance123".toCharArray());
out.close();
} catch (Throwable e) { e.printStackTrace(); } }
} //end of the class
the following call:
ks2.load(new FileInputStream("C:\\.temp"),"temp123".toCharArray());
assumes that you already created a keystore (.temp) having for password : temp123
Hope this help :)
KAnis

Similar Messages

  • Creating JAR files programmatically

    I am trying to create JAR files programmatically using the java.util.zip and java.util.jar APIs. I am starting with just a set of directories containing .class files. I can seem to make the JAR but if I try to use any of the classes in it they don't work. But, if I unzip the JAR using WinZip, the classes are usable. So I am somehow building the JAR file incorrectly. Does anyone have any ideas or suggestions? The code is pretty long so I won't post it yet but I can send it to you if you'd like to see it. Contact by email if you'd like to see the code. Thanks.

    What paths are you encoding? Here are a couple of rules:
    1 - All paths are '/' separated, and do not begin with a '/'.
    2 - All paths are relative (see 1) and contain the exact package name of the class, plus the class.
    E.G., the class java.lang.Object would look like this in your jar:
    java/lang/Object.classNothing more or less.

  • Is there any documentation on creating .key files programmatically?

    I am a programmer, and while I love keynote for presentations, I would much prefer to generate .key files via programs.
    There is a document that talks about this, and in fact encourages you to do it, but it's for a very old version of Keynote.  All of my attempts to find the old tech notes referred to in the document returned nothing.  I can't even find the XML Schemas referenced in the index.apxl.gz file, such as http://developer.apple.com/namespaces/keynote2.
    It would seem to be in Apple's best interest for developers to be developing to use Apple delivery platforms, such as Keynote, but I'm not getting the impression that Apple agrees.
    ../Dave

    Links to all reports docs
    http://otn.oracle.com/documentation/reports_dev.html
    Oracle9i Reports Building Reports ( very extensive )
    (PDF version ) http://download.oracle.com/otn/other/general/B10310_01.pdf [ 8 MB ]
    (HTML version ) http://otn.oracle.com/products/reports/htdocs/getstart/docs/B10310_01/title.htm
    Thanks
    The Oracle Reports Team

  • Please help, keystore file generation

    Hi all,
    I'm building an digital signature application using java, one of it's module is private/public key+certificate management.
    How can i create keystore file or edit using API not keytool ?
    Best regards
    -Lorenz-

    can you give me some example codes ?

  • How to create a New Excel File programmatically

    Hi !
    I am documenting acquired data continuously in an excel file, what I need to do is to create a new excel file automatically when the size of the previous file exceeds a certain limit lets say 1MB.
    I have tried using the simple 'Create/Open File' function and the 'Write to Spreadsheet File' function to create the new excel file. I does create a file but when I open the file it says the format of the file is not what you have opened it with.
    Also when the new file is created, three new worksheet are to be added programmatically with pre-defined worksheet name and also Column headers for each of the worksheet are to be added.
    I am also using 'Labview Report Generation Toolkit for Office'.
    Regards,
    Reeves
    Solved!
    Go to Solution.

    @ Aldo A
    Thanks for the reference to tutorial, I didn't know about them. They are useful in general but unfortunately they don't answer the problem of creating an altogether new excel file programmatically.
    @ ben64
    The template thing simplifies the issue of formatting the new file. But I am still working on the new excel file creation challenge.
    Let me put my problem in a different way.
    Certain data is being acquired continually and is being written to a certain excel file, when the size of the file exceeds lets say 1MB the program should start saving the data in a NEW FILE instead of the previous file.
    I have attached the VI to explain what I am trying to achieve here.
    Reeves
    Attachments:
    New Microsoft Office Excel Worksheet.zip ‏30 KB

  • Programmatically creating postscript files for office documents

    Hi All
    I am in the process of experimenting with vb.net to open up a word document in the background and create a postscript file, which i would then use to create a pdf. This currently is a windows service and seems to run ok when the same code runs through a windows form application.
    The problem i am having is with the "When creating a postscript file you have to sent the host fonts" error message, which seems to be fairly common judging by numerous articles on various forums. However, none of the solutions seem to solve my problem.
    I have set the "Do Not Send Fonts To Adobe PDF" option to OFF on printer defaults, on the current printer setup and even on the printer settings for that application (go to print, properties etc from within Word).
    However, whenever i run the code i get the error message. I then made the instance of word visible and checked the application settings for the adobe pdf printer.... the "Do Not Send Fonts To Adobe PDF" is now ticked. But when i close this down, and open word as a normal user would and check the setting it is off! Why would this be?
    Can i programmatically change this setting when word opens and before i run the post script file creation code? Where is this value for the setting stored? I do not understand why this is resetting in the instance of word through code? Is it something to do with setting the active printer and at this point using the default setting?
    Any help would be appreciated.
    Thanks in advance
    Nic

    You say you are doing this as Windows service – does this mean you are running this on a server of some sort?  If so, that is NOT ALLOWED.
    From: Adobe Forums <[email protected]<mailto:[email protected]>>
    Reply-To: "[email protected]<mailto:[email protected]>" <[email protected]<mailto:[email protected]>>
    Date: Wed, 26 Oct 2011 04:31:13 -0700
    To: Leonard Rosenthol <[email protected]<mailto:[email protected]>>
    Subject: Programmatically creating postscript files for office documents
    Programmatically creating postscript files for office documents
    created by nic.eastham<http://forums.adobe.com/people/nic.eastham> in Acrobat SDK - View the full discussion<http://forums.adobe.com/message/3990878#3990878

  • Need to create a pdf file programmatically

    Hi friends,
          I am able to read contents of a pdf file in KM repository programmatically. Now I am trying to create a pdf file programmatically. I ve tried the following solutions:
    1) <b>pdfwriter</b>. Here i endup with giving the path for the file.I ve tried giving RID and URL of the document. but in vein.
    2) <b>createresource</b>. Here i am able to create a txt file. but couldnt find how to create pdf.
    Awaiting replies specific to the questions. thanks in advance.
    Regards,
    Saravanan

    Hi Saravanan,
    In my view,the solution for this is to create a pdf file in C or any drive of the sever temporarily and get the FileInputstream from that temporary file and with the file stream upload pdf file in to KM repository and finally delete the temporary file u have created.
    Follow the code given,it will be more clear
    //Creating PDF
    Rectangle pageSize = new Rectangle(0,0,2382,3369);
    Document document = new Document(pageSize);
    try {
    PdfWriter.getInstance(document, new FileOutputStream("<b>D:\PDFfromJava.pdf</b>"));
      document.open();
      document.add(new Paragraph("Hi, this is demo PDF file from JAVA!"));
    catch(DocumentException de) {
      response.write("Document Exception");
    }catch(IOException ioe) {
    response.write("IO Exception");
    ResourceContext rContext=null;
    ICollection aCollection=null;
    IResource aResource=null;
    InputStream myIS=null;
    IUser loggedOnUser = (IUser) request.getUser().getUser(); if (loggedOnUser.isAuthenticated()) {
    rContext = new ResourceContext(loggedOnUser);
    RID aRid = RID.getRID("/documents"); // remember that the repository is case sensitive
    try {
    IResourceFactory aResourceFactory = ResourceFactory.getInstance();
    aCollection = (ICollection) aResourceFactory.getResource(aRid, rContext);
    //Creating a File object
    File myPDF=new File("<b>D:\PDFfromJava.pdf</b>");
    //Getting the stream from temp file
    myIS=new FileInputStream(myPDF);
    IContent aContent = new Content(myIS,"byte",-1);
    if (aCollection != null)
    aResource = aCollection.createResource("<b>PDFfromJava.pdf</b>", null, aContent);
    myIS.close();
    //deleting the temp file from server
    myPDF.delete();
    }catch(Exception e){
         response.write("Exce"+e);
    <b>One more thing the file name PDFfromJava.pdf mentioned in bold should be same at all places</b>

  • Unable to programmatically delete keystore file

    Hi
    I'm in the process of writing some junit tests for a Key Management helper class. What I want to do is initialise an empty keystore in setUp, add keys, get keys, delete keys, etc in the testXXX methods and delete the keystore file in tearDown. My tearDown looks like the following but is always failing as f.delete() is returning false (i.e. keystore file was not deleted).
         public void tearDown() {
              File f = new File(JUNIT_KEYSTORE);
              if(f.exists()) {
                   if(f.delete() == false) {
                        fail("Unable to delete " + JUNIT_KEYSTORE);
              assertFalse(JUNIT_KEYSTORE + " exists.", new File(JUNIT_KEYSTORE).exists());
         }I'm working on WinXP with 1.4.1_06. When viewing the keystore file properties via explorer it is writeable, and I can delete the file manually. Also I can programatically delete other files, just not keystore files. My suspicion is that since the keystore is seen as such a sensitive and valuable resource that the java security model may be placing some restrictions on what operations can be performed on it through the File class API. However being a relative java.security novice, I would be grateful if someone more enlightened could provide some insight?
    Thanks in advance
    Rob

    Hi
    Adding the following lines to tearDown() indicates that the java security model is indeed preventing the keystore file from being deleted as an AccessControlException is being thrown. Note read and write are also blocked.
         FilePermission delete = new FilePermission(JUNIT_KEYSTORE, "delete");
         AccessController.checkPermission(delete);Next question : Is it possible to programmatically enable the 'delete' FilePermission? or can this only be done by adding a suitable entry to java.policy?
    Rob

  • Creating Diagram and model file programmatically

    Hi,
    Am trying to create the Diagram and model file programmatically.
    I used the code similar to what is there in XXDiagramEditorUtil.createDiagram().
    In the normal case (when i have an empty domain ie nothing is set into the domain object), the diagram and the domain file gets created and works fine.
    Assume my model is of type XX, and that has a list of YY.
    i create YY and set it inside XX.
    Now when i create the domain file, the <YY> is set correctly inside <XX>.
    But in the diagram file, i dont see the <children/> tags corresponding to the YY.
    How would the appropriate <children/> tags be generated ?
    i tried diagram.createChild(yy.eClass()), but the diagram file does not get generated.
    Pls help.
    AbstractTransactionalCommand command = new AbstractTransactionalCommand(editingDomain,
    Messages.XXXDiagramEditorUtil_CreateDiagramCommandLabel,
    Collections.EMPTY_LIST) {
    protected CommandResult doExecuteWithResult(IProgressMonitor monitor, IAdaptable info) throws ExecutionException {
    XXX model = createInitialModel();
    YYY yyy = XXXFactory.eINSTANCE.createYYY();
    yyy.setAttribute1("2");
    yyy.setAttribute2("name");
    model.getYYYs().add(yyy);
    attachModelToResource(model, modelResource);
    Diagram diagram = ViewService.createDiagram(model, XXXEditPart.MODEL_ID,XXXEditorPlugin.DIAGRAM_PREFERENCES_HINT);
    if (diagram != null) {
    diagramResource.getContents().add(diagram);
    diagram.setName(diagramName);
    diagram.setElement(model);
    //diagram.createChild(yyy.eClass());
    //diagram.insertChild(arg0);
    try {
    modelResource.save(.getSaveOptions());
    diagramResource.save(getSaveOptions());
    } catch (IOException e) {
    return CommandResult.newOKCommandResult();

    Hi ganesh,
    you have two options to get it working.
    The first one is using a CanonicalEditPolicy, which creates all Nodes and Edges for you based on your semantic model. This is easy to implement, but it has some drawbacks. Your editor will get dirty after opening it, because your Notation Model is changes and no layout information is available.
    The better way is to create Nodes and Edges for each semantic element you created.
    For your code snippet it might look like this:
    XXX model = createInitialModel();
    YYY yyy = XXXFactory.eINSTANCE.createYYY();
    yyy.setAttribute1("2");
    yyy.setAttribute2("name");
    model.getYYYs().add(yyy);
    attachModelToResource(model, modelResource);
    Diagram diagram = ViewService.createDiagram(model, XXXEditPart.MODEL_ID,XXXEditorPlugin.DIAGRAM_PREFERENCES_HINT);
    Node yyyView = ViewService.createNode(diagram, yyy, SemanticHints.YYY,
    ,XXXEditorPlugin.DIAGRAM_PREFERENCES_HINT);
    //Set some layout information assuming you use a XYLayout
    Bounds bounds = NotationFactory.eINSTANCE.createBounds();
    bounds.setX(70);
    bounds.setY(20);
    yyyView.setLayoutConstraint(bounds);
    Regards,
    Andreas

  • Creating keystore problem

    Hello, I'm a little new to this and have been working on creating a keystore programmatically. This is code so far: It compiles fine, but it won't run - just the "Press any key to continue" shows up on the command window. I'm sure I've probably made some stupid mistake that's staring at me in the face, but since it's past 1am I can't exactly ask anyone for a fresh set of eyes to see if they spot anything. Could someone please have a quick look at the code below, I'd greatly appreciate it. (by the way all the printlns are just for testing)
    try{
    Security.addProvider(new com.sun.crypto.provider.SunJCE());
    String homedir = System.getProperty("user.home");
    System.out.println("Home Directory: "+ homedir);
    String fileSep = System.getProperty("file.separator");
    String stringKeyStore = homedir + fileSep + ".keystoreF";
    System.out.println("StringKeyStore = " + stringKeyStore);
    File fileKeyStore = new File(stringKeyStore);
    System.out.println("FileName:" + fileKeyStore);
    String javaHome = System.getProperty("java.home");
    System.out.println("Java Home = " + javaHome);
    String keyStoreType=KeyStore.getDefaultType();      
    System.out.println("KeyStoreType:" + keyStoreType);
         if (fileKeyStore.exists() == false){
    System.out.println("Creating keystore...");
         String [] arstringCommand = new String []{
         System.getProperty("java.home") + fileSep + "bin"+fileSep
    "keytool",
    "-genkey",
         "-alias", stringId,
         "-keyalg", "RSA",
         "-keysize", "1024",
         "-dname", "CN=" + stringName,
         "-keystore", homedir + fileSep + "keystoreF",
         "-keypass", stringPassword,
    "-storetype", "JKS",
    "-storepass", stringPassword};
    Process process = Runtime.getRuntime().exec(arstringCommand);
    process.waitFor();
    BufferedReader reader = new BufferedReader(                         new InputStreamReader(process.getInputStream()));
         while (true)
         try {
         String lineStr = reader.readLine();
         if (lineStr == null)
                                                 break;
                                            System.out.println(lineStr);
         } catch (Exception e) { break; }
         }//end while
         try {
         process.waitFor();
         catch (InterruptedException e) {}
         System.out.println("");*/
         passW = stringPassword.toCharArray();
         FileInputStream fis = new FileInputStream(homedir + fileSep +
                                  "keystoreF");
         keyStore = KeyStore.getInstance(keyStoreType);
         System.out.println("KeyStore:" + keyStore);
    if (fileKeyStore.exists()) {
         FileInputStream fis = new FileInputStream(homedir + fileSep +
                             "keystoreF");
         keyStore.load(fis, passW);
         fis.close();
         }else {
         System.out.println("New KeyStore ("+fileKeyStore+") ...");
         keyStore.load(null, passW);
    }catch (Exception e)
    System.out.println("Cannot load keystore");
    }//end constructor

    it's ok, i found my stupid mistake in another part of the program!!

  • Sequence tag error while importing the SSL certificate into ".keystore" fil

    I have created the ".keystore " file successfully and also imported the "root.cer".
    but while importing the SSL certificate it says like
    "keytool error: java.security.cert.CertificateException: IOException: Sequence ta
    g error" (I got the certificate from Verisign)
    How to resolve this Error?
    can anyone help me?
    mail to:: [email protected]
    Thanks in Advance

    Hi,
    I resolved this error by making it sure that there are no extra spaces or unwanted caracter copied while copying the certificate response from the CA. Make sure you are copying the certificate response properly. In my case, some extra space was getting copied so after re-copyinf it properly, it worked.

  • How to avoid dialog in Open/Create/Replace File? (yes, I set 'no adv.dialog')

    I would like to avoid the dialog box which seems to
    appear whenever I can successfully open a file:
    I tried both 'advisory dialog' FALSE and TRUE for the following, as well as all file modes (open,create,etc):
    path:"C:\labview" file:"test.txt" ERROR 8
    path:nothing file:"C:\labview\test.txt" dialog box!
    path:"C:\labview\test.txt" file:nothing ERROR 8
    path:"C:\labview\test.txt" file:"C:\labview\test.txt"
    ERROR 8
    as well as other less sensical combinations.

    I'm guessing that you put the filename into the 'default filename' input.
    Instead you need to put the path (including filename) into the 'file path'
    input. The 'default filename' input is for when you want to allow the user
    to input the filename but give him a suggestion of what would be
    appropriate.
    "Grover" wrote in message
    news:[email protected]..
    > I am having the same problem when trying to programmatically create a
    > file. I have made sure I have a legitimate file path/name, no other
    > app/vi is denying access, I have 2k, but I am admin plus the folder
    > where I try creating the file has permissions for everyone set to full
    > control. Any ideas??

  • Keytool error: java.lang.Exception: Keystore file does not exist:

    Hi All,
    While listing the keystore using the command keytool -list, I got the error message that
    keytool error: java.lang.Exception: Keystore file does not exist: C:\Documents and Settings\subramanian.arivalag\.keystore
    I noticed there is no file .keystore in the above mentioned directory. What's this .keystore file? Will it be created automatically or should we create manually?
    Already I created a keystore using -genkey command and received CA authority also.
    Kindly provide me more details about .keystore file and how to handle this error.

    If you specified a keystore filename when you created the keystore
    i.e. keytool -genkey -alias jboss-ssl -keyalg RSA -keystore my_name.keystore -validity 3650
    then you need to specify the same keystore when you export the cert
    i.e. keytool -export -alias jboss-ssl -keystore my_name.keystore –file my_name.cer

  • How to use keystore file from native android project.

    Android apk upload fails with error 'The apk must be signed with the same certificates as the previous one'.
    Out of the frying pan, into the fire.
    How to convert .keystore file to .p12 file?

    "Bobby Digi" <[email protected]> wrote:
    Hi,
    Is there a way to use .keystore file with BEA Weblogic 6 or 6.1 ?
    I used keytool to create private key and public key..
    I do not know how to tell weblogic 6 to use it....
    Can this be done through the GUI or do I have to add something to the.xml
    config file for the site?
    Thanks,
    Rob
    nope. with 7.0 you can do that.
    >
    >

  • How to create an IDoc programmatically at Inbound side?

    Hi,
    How to create an IDoc programmatically at Inbound side?
    Assume that you have a file(material master details) which is enough to create master data.
    Regards,
    Thiyagu

    Read the documentation of this FM first:
    FU IDOC_INBOUND_ASYNCHRONOUS                                                                               
    K. tekst
                                                                                    IDoc inbound processing via tRFC                                                                               
    Functionality
                                                                                    This function module starts inbound processing in the case of port type    
        "tRFC". The function module is a successor to INBOUND_IDOC_PROCESS,        
        which processes IDocs in the Release 4.0 record types. If you are          
        processing IDocs in Release 3.X record types, the function module          
        INBOUND_IDOC_PROCESS must still be called.                                                                               
    The function module checks the ID 'EDI_MES' in authorization object        
        B_ALE_RECV against the received message type.                                                                               
    The IDocs are saved by the function module IDOC_INBOUND_WRITE_TO_DB (a     
        COMMIT for all IDocs) and then transferred directly to the application     
        by the dispatcher module IDOC_START_INBOUND.                                                                               
    Parameter
                                                                                    IDOC_CONTROL_REC_40                                                        
        IDOC_DATA_REC_40                                                                               
    Exceptions
                                                                                    Functiegroep                                                                               
    Edited by: Micky Oestreich on Jun 11, 2009 12:52 PM

Maybe you are looking for

  • Application on approved list won't open

    I am running a lab using the Mac OX Server (Leopard) and have had several problems with applications being on the "approved list" but not allowing the user to open them. iPhoto is one of them and the newest is a free program called TextWrangler. Stud

  • Min-Max to create WIP

    Hi All, I need help on the following - I am running Min-Max planning to create WIP jobs. I want to - 1: Default WIP Start Date to Current Date. Currently WIP completion date is defaulted to current date. This causes WIP Start Date in Past Due which i

  • Orders05 idoc mapping

    Hi, Please help me where to map below fields in orders05 idoc. 1) shipping terms 2) shipping via. 3) NSP Quote Number ( discount ) Thanks, Raghu.

  • Statistical Net Income Migration

    Hello guru's I have come across an issue with the migration of Statistical Net Income values, from ECCS to a SEM-BCS 6.0 system. We are loading the prior year RFD Trial Balance from the historic system into P12, via BI tools. We are setting the perio

  • Passing generics into a constructor.

    Hi I have this class as follows. package generation; import java.util.LinkedList; import java.util.NoSuchElementException; import java.util.Queue; @author David *public class EconomicLoadOrder<E>* *Queue<E> queue = new LinkedList<E>();* *public Econo