Forum Stats

  • 3,874,309 Users
  • 2,266,718 Discussions
  • 7,911,811 Comments

Discussions

GnuPG key generation problem

876084
876084 Member Posts: 4
edited Aug 29, 2011 10:02AM in Java Desktop Applications
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\[email protected]\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 [email protected] 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<em>);<br />
<br />
			BufferedWriter out = new BufferedWriter(new OutputStreamWriter(p.getOutputStream()));<br />
<br />
			try<br />
			{<br />
				//out.write(inputPassphrase);<br />
out.write(tempstr[i]);<br />
try{p.waitFor();}catch(Exception ex){}<br />
				out.close();<br />
// System.out.println("hello");<br />
			}<br />
			catch(IOException io)<br />
			{<br />
				System.out.println("Exception at write! " + io.getMessage ());<br />
				return false;<br />
			}<br />
}<br />
		}<br />
		<br />
		try<br />
		{<br />
			p.waitFor();<br />
			psr_stdout.join();<br />
			psr_stderr.join();<br />
		}<br />
		catch(Exception i/*InterruptedException i*/)<br />
		{<br />
			System.out.println("Exception at waitfor! " + i.getMessage ());<br />
			return false;<br />
		}<br />
		<br />
		try<br />
		{<br />
			gpg_exitCode = p.exitValue ();<br />
		}<br />
		catch (IllegalThreadStateException itse)<br />
		{<br />
			return false;<br />
		}<br />
		<br />
		gpg_result = psr_stdout.getString();<br />
		gpg_err = psr_stdout.getString();<br />
		<br />
		return true;<br />
	}<br />
	<br />
String [] addvalue(String atr, String [] arrstr){<br />
String [] retstr =null;<br />
//System.out.println(arrstr.length);<br />
try{<br />
if (arrstr.length>0){<br />
retstr=new String[arrstr.length+1];<br />
System.arraycopy(arrstr, 0, retstr, 0, arrstr.length);<br />
retstr[arrstr.length]=atr;<br />
}<br />
else{<br />
retstr=new String[1];<br />
retstr[0]=atr;<br />
}<br />
}catch(Exception ex){<br />
retstr=new String[1];<br />
retstr[0]=atr;<br />
}<br />
<br />
return retstr;<br />
}<br />
<br />
	String [] splitstr(String inp){<br />
String [] temp=null; String atr="";<br />
for (int i=0;i<inp.length();i++){<br />
if (inp.charAt(i)==' '){<br />
temp=addvalue(atr,temp);<br />
atr="";<br />
}<br />
else{<br />
atr=atr+inp.charAt(i);<br />
}<br />
}<br />
temp=addvalue(atr,temp);<br />
//System.out.println(temp.length);<br />
//atr="";<br />
return temp;<br />
}<br />
<br />
//this is the thread handling the procedures for the runGnuPG method<br />
<br />
class ProcessStreamReader extends Thread<br />
	{<br />
		StringBuffer		stream;<br />
		InputStreamReader	in;<br />
		<br />
		final static int BUFFER_SIZE = 1024;<br />
		<br />
		/**<br />
		*	Creates new ProcessStreamReader object.<br />
		*	<br />
		*	@param	in<br />
		*/<br />
		ProcessStreamReader (InputStream in)<br />
		{<br />
			super();<br />
			<br />
			this.in = new InputStreamReader(in);<br />
<br />
			this.stream = new StringBuffer();<br />
		}<br />
		<br />
		public void run()<br />
		{<br />
			try<br />
			{       <br />
				int read;<br />
				char[] c = new char[BUFFER_SIZE];<br />
				<br />
				while ((read = in.read(c, 0, BUFFER_SIZE - 1)) > 0)<br />
				{<br />
					stream.append(c, 0, read);<br />
					if (read < BUFFER_SIZE - 1) break;<br />
				}<br />
			}<br />
			catch(IOException io) {}<br />
		}<br />
		<br />
		String getString()<br />
		{<br />
				return stream.toString();<br />
		}<br />
	}<br />
<br />
Edited by: user13340119 on Jul 17, 2011 11:53 PM<br />
<br />
Edited by: user13340119 on Jul 17, 2011 11:53 PM<br />
<br />
Edited by: user13340119 on Jul 17, 2011 11:54 PM<br />
<br />
Edited by: sabre150 on 18-Jul-2011 01:50<br />
<br />
Added code tags to make the code readable. </em>
Tagged:

Answers

  • gimbal2
    gimbal2 Member Posts: 11,949 Gold Trophy
    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.
  • sabre150
    sabre150 Member Posts: 1,405
    edited Jul 18, 2011 5:33AM
    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.
  • 876084
    876084 Member Posts: 4
    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.
  • gimbal2
    gimbal2 Member Posts: 11,949 Gold Trophy
    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
  • 876084
    876084 Member Posts: 4
    edited Jul 20, 2011 9:14AM
    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
  • sabre150
    sabre150 Member Posts: 1,405
    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!
  • 876084
    876084 Member Posts: 4
    edited Aug 29, 2011 10:02AM
    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
This discussion has been closed.