This discussion is archived
7 Replies Latest reply: Aug 29, 2011 7:02 AM by 876084 RSS

GnuPG key generation problem

876084 Newbie
Currently Being Moderated
Hi java gurus, I am a actually new to the GnuPG package and i have been able to deal with the problems i have encountered so far but this one has been very difficult for me to accomplish, any help or ideas on how to fix it will be very appreciated.

i am trying to create a new key in the GnuPG database which is external to my application and i have been able to create the key using the command line (which is not what i want to do) but be able to create this key using my application but instead when i run my code i keep getting a no response and no key was created when i checked this via the GnuPG, however if i create a key or i already registered a user via the command utility by windows, i can use the encryption and decryption command via my application and and my code can be found below. many thanks in advance.

//method to create the key 

public boolean createkey(){
            boolean success=false;
            success = runGnuPG ("--gen-key \n1\n2048\n365\ny\ntolulope\ntolu@tolu.com\ndulling\no\npassword123\npassword123",null);
            if (success && this.gpg_exitCode != 0)
                    success = false;
          return success;
        }

public boolean createkey2(){
            boolean success=false;
            success = runGnuPG ("--gen-key ","1 2048 365 y tolulope tolu@tolu.com dulling o password123 password123"/*null*/);
            if (success && this.gpg_exitCode != 0)
                    success = false;
          return success;
        }



//method to encrypt and decrypt a file 


public boolean encrypt (String inStr, String User)
     {
          boolean          success=false;
                
          File temp=  createTempFile (inStr);
                String outFile =progtempdir+"/"+User+System.currentTimeMillis()+".gpg";
          
          if (temp!=null)
          {
               success = runGnuPG ("-r " + User+" -o \""+outFile+"\" --encrypt \""+temp+"\"", null);
               temp.delete ();
               if (success && this.gpg_exitCode != 0)
                    success = false;
          }
          return success;
     }

public boolean decrypt ( String passPhrase,String User,String inFile)
     {
          boolean          success=false;
          //File temp=  createTempFile (inStr);
                String OutFile=progtempdir+"/"+inFile+".txt";
                inFile =progtempdir+"/"+inFile+".gpg";
          
          //if (temp!=null)
          //{
               success = runGnuPG ("-r " + User+" --passphrase \""+passPhrase+"\" -o \""+OutFile+"\" --decrypt \""+inFile+"\"", passPhrase);
               //temp.delete ();
               if (success && this.gpg_exitCode != 0)
                    success = false;
          //}
          return success;
     }



//method for running the commandline and passed instructions passed into it.

private boolean runGnuPG (String commandArgs, String inputPassphrase)
     {
                String kGnuPGCommand = "cmd /c gpg";
          Process          p=null;
          String          fullCommand = kGnuPGCommand + " " + commandArgs;
//          String          fullCommand = commandArgs;
          
          System.out.println (fullCommand);
          
          try
          {
               p = Runtime.getRuntime().exec(/*"cmd /c md helloboy"*/fullCommand);
                        
          }
          catch(IOException io)
          {
               System.out.println ("io Error" + io.getMessage ());
               return false;
          }
          
          ProcessStreamReader psr_stdout = new ProcessStreamReader(p.getInputStream());
          ProcessStreamReader psr_stderr = new ProcessStreamReader(p.getErrorStream());
          psr_stdout.start();
          psr_stderr.start();
                
                
                
                //System.out.println("hello");
          if (inputPassphrase != null)
          {
                    String tempstr[]=splitstr(inputPassphrase);
                    //BufferedOutputStream out = new BufferedOutputStream(p.getOutputStream());
                    //BufferedWriter out = new BufferedWriter(new OutputStreamWriter(p.getOutputStream()));
                    //OutputStream out=p.getOutputStream();
                    for (int i=0;i<tempstr.length;i++){
                        System.out.println(tempstr);

               BufferedWriter out = new BufferedWriter(new OutputStreamWriter(p.getOutputStream()));

               try
               {
                    //out.write(inputPassphrase);
out.write(tempstr[i]);
try{p.waitFor();}catch(Exception ex){}
                    out.close();
// System.out.println("hello");
               }
               catch(IOException io)
               {
                    System.out.println("Exception at write! " + io.getMessage ());
                    return false;
               }
}
          }
          
          try
          {
               p.waitFor();
               psr_stdout.join();
               psr_stderr.join();
          }
          catch(Exception i/*InterruptedException i*/)
          {
               System.out.println("Exception at waitfor! " + i.getMessage ());
               return false;
          }
          
          try
          {
               gpg_exitCode = p.exitValue ();
          }
          catch (IllegalThreadStateException itse)
          {
               return false;
          }
          
          gpg_result = psr_stdout.getString();
          gpg_err = psr_stdout.getString();
          
          return true;
     }
     
String [] addvalue(String atr, String [] arrstr){
String [] retstr =null;
//System.out.println(arrstr.length);
try{
if (arrstr.length>0){
retstr=new String[arrstr.length+1];
System.arraycopy(arrstr, 0, retstr, 0, arrstr.length);
retstr[arrstr.length]=atr;
}
else{
retstr=new String[1];
retstr[0]=atr;
}
}catch(Exception ex){
retstr=new String[1];
retstr[0]=atr;
}

return retstr;
}

     String [] splitstr(String inp){
String [] temp=null; String atr="";
for (int i=0;i<inp.length();i++){
if (inp.charAt(i)==' '){
temp=addvalue(atr,temp);
atr="";
}
else{
atr=atr+inp.charAt(i);
}
}
temp=addvalue(atr,temp);
//System.out.println(temp.length);
//atr="";
return temp;
}

//this is the thread handling the procedures for the runGnuPG method

class ProcessStreamReader extends Thread
     {
          StringBuffer          stream;
          InputStreamReader     in;
          
          final static int BUFFER_SIZE = 1024;
          
          /**
          *     Creates new ProcessStreamReader object.
          *     
          *     @param     in
          */
          ProcessStreamReader (InputStream in)
          {
               super();
               
               this.in = new InputStreamReader(in);

               this.stream = new StringBuffer();
          }
          
          public void run()
          {
               try
               {      
                    int read;
                    char[] c = new char[BUFFER_SIZE];
                    
                    while ((read = in.read(c, 0, BUFFER_SIZE - 1)) > 0)
                    {
                         stream.append(c, 0, read);
                         if (read < BUFFER_SIZE - 1) break;
                    }
               }
               catch(IOException io) {}
          }
          
          String getString()
          {
                    return stream.toString();
          }
     }

Edited by: user13340119 on Jul 17, 2011 11:53 PM

Edited by: user13340119 on Jul 17, 2011 11:53 PM

Edited by: user13340119 on Jul 17, 2011 11:54 PM

Edited by: sabre150 on 18-Jul-2011 01:50

Added code tags to make the code readable.
  • 1. Re: GnuPG key generation problem
    gimbal2 Guru
    Currently Being Moderated
    Okay, lets filter that story of yours. What you are actually having difficulty with is running a command line utility using Java right? It has nothing to do with GnuPG specifically, so why base your entire question around it? Your thread title will now probably discourage people from coming here because they don't have experience with this tool you're using.

    If you want to get help, ask clear questions. That also means drilling down to the core of your problem first.

    Your first stop should be reading this article front to back:

    http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html


    Also, read the forum faq to learn how to format the code you post. Right now it is quite a mess.
  • 2. Re: GnuPG key generation problem
    sabre150 Expert
    Currently Being Moderated
    As part of an article I have been writing on the use of Runtime.exec() and ProcessBuilder, for the last couple of weeks I have been writing a simple Java GUI that wraps the 'gpg' command line so I thought I would be able to help here but I don't think I can. You seem to have read some of the 'traps' article and to have implemented some of the recommendations but your exception handling makes your code just about unreadable. If a particular exception means that you have a system error then wrap it in an Error and throw that. If a particular exception means that the caller of your code has provided bad data then throw an exception to tell him that. If you can't think of what to do with an exception then don't do anything; just pass it back to the calling process. Never (well almost never) just smother an exception and just printing a stack trace then continuing is usually wrong.

    Note - there is a pretty complete Pure Java PGP library available from BouncyCastle.
  • 3. Re: GnuPG key generation problem
    876084 Newbie
    Currently Being Moderated
    thanks sabre 4your aid, you have been able to help me to an extent, let me see if i can do a work around on this because i have been able to implement everything even other processes in the GPG only this part of the creation of the key which if i do that manually using the command line in windows in a batch file it works but during my program it just gives error and just like you said i think i would take your advice and try see if it works well, and would have a look at the bouncy castle if it works like the GPG and every procedure is similar that would save me a lot of problem. thanks very much again.
  • 4. Re: GnuPG key generation problem
    gimbal2 Guru
    Currently Being Moderated
    user13340119 wrote:
    thanks sabre 4your aid, you have been able to help me to an extent, let me see if i can do a work around on this because i have been able to implement everything even other processes in the GPG only this part of the creation of the key which if i do that manually using the command line in windows in a batch file it works but during my program it just gives error and just like you said i think i would take your advice and try see if it works well, and would have a look at the bouncy castle if it works like the GPG and every procedure is similar that would save me a lot of problem. thanks very much again.
    Just to note: you may need to install the unlimited strength policy into your JRE if you want to use GPG encryption through BouncyCastle to allow encryption keys of any length.

    http://www.oracle.com/technetwork/java/javase/downloads/jce-6-download-429243.html
  • 5. Re: GnuPG key generation problem
    876084 Newbie
    Currently Being Moderated
    thanks sabre and gimbal2 for your assistance but i have checked this pgp implementation, i found out it is not open source, and i will love to work with this gnupg version because it is open source. also i found out the process is likely similar in generating keys in pgp but i do not seem to see where this part as specified by this website http://www.gnupg.org/gph/en/manual.html similar to http://www.seas.upenn.edu/cets/answers/pgp_keys.html in terms of the key generation; can be implemented via my application without actually interacting with the command prompt on windows which is my major problem. but i still appreciate your helpful details provided earlier, however, any further assistance would be much appreciated.

    Edited by: user13340119 on Jul 20, 2011 6:13 AM
  • 6. Re: GnuPG key generation problem
    sabre150 Expert
    Currently Being Moderated
    user13340119 wrote:
    thanks sabre and gimbal2 for your assistance but i have checked this pgp implementation, i found out it is not open source,
    If you are referring to the BouncyCastle PGP then it most definitely is open source!
  • 7. Re: GnuPG key generation problem
    876084 Newbie
    Currently Being Moderated
    after trying a lot of things i learnt a lot on my way and still come about the solution which is what i have pasted below in my codes, sorry for pasting it late.

    thanks for all the assistance from the people that have helped me.

    code_tags

    //create key
    public boolean createkey(String user, String regno, String email, String passphrase){
    boolean success=false;
    String other="Key-Type: RSA\n"
    + "Key-Length: 2048\n"
    + "Subkey-Type: ELG-E\n"
    + "Subkey-Length: 1024\n"
    + "Name-Real: "+ user+"\n"
    + "Name-Comment: "+regno+"\n"
    + "Name-Email: "+email+"\n"
    + "Expire-Date: 365\n"
    + "Passphrase: "+passphrase+"\n"
    + "%commit\n";
    success = runGnuPG ("--gen-key --batch --yes --no-tty",other);
    try{Thread.sleep(2000);//wait for operation to complete
                }catch(Exception ex){}
    if (success && this.gpg_exitCode != 0)
    success = false;
    return success;
    }

    code_tags

    once again many thanks in advance.

    Edited by: user13340119 on Aug 29, 2011 7:00 AM

Legend

  • Correct Answers - 10 points
  • Helpful Answers - 5 points