473,406 Members | 2,293 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,406 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 23940
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 perform QueryExecute I get an error, either Socket...
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 standard libraries, about multithreading, socket...
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 now wanted to implement a similar program using C++....
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 understand the different ways to do the same thing in...
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 nothing happens whereas if I run the Java class it...
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 is to use socket programming, having the java...
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 it doesn't work). I'm not going to make you dig...
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 socket programs available? The Richard Stevens'...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

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.