Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 12 of 12

Thread: my encrypting simple client to server program unable to get the key from client

  1. #1
    Junior Member
    Join Date
    Jan 2012
    Posts
    10
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default my encrypting simple client to server program unable to get the key from client

    hi,

    so currently i am still trying the send the aes key encrypted with private and public key from keystore but it keep java.crypto.badpaddingexception blocktype mismatch:0
    nullpointerexception

    so i tried to print out the aes keys on both size and realized i am unable to get the aes key from the client so please take a min and help me to look through my code.

    my Client
    import java.net.*;
    import java.io.*;
     import javax.crypto.*;
     import javax.crypto.spec.*;
     import java.security.*;
     import sun.misc.*;
     import java.security.cert.Certificate;
    import java.security.cert.CertificateFactory;
    import java.security.spec.*;
    public class myClient
    {  private Socket socket              = null;
       private DataInputStream  console   = null;
       private DataOutputStream streamOut = null;
     
     
       public myClient(String serverName, int serverPort,String clientuser,String serveruser) throws Exception
       {  System.out.println("Establishing connection. Please wait ...");
          try
          {  socket = new Socket(serverName, serverPort);
             System.out.println("Connected: " + socket);
             start();
          }
          catch(UnknownHostException uhe)
          {  System.out.println("Host unknown: " + uhe.getMessage());
          }
          catch(IOException ioe)
          {  System.out.println("Unexpected exception: " + ioe.getMessage());
          }
          String line = "";
    	    //get public certificate.(signed)
    	  //get private key
     
     
    CertificateFactory certfac = CertificateFactory.getInstance("X.509");
    	// //get CA CERT gen cert. closest filestream
    	// FileInputStream CA = new FileInputStream ("rootca.cer");
    	// Certificate CACert = certfac.generateCertificate(CA);
    	// CA.close();
    	// //ca cert get public
    	// PublicKey CACertPub=CACert.getPublicKey();
     
     
    	//need name for server user, generate server cert
    			FileInputStream server = new FileInputStream (serveruser+".crt");
    		Certificate serverCert = certfac.generateCertificate(server);
    			ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    	//generating the signature of the server cert
    int nRead;
    byte[] data = new byte[1024];
     
    while ((nRead = server.read(data, 0, data.length)) != -1) {
      buffer.write(data, 0, nRead);
    }
    buffer.flush();
    	server.close();
     
     
     
     
    	//
    	//verifying the Server Cert with 
    	 // File file = new File(serveruser+".sig");
    // byte[] sigBytes = new byte[(int) file.length()];
     // FileInputStream fis = new FileInputStream(file);
     // fis.read(sigBytes);
     // fis.close();
    	// boolean veri=verifySig(data,CACertPub,sigBytes);
     
     
     
     
     
    	  // if(veri==true){
     
    	//  	get private key from .keystore	  
    	PrivateKey ClientPriv=(PrivateKey)getKeyfromkeystore(clientuser);
    	  Key AESKey=AESGen();
    	  byte[] objectbyte=changetobyte(AESKey);
    	  System.out.println(asHex(AESKey.getEncoded()));
     
      //send aes key in encrypt format
    	  byte[] aessend=RSAEncryption(serverCert.getPublicKey(),ClientPriv ,objectbyte);
     
    		streamOut.write(aessend,0,aessend.length);
    		streamOut.flush();
    		byte[] signatureaes=signData(aessend,ClientPriv);
    		streamOut.writeUTF(AESEncrypt(AESKey,asHex(signatureaes)));
    		streamOut.flush();
    	 while (!line.equals("..bye"))
          {  try
     
             {
     
     
    		 line = console.readLine();
    		//encrypt line
    		if (line.length()<200){
    		String encryptedline =AESEncrypt(AESKey,line);
    		//sign the  encrypted line
    		byte[] signature=signData(getfromhex(encryptedline),ClientPriv);
    		//send line over
     
    			streamOut.writeUTF(line);
                streamOut.flush();
    			streamOut.writeUTF(AESEncrypt(AESKey,asHex(signature)));
                streamOut.flush();
    		//send the signature over
    		}
    		else System.out.println("ERROR message too long");
     
             }
             catch(IOException ioe)
             {  System.out.println("Sending error: " + ioe.getMessage());
             }
          }
    	  // }else
    	  // System.out.println("Error, Someone is Impersonating the person you are talking to.");
       }
       public void start() throws IOException
       {  console   = new DataInputStream(System.in);
          streamOut = new DataOutputStream(socket.getOutputStream());
       }
       public void stop()
       {  try
          {  if (console   != null)  console.close();
             if (streamOut != null)  streamOut.close();
             if (socket    != null)  socket.close();
          }
          catch(IOException ioe)
          {  System.out.println("Error closing ...");
          }
       }
       public static void main (String args[]) throws Exception
       {  myClient client = null;
          if (args.length != 4)
             System.out.println("Usage: java myClient host port yourname serverusername");
          else
             client = new myClient(args[0], Integer.parseInt(args[1]),args[2],args[3]);
       }
     
     
      public static byte[] signData(byte[] data, PrivateKey key) throws Exception {
        Signature signer = Signature.getInstance("SHA1withRSA");
        signer.initSign(key);
        signer.update(data);
        return (signer.sign());
      }
       public byte[] changetobyte(Key AESKey){
       	  Object Aesobj= new Object();
    	  Aesobj = (Object)AESKey;
    	  byte[] objectbyte =null;
    try{	  
    	//Change Object to byte format  
    	  ByteArrayOutputStream bos = new ByteArrayOutputStream();
    ObjectOutput out = null;
      out = new ObjectOutputStream(bos);   
      out.writeObject(Aesobj);
      objectbyte = bos.toByteArray();
      out.close();
      bos.close(); }catch(Exception e){
    	System.out.println(e);
      }
       return objectbyte;
       }
         public Key AESGen(){
      //generate aes
      Key AESKey = null;
      try{
      KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
        keyGenerator.init(128);
        AESKey = keyGenerator.generateKey();
     
    	}
    	catch(Exception e){
    		System.out.println(e);
    	}
    	return AESKey;
      }
     
     
      public Key getKeyfromkeystore(String alias){
      final String keystoreName = "./.keystore";
            final String keystorePassword = "123123123aA";
            KeyStore ks = null;
    		Key key=null;
      try{
       ks= KeyStore.getInstance("jks");
            ks.load(new FileInputStream(keystoreName), keystorePassword.toCharArray());
             key = ks.getKey(alias+"signed", keystorePassword.toCharArray());
    	}catch (Exception e){
    	System.out.println(e);
    	}
    		 return key;
      }
     
         		   public static boolean verifySig(byte[] data, PublicKey key, byte[] sig) throws Exception {
        Signature signer = Signature.getInstance("SHA1withRSA");
        signer.initVerify(key);
        signer.update(data);
        return (signer.verify(sig));
     
      }
     
         	 public byte[] RSAEncryption(PublicKey ServerPub,PrivateKey ClientPriv,byte[] Aestxt){
      //encrypts the AES key with private key then public key
      byte[] seccipher = null;
      try{
      Cipher cipher = Cipher.getInstance("RSA/ECB/NoPadding");
      cipher.init(Cipher.ENCRYPT_MODE,ClientPriv);
      byte[] firstcipher=cipher.doFinal(Aestxt);
      cipher.init(Cipher.ENCRYPT_MODE,ServerPub);
     seccipher= cipher.doFinal(firstcipher); 
      }
      catch(Exception e){
    	System.out.println(e);
      }
      return seccipher;
     
      }
     
     
      public String AESEncrypt(Key AESKey, String PlainTxt){
     //get instance of AES
     //Encrypt data
     byte[] ciphertxt = null;
     try{
      Cipher c = Cipher.getInstance("AES");
    //SecretKeySpec k =new SecretKeySpec(AESKey, "AES");
    c.init(Cipher.ENCRYPT_MODE, AESKey);
    byte[] Ptxt=getfromhex(PlainTxt);;
    ciphertxt=c.doFinal(Ptxt);
    	}
    	catch(Exception e){
    		System.out.println(e);
    	}
       return asHex(ciphertxt);
      }
     
      public static byte[] getfromhex(String s){
    	int len =s.length();
    	byte[] data=new byte[len/2];
    for(int i=0;i<len;i+=2){
    data[i/2] = (byte)((Character.digit(s.charAt(i),16)<<4) + Character.digit(s.charAt(i+1),16));
     
    }
     return data;
     
    }
     
        public static String asHex (byte buf[]) {
      //Obtain a StringBuffer object
          StringBuffer strbuf = new StringBuffer(buf.length * 2);
          int i;
     
          for (i = 0; i < buf.length; i++) {
              if (((int) buf[i] & 0xff) < 0x10)
                 strbuf.append("0");
                 strbuf.append(Long.toString((int) buf[i] & 0xff, 16));
           }
           // Return result string in Hexadecimal format
           return strbuf.toString();
      }
     
     
     
    }

    My server
    import java.net.*;
    import java.io.*;
     import javax.crypto.*;
     import javax.crypto.spec.*;
     import java.security.*;
     import sun.misc.*;
     import java.security.cert.Certificate;
    import java.security.cert.CertificateFactory;
    import java.security.spec.*;
     
    public class myServer
    {  private Socket          socket   = null;
       private ServerSocket    server   = null;
       private DataInputStream streamIn =  null;
     
       public myServer(int port,String User,String Clientuser) throws Exception
        	 {try{
    		 System.out.println("Binding to port " + port + ", please wait  ...");
             server = new ServerSocket(port);
             System.out.println("Server started: " + server);
             System.out.println("Waiting for a client ...");
             socket = server.accept();
             System.out.println("Client accepted: " + socket);
             open();
             boolean done = false;
     
    		 //get Public Cert from Client
    	 //convert to public cert.
     
     
    		// Generate a certificate from that file
    		Certificate ClientCert = getcert(Clientuser);
    //getting the public key 
    	PublicKey ClPubkey=ClientCert.getPublicKey();
     
    // //verifying the Client Cert
    	// boolean veri=verifySig(data,CACertPub,sigBytes);
     
     
    		// //get CA,certificate
    	// Certificate CACert = getcert(CA);
     
    	// //ca cert get public
    	// PublicKey CACertPub=CACert.getPublicKey();
     
     
    //get the user of my server cert
    	//need name
    	Certificate serverCert = getcert(User);
     
     
    							//get private key from .keystore		
    		 PrivateKey ServerPriv=(PrivateKey)getKeyfromkeystore(User);
    		 byte[] mybyte= new byte[5000];
    		 //get aes string
    		int rsize=  streamIn.read(mybyte);
    		byte[] encryptedobj = new byte[rsize];
    		for(int i=0; i==rsize;i++){
    		encryptedobj[i]=mybyte[i];
    		}
     
     
    		//decrypt it
    		byte[] aesobj=DecryptRSA(ServerPriv,serverCert.getPublicKey(),encryptedobj);
     
    		//convert string aes to object.
    		ByteArrayInputStream bis = new ByteArrayInputStream(aesobj);
    ObjectInput in = null;
      in = new ObjectInputStream(bis);
      Object o = in.readObject(); 
     bis.close();
      in.close();
    		Key AESKey=(Key) o;
     
    					//get signature
     
    		  System.out.println(asHex(AESKey.getEncoded()));
     
    		String sigofobjencrypted=streamIn.readUTF();
    		//decrypt signature
     
    		String sigofobj=AESDecrypt(AESKey,getfromhex(sigofobjencrypted));
    		//verify signature with encryptedobj(get sig),CLient PublicKey and the recieved signature
    	//	verifySig(encryptedobj.getBytes(),ClientCert.getPublicKey(),sigofobj.getBytes());
     
     
     
    		String line="";
    		String encryptedline = "";
     
    			String encyptedsignature = "";
     
             while (!done){  
    			try{  			//verifys the line
    			encryptedline = streamIn.readUTF();
    			 encyptedsignature = streamIn.readUTF();
    		//	 signatureString=AESDecrypt(AESKey,getfromhex(encyptedsignature));
    			//if verifying failed, print nothing
    			//verifying if Clientpublic key of the encrypted line with the signature that was send
    				//if(verifySig(encryptedline.getBytes(),ClPubkey,signatureString.getBytes())==true){
    				line=AESDecrypt(AESKey,getfromhex(encryptedline));
     
    					System.out.println(line);
    					done = line.equals("..bye");
    				//}
    			}	
     
                catch(IOException ioe)
    				{  done = true;
    				}
    //			else System.out.println("ERROR, its not"+Clientuser);
     
    				}	
     
    			}
    			catch(IOException ioe){
    				System.out.println(ioe);
    			}
       close();
       }
     
     
     
     
       public Certificate getcert(String Clientuser){
       FileInputStream Clientpersonc = null;
       		CertificateFactory certfac =null;
    		Certificate ClientCert = null;
    		try{
        Clientpersonc = new FileInputStream (Clientuser+".crt");
    		// Generate a certificate from that file
    		certfac = CertificateFactory.getInstance("X.509");
    		//convert to public cert.
    		// Generate a certificate from that file
    		ClientCert = certfac.generateCertificate(Clientpersonc);
       					Clientpersonc.close();}
    					catch(Exception e){
    						System.out.println(e);
    					}
       return ClientCert;
       }
     
       public void open() throws IOException{  
       streamIn = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
    		}
       public void close() throws IOException
       {  if (socket != null)    socket.close();
          if (streamIn != null)  streamIn.close();
       }
       public static void main(String args[])
       {  myServer server = null;
          try{
    	  if (args.length != 3)
             System.out.println("Usage: java myServer port yourname Clientname");
          else
             server = new myServer(Integer.parseInt(args[0]),args[1],args[2]);
    		}
    	catch(Exception e){
    		System.out.println(e);
    		}
       }
     
     
     public Key getKeyfromkeystore(String alias){
      final String keystoreName = "./.keystore";
            final String keystorePassword = "123123123aA";
            KeyStore ks = null;
    		Key key=null;
      try{
       ks= KeyStore.getInstance("jks");
            ks.load(new FileInputStream(keystoreName), keystorePassword.toCharArray());
             key = ks.getKey(alias+"signed", keystorePassword.toCharArray());
    	}catch (Exception e){
    	System.out.println(e);
    	}
    		 return key;
      }
     
     
      public String AESDecrypt(Key AES,byte[] encrypted){
      //decrypt aes
      String text="";
    	try{//some try catch problem
    			Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");
    			cipher.init(Cipher.DECRYPT_MODE,AES);
    			byte [] txt=cipher.doFinal(encrypted);
    			text=asHex(txt);
     
    		}
    		catch(Exception e){
    			System.out.println(e);
    		}	
    		return (text);
      }  
     public byte[] DecryptRSA(PrivateKey Serverpriv, Key ClientPub,byte[] CTxt){
       //Decrypt with private key
       //decrypt with public key
       byte[] aesbyt = null;
    	try{
    		Cipher cipher = Cipher.getInstance("RSA");
    		//init with private key   
    		cipher.init(Cipher.DECRYPT_MODE,Serverpriv);
    		byte[] Cipher1=cipher.doFinal(CTxt);
     
    		//init it with serverpublic key   
    		cipher.init(Cipher.DECRYPT_MODE,ClientPub);
    		aesbyt=cipher.doFinal(Cipher1);
    		}
     
    	catch(Exception e){
    			System.out.println(e);
    		}
    		return aesbyt;
    	}
     
       		   public static boolean verifySig(byte[] data, PublicKey key, byte[] sig) throws Exception {
        Signature signer = Signature.getInstance("SHA1withRSA");
        signer.initVerify(key);
        signer.update(data);
        return (signer.verify(sig));
      }
     
        public static String asHex (byte buf[]) {
     
      //Obtain a StringBuffer object
          StringBuffer strbuf = new StringBuffer(buf.length * 2);
          int i;
     
          for (i = 0; i < buf.length; i++) {
              if (((int) buf[i] & 0xff) < 0x10)
                 strbuf.append("0");
                 strbuf.append(Long.toString((int) buf[i] & 0xff, 16));
           }
           // Return result string in Hexadecimal format
           return strbuf.toString();
      }
     
     
     
       public static byte[] getfromhex(String s){
    	int len =s.length();
    	byte[] data=new byte[len/2];
    for(int i=0;i<len;i+=2){
    data[i/2] = (byte)((Character.digit(s.charAt(i),16)<<4) + Character.digit(s.charAt(i+1),16));
     
    }
     return data;
     
    }
     
     
    }


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: my encrypting simple client to server program unable to get the key from client

    Can you post the contents of the console(s) from when you execute the code?

    I get these errors:
    java.io.FileNotFoundException: CLient.crt (The system cannot find the file specified)
    java.io.FileNotFoundException: srvr.crt (The system cannot find the file specified)


    If the problem is sending and receiving a binary file, can you remove the references to .crt files and use some other file that will make it possible to test the code?
    If you don't understand my answer, don't ignore it, ask a question.

  3. #3
    Junior Member
    Join Date
    Jan 2012
    Posts
    10
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: my encrypting simple client to server program unable to get the key from client

    Capture.JPGCapture1.JPG

    heres both of them.

    System.out.println("fufiffofo");
    //decrypt it
    byte[] aesobj=DecryptRSA(ServerPriv,serverCert.getPublicK ey(),encryptedobj);
    System.out.println("fufiffofo");

    i tried to debug it using print ln and this was between the nonsense

  4. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: my encrypting simple client to server program unable to get the key from client

    Can you copy and paste it here. The images are not readable.

    To copy the contents of the command prompt window:
    Click on Icon in upper left corner
    Select Edit
    Select 'Select All' - The selection will show
    Click in upper left again
    Select Edit and click 'Copy'

    Paste here.


    If the problem is sending and receiving a binary file, can you remove the references to .crt files and use some other file that will make it possible to test the code?
    If you don't understand my answer, don't ignore it, ask a question.

  5. #5
    Junior Member
    Join Date
    Jan 2012
    Posts
    10
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: my encrypting simple client to server program unable to get the key from client

    ok sorry here the error

    C:\Users\hp\Desktop\project>java myServer 80 alice bob
    Binding to port 80, please wait ...
    Server started: ServerSocket[addr=0.0.0.0/0.0.0.0,port=0,localport=80]
    Waiting for a client ...
    Client accepted: Socket[addr=/127.0.0.1,port=59886,localport=80]
    fufiffofo
    javax.crypto.BadPaddingException: Blocktype mismatch: 0
    fufiffofo
    java.lang.NullPointerException

    C:\Users\hp\Desktop\project>

    C:\Users\hp\Desktop\project>java myClient 127.0.0.1 80 bob alice
    Establishing connection. Please wait ...
    Connected: Socket[addr=/127.0.0.1,port=80,localport=59886]
    d3cbf144b7bc32a18f29d598d9977354
    Exception in thread "main" java.lang.NullPointerException

    C:\Users\hp\Desktop\project>
    the problem is sending the decrypting the AESKey after being encrypted with rsa private and public key from certificate

  6. #6
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: my encrypting simple client to server program unable to get the key from client

    java.lang.NullPointerException
    Where is the stack trace that shows where the error happened?


    Has the key processing been tested without the client/server send/receive logic?
    Have you tried passing the byte array directly without the client/server write/read?
    Source-of-data => target-for-data
    If the works then try this:
    Somebytes => server => client => recvdbytes
    then compare Somebytes to recvdbytes


    What you are trying to do is:
    Source-of-data => server => client => target-for-data

    Isolate the different parts of the code and test those first two paths.
    If you don't understand my answer, don't ignore it, ask a question.

  7. The Following User Says Thank You to Norm For This Useful Post:

    Paytheprice (February 1st, 2013)

  8. #7
    Junior Member
    Join Date
    Jan 2012
    Posts
    10
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: my encrypting simple client to server program unable to get the key from client

    ok i found the error here


    //remove additional byte
    byte[] mybyte= new byte[300];
    //get aes string
    int rsize= streamIn.read(mybyte);

    byte[] encryptedobj = new byte[rsize];
    for(int i=0; i==rsize;i++){
    encryptedobj[i]=mybyte[i];

    }
    these code does not transfer the value of the byte to encryptedobj somehow.. any ideas on how to fix it?

    thanks for the help so far.

  9. #8
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: my encrypting simple client to server program unable to get the key from client

    does not transfer the value of the byte to encryptedobj
    Are you asking about the contents of encryptedobj ?
    What is in it after the loop executes? How many bytes are copied?

    How to write a for loop:
    http://docs.oracle.com/javase/tutori...bolts/for.html
    If you don't understand my answer, don't ignore it, ask a question.

  10. #9
    Junior Member
    Join Date
    Jan 2012
    Posts
    10
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: my encrypting simple client to server program unable to get the key from client

    nah i am asking how do i copy the value of the byte array to another byte array using a for loop

  11. #10
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: my encrypting simple client to server program unable to get the key from client

    Did you read the contents of the link I posted? It's described there.


    How to write a for loop:
    The for Statement (The Java™ Tutorials > Learning the Java Language > Language Basics)

    or look at the Arrays class. It has methods for copying arrays.
    Java Platform SE 7
    If you don't understand my answer, don't ignore it, ask a question.

  12. #11
    Junior Member
    Join Date
    Jan 2012
    Posts
    10
    Thanks
    1
    Thanked 0 Times in 0 Posts

    Default Re: my encrypting simple client to server program unable to get the key from client

    i am getting bytes cannot be dereferenced

  13. #12
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,162
    Thanks
    65
    Thanked 2,725 Times in 2,675 Posts

    Default Re: my encrypting simple client to server program unable to get the key from client

    Please copy the full text of the error message and paste it here. It should show the source line(s) causing the error.
    If you don't understand my answer, don't ignore it, ask a question.

Similar Threads

  1. unable to get server socket in client thread
    By shanalikhan in forum What's Wrong With My Code?
    Replies: 1
    Last Post: January 13th, 2013, 02:47 PM
  2. Replies: 0
    Last Post: May 31st, 2012, 05:35 PM
  3. server/client application fails when client closes
    By billykid in forum Java Networking
    Replies: 4
    Last Post: January 26th, 2012, 01:54 AM
  4. Simple client-server chat program
    By Saloni Patil in forum Java Networking
    Replies: 3
    Last Post: October 22nd, 2011, 09:29 AM
  5. Simple server-client trouble
    By DC200 in forum Java Networking
    Replies: 3
    Last Post: November 12th, 2009, 08:16 AM