Problem in a simple program

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • techani
    New Member
    • Jan 2009
    • 6

    Problem in a simple program

    hi , I have a problem in the following program (at the first link ) , which is : I send a simple encrypted message in AES , the encrypting and sending operations is done ok with no any problems , but when receiving and decrypting , the message decryption operation gives an exceptions , Although the decryption operation is done absolutely very well ( the second link improves that ) , some body tells me what is the problem Exactly please , thanks .

    the first link :
    RapidShare: Easy Filehosting

    the second link :
    RapidShare: Easy Filehosting
  • r035198x
    MVP
    • Sep 2006
    • 13225

    #2
    What exception do you get at what line number? Post the line that is reported for the exception here.

    Comment

    • techani
      New Member
      • Jan 2009
      • 6

      #3
      yes , these are the exceptions :

      java.lang.NullP ointerException
      at trying.methodsF orEncAndDec.AES _decrypt(method sForEncAndDec.j ava:83)
      at trying.UDPServe r.main(UDPServe r.java:72)
      Client send:
      Exception in thread "main" java.lang.NullP ointerException
      at trying.methodsF orEncAndDec.byt e_deconcat(meth odsForEncAndDec .java:123
      )
      at trying.UDPServe r.main(UDPServe r.java:80)
      Press any key to continue...

      Comment

      • JosAH
        Recognized Expert MVP
        • Mar 2007
        • 11453

        #4
        Originally posted by techani
        yes , these are the exceptions :

        java.lang.NullP ointerException
        at trying.methodsF orEncAndDec.AES _decrypt(method sForEncAndDec.j ava:83)
        at trying.UDPServe r.main(UDPServe r.java:72)
        Client send:
        Exception in thread "main" java.lang.NullP ointerException
        at trying.methodsF orEncAndDec.byt e_deconcat(meth odsForEncAndDec .java:123
        )
        at trying.UDPServe r.main(UDPServe r.java:80)
        Press any key to continue...
        Read that stack trace: at line 83 of method AES_decrypt something was null while it shouldn't be (hence the thrown Exception). That method was called from line 72 in your main method (the next line in the stack trace).

        Those lines should give you a clue about what was null. Check your own source.

        kind regards,

        Jos

        Comment

        • techani
          New Member
          • Jan 2009
          • 6

          #5
          ya, I have checked , but i really wasn't able to know what is the wrong in the function AES_decrypt at the source code, because i don't see or even I can't see any runtime error there in that function , have you ever tried to execute the program in the second link ?! , then you will find that it does the encryption and the decryption operation very very well

          Sooooo the problem surly absolutely is not at the (en-de)cryption operation

          But although of that, the runtime error which the compiler Alleges in line 83 in the
          AES_decrypt function, shows in some way that there is a problem in the key using operations(mayb e ???), but i say again, the key using operation at the program in the second link(you should execute it to get more imagination about the problem) is the same using operations here in the main program, i don't know whats up ! . I really got so disappointed !!!!!!!!!!!!!!! !!!!!!!!!

          Comment

          • JosAH
            Recognized Expert MVP
            • Mar 2007
            • 11453

            #6
            Originally posted by techani
            have you ever tried to execute the program in the second link ?!
            No I haven't; not many people like to be lured away in order to download something they don't know. Better post a short (compiling and running) example here in this forum that shows the unwanted behaviour. You'd get more and better responses then.

            NullPointerExce ptions can easily be pinned down with a couple of System.out.prin tln() statements at crucial locations. Your stack trace helps here.

            kind regards,

            Jos

            Comment

            • techani
              New Member
              • Jan 2009
              • 6

              #7
              ok , here take , this which was at the first link , my main program , three files :

              methodsForEncAn dDec.java :
              [code=java]
              package trying;

              import java.util.*;
              import java.io.*;
              import java.security.* ;
              import java.security.s pec.*;
              import javax.crypto.*;
              import javax.crypto.sp ec.*;
              import java.lang.Syste m.*;
              import java.lang.*;



              public class methodsForEncAn dDec{

              public static int msglength;
              public static KeyPair key ;
              public static String AESinput_key;


              public methodsForEncAn dDec(){}



              public static byte[] SHA_hash(String text)
              {
              try{
              //hash
              MessageDigest md = MessageDigest.g etInstance("SHA ");
              byte[] hash_text = md.digest(text. getBytes());
              //print
              /* String hs = new sun.misc.BASE64 Encoder().encod e(hash_text);
              System.out.prin tln("---> hash: <---");
              System.out.prin tln(hs);*/
              return hash_text;
              }
              catch( Exception e )
              {
              e.printStackTra ce();
              }
              return null;
              }
              //############### ############### ############### ############### #
              public static byte[] AES_encrypt(byt e[] plain_Text,Stri ng key)
              {
              try{
              // Key
              byte[] byte_key = key.getBytes();
              SecretKeySpec final_key = new SecretKeySpec(b yte_key,"AES");

              // ENCRYPTION
              Cipher m_encrypter = Cipher.getInsta nce("AES/ECB/PKCS5Padding");
              m_encrypter.ini t(Cipher.ENCRYP T_MODE , final_key);
              byte[] encrypted_Text = m_encrypter.doF inal(plain_Text );

              // unhide this if you want to see the sent message
              /*System.out.pri ntln("---> After Encryption with AES: <---");
              for (int i=0 ; i<encrypted_Tex t.length ; i++)
              System.out.prin tln((char)encry pted_Text[i]);
              */

              return encrypted_Text;
              }
              //catch exceptions
              catch( Exception e )
              {
              e.printStackTra ce();
              }
              return null;
              }
              //############### ############### ############### ############### #
              public static byte[] AES_decrypt(byt e[] encrypted_Text, String key)
              {
              try{
              // Key
              byte[] byte_key = key.getBytes();
              SecretKeySpec final_key = new SecretKeySpec(b yte_key,"AES");

              // DECRYPTION
              Cipher m_decrypter = Cipher.getInsta nce("AES/ECB/PKCS5Padding");
              m_decrypter.ini t(Cipher.DECRYP T_MODE , final_key);
              byte[] decrypted_Text = m_decrypter.doF inal(encrypted_ Text);

              // Print
              /* String dt = new sun.misc.BASE64 Encoder().encod e(decrypted_Tex t);
              System.out.prin tln("---> After Decryption with AES: <---");
              System.out.prin tln(dt);*/

              return decrypted_Text;
              }
              //catch exceptions
              catch( Exception e )
              {
              e.printStackTra ce();
              }
              return null;
              }
              //############### ############### ############### ############### #
              public static byte[] byte_concat(byt e[] a , byte[] b)
              {
              byte[] x = new byte[a.length + b.length];
              for(int i=0 ; i<a.length ; i++)
              {
              x[i]=a[i];
              }
              for(int j=a.length ; j<x.length ; j++)
              {
              x[j]=b[j-a.length];
              }
              return x;
              }
              //############### ############### ############### ############### #
              public static byte[] byte_deconcat(b yte[] a)
              {
              //20 byte = 160bit = length of SHA hash to be deconcat
              byte[] x = new byte[a.length - 20];
              for(int i=0 ; i<x.length ; i++)
              {
              x[i]=a[i];
              }
              //print
              System.out.prin tln("---> After de-concat : <---");
              for (int i=0 ; i<x.length ; i++)
              {
              System.out.prin t((char)x[i]);
              }
              System.out.prin tln("");
              return x;
              }

              }
              [/code]
              UDPServer.java :
              [code=java]
              package trying;


              import java.io.*;
              import java.net.*;
              import javax.swing.*;
              import java.util.*;
              import java.security.* ;
              import java.security.s pec.*;
              import javax.crypto.*;
              import javax.crypto.sp ec.*;
              import java.lang.Syste m.*;
              import java.lang.*;


              public class UDPServer{



              public static void main(String args[]){

              //Create receiver Socket
              DatagramSocket aSocket = null;


              try{
              //1.create socket at agreed port
              aSocket = new DatagramSocket( 1234);


              //2. Define Receeiver Packet Size Size
              byte[] buffer = new byte[methodsForEncAn dDec.msglength];



              Provider sunjce = new com.sun.crypto. provider.SunJCE ();
              Security.addPro vider(sunjce);



              // 3. Listening....
              while(true){
              DatagramPacket request = new DatagramPacket( buffer, buffer.length);
              aSocket.receive (request);




              //------------------------------- Decryption operation with AES--------------------------------------------------------------------



              String recieved=new String(request. getData()).trim ();

              char[] AES_encrypted_C =recieved.toCha rArray();

              byte[] AES_encrypted_B =new byte[AES_encrypted_C .length];

              for (int i=0 ; i<AES_encrypted _C.length ; i++)
              AES_encrypted_B[i]=(byte)AES_encr ypted_C[i];



              // unhide the following(lines :66-68) if you want to see that the received message is as same as the sent one
              /*
              System.out.prin tln("---> After Recieving: <---");
              for (int i=0 ; i<AES_encrypted _B.length ; i++)
              System.out.prin tln((char)AES_e ncrypted_B[i]);
              */


              byte [] AES_decrypted = methodsForEncAn dDec.AES_decryp t(AES_encrypted _B,methodsForEn cAndDec.AESinpu t_key);



              //---------------------------------------------------------------------------------------------------------------------------------------------

              System.out.prin tln("Client send: ");

              byte [] AES_without_has h =methodsForEncA ndDec.byte_deco ncat(AES_decryp ted);


              }
              }catch (SocketExceptio n e){System.out.p rintln("Socket: " + e.getMessage()) ;
              }catch (IOException e) {System.out.pri ntln("IO: " + e.getMessage()) ;
              }finally {if(aSocket != null) aSocket.close() ;}
              }
              }
              [/code]
              UDPClient.java :
              [code=java]
              package trying;

              import java.io.*;
              import java.net.*;
              import javax.swing.*;
              import java.util.*;
              import java.security.* ;
              import java.security.s pec.*;
              import javax.crypto.*;
              import javax.crypto.sp ec.*;
              import java.lang.Syste m.*;
              import java.lang.*;



              public class UDPClient{




              public static void main(String args[]){

              DatagramSocket aSocket = null;


              try {

              // 1. Create Client Socket
              aSocket = new DatagramSocket( );



              //------------------------------- Encryption operation with AES--------------------------------------------------------------------

              //Declare SunJCE provider.
              Provider sunjce = new com.sun.crypto. provider.SunJCE ();
              Security.addPro vider(sunjce);

              //Get Plaintext
              Scanner my_object = new Scanner(System. in);
              System.out.prin tln("---> Enter the plainText: <---");
              String plain = my_object.nextL ine();

              //Hashing then Concatenating
              byte[] hash = methodsForEncAn dDec.SHA_hash(p lain);
              byte[] msg_with_hash = methodsForEncAn dDec.byte_conca t(plain.getByte s() , hash);



              //Get AES key
              System.out.prin tln("---> Enter 16 characters key: <---");
              methodsForEncAn dDec.AESinput_k ey/*String kyy */= my_object.nextL ine();

              //AES encrypt
              byte [] AES_encrypted = methodsForEncAn dDec.AES_encryp t(msg_with_hash ,methodsForEncA ndDec.AESinput_ key/*kyy*/);

              //convert into character array
              char[] AES_encrypted_C =new char[AES_encrypted.l ength];
              for (int i=0 ; i<AES_encrypted .length ; i++)
              AES_encrypted_C[i]=(char)AES_encr ypted[i];

              //convert into string
              String AES_encrypted_S =new String(AES_encr ypted_C);

              //then convert the string into array of bytes to be sent
              byte[] AES_finalencryp ted=AES_encrypt ed_S.getBytes() ;


              //---------------------------------------------------------------------------------------------------------------------------------------------




              //3.Define the server IP..
              InetAddress aHost = InetAddress.get ByName("localho st");//master


              //4. Attatch the socket to the Server Port..
              int serverPort =1234;



              //5. define the packet to be sent to the server ...
              DatagramPacket request =
              new DatagramPacket( AES_finalencryp ted,AES_encrypt ed_S.length(), aHost, serverPort);


              //6. Send the Packet to the server...
              aSocket.send(re quest);


              methodsForEncAn dDec.msglength= AES_finalencryp ted.length;


              }catch (SocketExceptio n e){System.out.p rintln("Socket: " + e.getMessage()) ;
              }catch (IOException e){System.out.p rintln("IO: " + e.getMessage()) ;
              }finally {if(aSocket != null) aSocket.close() ;}
              }
              }
              [/code]
              and this which was at the second link :

              AES_SHA_RSA.jav a :
              [code=java]
              import java.util.*;
              import java.io.*;
              import java.security.* ;
              import java.security.s pec.*;
              import javax.crypto.*;
              import javax.crypto.sp ec.*;
              import java.lang.Syste m.*;
              import java.lang.*;

              /*Note 1 : I use 'Base64' to display cipher texts in terms
              //of hex digits only , If you don't want to use it , you can
              //do this : Scanner.out.pri ntln(new String(cipher_T ext));

              //Note 2 : input msg cannot be very long , because i don't
              //use update() yet, if you want to input a msg with any
              //length then use update() in conjunction with doFinal()

              //Note 3 : it may be better to build a new function to initia-
              //-lize the ciphers , i.e. to put the .getInstance() constru-
              //-ctors there , so there will be only one instance of every
              //cipher...

              //Note 4 : the program firstly computes the hash of the msg , then //concatenates the hash to the msg , now we encrypt (using RSA or //AES ) the new msg. After decryption , it deconcatenates the hash to //obtain the original msg.
              */

              public class AES_SHA_RSA
              {
              public static void main(String args[])
              {
              //Declare SunJCE provider.
              Provider sunjce = new com.sun.crypto. provider.SunJCE ();
              Security.addPro vider(sunjce);

              //Get Plaintext
              Scanner my_object = new Scanner(System. in);
              System.out.prin tln("---> Enter the plainText: <---");
              String plain = my_object.nextL ine();

              //Hashing then Concatenating
              byte[] hash = SHA_hash(plain) ;
              byte[] msg_with_hash = byte_concat(pla in.getBytes() , hash);

              //Get AES key
              System.out.prin tln("---> Enter the 128-bit key: <---");
              String input_key = my_object.nextL ine();

              //AES en(de)crypt
              byte [] AES_encrypted = AES_encrypt(msg _with_hash,inpu t_key);
              byte [] AES_decrypted = AES_decrypt(AES _encrypted,inpu t_key);
              byte [] AES_without_has h = byte_deconcat(A ES_decrypted);

              }//end




              //############### ############### ############### ############### #
              public static byte[] SHA_hash(String text)
              {
              try{
              //hash
              MessageDigest md = MessageDigest.g etInstance("SHA ");
              byte[] hash_text = md.digest(text. getBytes());
              //print
              String hs = new sun.misc.BASE64 Encoder().encod e(hash_text);
              System.out.prin tln("---> hash: <---");
              System.out.prin tln(hs);
              return hash_text;
              }
              catch( Exception e )
              {
              e.printStackTra ce();
              }
              return null;
              }
              //############### ############### ############### ############### #
              public static byte[] AES_encrypt(byt e[] plain_Text,Stri ng key)
              {
              try{
              // Key
              byte[] byte_key = key.getBytes();
              SecretKeySpec final_key = new SecretKeySpec(b yte_key,"AES");

              // ENCRYPTION
              Cipher m_encrypter = Cipher.getInsta nce("AES/ECB/PKCS5Padding");
              m_encrypter.ini t(Cipher.ENCRYP T_MODE , final_key);
              byte[] encrypted_Text = m_encrypter.doF inal(plain_Text );

              // Print
              String ct = new sun.misc.BASE64 Encoder().encod e(encrypted_Tex t);
              System.out.prin tln("---> After Encryption with AES: <---");
              System.out.prin tln(ct);

              return encrypted_Text;
              }
              //catch exceptions
              catch( Exception e )
              {
              e.printStackTra ce();
              }
              return null;
              }
              //############### ############### ############### ############### #
              public static byte[] AES_decrypt(byt e[] encrypted_Text, String key)
              {
              try{
              // Key
              byte[] byte_key = key.getBytes();
              SecretKeySpec final_key = new SecretKeySpec(b yte_key,"AES");

              // DECRYPTION
              Cipher m_decrypter = Cipher.getInsta nce("AES/ECB/PKCS5Padding");
              m_decrypter.ini t(Cipher.DECRYP T_MODE , final_key);
              byte[] decrypted_Text = m_decrypter.doF inal(encrypted_ Text);

              // Print
              String dt = new sun.misc.BASE64 Encoder().encod e(decrypted_Tex t);
              System.out.prin tln("---> After Decryption with AES: <---");
              System.out.prin tln(dt);

              return decrypted_Text;
              }
              //catch exceptions
              catch( Exception e )
              {
              e.printStackTra ce();
              }
              return null;
              }
              //############### ############### ############### ############### #
              public static byte[] byte_concat(byt e[] a , byte[] b)
              {
              byte[] x = new byte[a.length + b.length];
              for(int i=0 ; i<a.length ; i++)
              {
              x[i]=a[i];
              }
              for(int j=a.length ; j<x.length ; j++)
              {
              x[j]=b[j-a.length];
              }
              return x;
              }
              //############### ############### ############### ############### #
              public static byte[] byte_deconcat(b yte[] a)
              {
              //20 byte = 160bit = length of SHA hash to be deconcat
              byte[] x = new byte[a.length - 20];
              for(int i=0 ; i<x.length ; i++)
              {
              x[i]=a[i];
              }
              //print
              System.out.prin tln("---> After de-concat : <---");
              for (int i=0 ; i<x.length ; i++)
              {
              System.out.prin t((char)x[i]);
              }
              System.out.prin tln("");
              return x;
              }

              }
              [/code]
              and what do you mean by : can easily be pinned down with a couple of System.out.prin tln() statements at crucial locations??? sorry i didn't understand , could you explain well please ??? thanks .
              Last edited by Nepomuk; Feb 26 '09, 10:56 PM. Reason: Please use [CODE] tags and don't use the [B] tag so much, it makes the text pretty ugly.

              Comment

              • r035198x
                MVP
                • Sep 2006
                • 13225

                #8
                Originally posted by techani
                ok , here take , this which was at the first link , my main program , three files :
                That is not required. You were supposed to post only the lines at and just before the line reported for the exception by your stacktrace.



                Originally posted by techani
                and what do you mean by : (can easily be pinned down with a couple of System.out.prin tln() statements at crucial locations) ??? sorry i didn't understand , could you explain well please ??? thanks .
                You have got to be kidding me.

                Comment

                • JosAH
                  Recognized Expert MVP
                  • Mar 2007
                  • 11453

                  #9
                  I wrote: "Better post a short (compiling and running) example here in this forum that shows the unwanted behaviour. You'd get more and better responses then."

                  kind regards,

                  Jos

                  Comment

                  • BSCode266
                    New Member
                    • Jan 2007
                    • 38

                    #10
                    I'm missing line numbers, what line is exactly 83?

                    Comment

                    • techani
                      New Member
                      • Jan 2009
                      • 6

                      #11
                      I'm very sorry for late , here is the line :


                      SecretKeySpec final_key = new SecretKeySpec(b yte_key,"AES");

                      thanks.

                      Comment

                      • techani
                        New Member
                        • Jan 2009
                        • 6

                        #12
                        ??????????????? ??????????????? ?????????

                        Comment

                        • jkmyoung
                          Recognized Expert Top Contributor
                          • Mar 2006
                          • 2057

                          #13
                          Try adding the following lines before that line:

                          Code:
                          if ( byte_key == null){
                          System.out.println("My program will die here");
                          }

                          Also please use code tags. eg [ code ] without the spaces [ / code]

                          Comment

                          Working...