472,340 Members | 1,743 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,340 software developers and data experts.

Java Socket Programming with AES encryption

This is how my test program works.

Server will encrypt some text and sends it over to the client.
The client will then decrypts it.

However I have some problem decrypting it. When I play around with the key and the plaintext, sometime it is able to decrypt. I think it should be some ASCII character problems.

Right now, I am using out.writeUTF(new String(encrypted)); and on this other side I use in.readUTF() to get the string. Lastly, I convert the string to byte for decryption.

Is there anyway to fix this problem? Basically, what and how do I send the ciphertext over and how can I decrypt properly on the other side.

Here are my codes, thanks in advance..

Server:
Expand|Select|Wrap|Line Numbers
  1. import java.io.*;
  2. import java.net.*;
  3.  
  4. import java.security.*;
  5. import javax.crypto.*;
  6. import javax.crypto.spec.*;
  7.  
  8. public class RealEchoServer{
  9.     public static void main(String[] args ){
  10.         int i = 1;
  11.         try{
  12.              ServerSocket s = new ServerSocket(9003);
  13.  
  14.              for (;;){
  15.                  Socket incoming = s.accept( );
  16.                  System.out.println("Spawning " + i);
  17.                  new RealEchoHandler(incoming, i).start();
  18.                  i++;
  19.              }
  20.         } catch (Exception e){ System.out.println(e); }
  21.     }
  22. }
  23.  
  24. class RealEchoHandler extends Thread{
  25.     DataInputStream in;
  26.     DataOutputStream out;
  27.     private Socket incoming;
  28.     private int counter;
  29.  
  30.     public RealEchoHandler(Socket i, int c){
  31.         incoming = i;
  32.         counter = c;
  33.     }
  34.  
  35.     public void run(){
  36.         try {
  37.  
  38.  
  39.             String key1 = "1234567812345678"; 
  40.               byte[] key2 = key1.getBytes();
  41.               SecretKeySpec secret = new SecretKeySpec(key2, "AES");
  42.             String msg = "Singapore Malaysia Japan India Indonesia HongKong Taiwan China England";
  43.             Cipher cipher = Cipher.getInstance("AES");        
  44.                 cipher.init(Cipher.ENCRYPT_MODE, secret);
  45.                byte[] encrypted = cipher.doFinal(msg.getBytes());
  46.  
  47.             in = new DataInputStream(incoming.getInputStream());
  48.             out = new DataOutputStream(incoming.getOutputStream());
  49.  
  50.             boolean done = false;
  51.             String str="";
  52.             out.writeUTF("Connected!\n");
  53.             out.flush();
  54.             while (!done){
  55.                 out.writeUTF(">");
  56.                 out.flush();
  57.                 str = in.readUTF();
  58.                 System.out.println(in+":"+str);
  59.                 if (str == null)
  60.                     done = true;
  61.                 else{
  62.                     System.out.println("Sending Ciphertext : " + new String(encrypted));
  63.                     out.writeUTF(new String(encrypted));
  64.                     out.flush();
  65.                 }
  66.             }
  67.             incoming.close();
  68.          } catch (Exception e){
  69.              System.out.println(e);
  70.          }
  71.     }
  72. }
  73.  
Client:
Expand|Select|Wrap|Line Numbers
  1. import java.io.*;
  2. import java.net.*;
  3. import java.security.*;
  4. import javax.crypto.*;
  5. import javax.crypto.spec.*;
  6. import java.util.*;
  7.  
  8. class RealSocketTest{
  9.     public static void main(String[] args) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException{
  10.  
  11.         String str = "";
  12.         String str2 = "";
  13.         DataOutputStream out;
  14.         DataInputStream in;
  15.  
  16.         try {
  17.             Socket t = new Socket("127.0.0.1", 9003);
  18.             in = new DataInputStream(t.getInputStream());
  19.             out = new DataOutputStream(t.getOutputStream());
  20.             BufferedReader br = new BufferedReader (new InputStreamReader(System.in));
  21.  
  22.             boolean more = true;
  23.             System.out.println(in.readUTF());    
  24.  
  25.             while (more) {
  26.                 str = in.readUTF();
  27.                 System.out.print(str);
  28.                 str2 = br.readLine();
  29.                 out.writeUTF(str2);
  30.                 out.flush();
  31.                 str = in.readUTF();
  32.  
  33.                 System.out.println("Encrypted Info: " + str);
  34.  
  35.                 try {
  36.  
  37.                     String key1 = "1234567812345678"; 
  38.                       byte[] key2 = key1.getBytes();
  39.                       SecretKeySpec secret = new SecretKeySpec(key2, "AES");
  40.  
  41.                     Cipher cipher = Cipher.getInstance("AES");        
  42.  
  43.                     cipher.init(Cipher.DECRYPT_MODE, secret);
  44.                     byte[] decrypted = cipher.doFinal(str.getBytes());
  45.                     System.out.println("Decrypted Info: " + new String(decrypted));
  46.                 }
  47.                 catch(BadPaddingException e){
  48.                     System.out.println("Wrong Key!");
  49.                 }
  50.                 catch(InvalidKeyException f) {
  51.                     System.out.println("Invalid Key!");
  52.                 }
  53.             }
  54.         } 
  55.         catch(IOException e){
  56.             System.out.println("Error");
  57.         }
  58.     }
  59. }
  60.  
  61.  
Oct 26 '08 #1
2 23404
Nepomuk
3,112 Expert 2GB
This is how my test program works.

Server will encrypt some text and sends it over to the client.
The client will then decrypts it.

However I have some problem decrypting it. When I play around with the key and the plaintext, sometime it is able to decrypt. I think it should be some ASCII character problems.
Hi!
You say, sometimes you can decrypt? So I guess, sometimes you can't. Can you give us an example for a few keys and plaintexts that work and some that don't?

Greetings,
Nepomuk
Oct 27 '08 #2
Thanks, that answers my question
Oct 28 '08 #3

Sign in to post your reply or Sign up for a free account.

Similar topics

0
by: Dominique | last post by:
I am trying to communicate to a prolog server from a java client, however even though the connection is successfully made every time I try to...
9
by: | last post by:
Java has packages (libraries) for everything. EVERYTHING. Instead, C++ is too poor in its classes. Is there a concept to extend C++ with other...
3
by: Jay | last post by:
Hi, I implemeneted an FTP client and server long time back using Java. I found sockets porgramming in java quite useful and easy to handle. I...
11
by: DrUg13 | last post by:
In java, this seems so easy. You need a new object Object test = new Object() gives me exactly what I want. could someone please help me...
133
by: Gaurav | last post by:
http://www.sys-con.com/story/print.cfm?storyid=45250 Any comments? Thanks Gaurav
12
by: Mark Fink | last post by:
I wrote a Jython class that inherits from a Java class and (thats the plan) overrides one method. Everything should stay the same. If I run this...
4
by: MimiMi | last post by:
I want an application written in C# to start an application written in java and be able to communicate with each other. I believe one way to do this...
2
by: jlparise | last post by:
Hey everyone, I am really rusty on my Java socket programming and am having some confusing problems. I don't need the code debugged(even though...
3
by: TsanChung | last post by:
I want to make a java TCP socket client to communicate with a TCP server socket on linux. Are there some sample C unix server and java client...
0
by: teenabhardwaj | last post by:
How would one discover a valid source for learning news, comfort, and help for engineering designs? Covering through piles of books takes a lot of...
0
by: Kemmylinns12 | last post by:
Blockchain technology has emerged as a transformative force in the business world, offering unprecedented opportunities for innovation and...
0
by: CD Tom | last post by:
This only shows up in access runtime. When a user select a report from my report menu when they close the report they get a menu I've called Add-ins...
0
by: antdb | last post by:
Ⅰ. Advantage of AntDB: hyper-convergence + streaming processing engine In the overall architecture, a new "hyper-convergence" concept was...
0
by: Matthew3360 | last post by:
Hi there. I have been struggling to find out how to use a variable as my location in my header redirect function. Here is my code. ...
2
by: Matthew3360 | last post by:
Hi, I have a python app that i want to be able to get variables from a php page on my webserver. My python app is on my computer. How would I make it...
0
by: Arjunsri | last post by:
I have a Redshift database that I need to use as an import data source. I have configured the DSN connection using the server, port, database, and...
0
hi
by: WisdomUfot | last post by:
It's an interesting question you've got about how Gmail hides the HTTP referrer when a link in an email is clicked. While I don't have the specific...
0
by: Matthew3360 | last post by:
Hi, I have been trying to connect to a local host using php curl. But I am finding it hard to do this. I am doing the curl get request from my web...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.