473,549 Members | 2,625 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Java Socket Programming with AES encryption

2 New Member
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(ne w String(encrypte d)); 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 24026
Nepomuk
3,112 Recognized Expert Specialist
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
rayoflight
2 New Member
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
2692
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 closed or null etc. Can anyone help? I am using SICStus prolog. Currently my prolog server looks like: :- write('starting'),nl. :-...
9
4018
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 programming etc? I do not speak about libraries programmed only in one platform (e.g. MFC) but about standard C++ libraries.
3
14855
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++. My questions are 1. How good a language is C++ for network programming? 2. what are good onine resources to learn C++ network programming? 3. How...
11
9218
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 C++. I find my self sometimes, trying Object app = Object(); Object *app = Object(); Object app = new Object();
133
8457
by: Gaurav | last post by:
http://www.sys-con.com/story/print.cfm?storyid=45250 Any comments? Thanks Gaurav
12
5896
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 says: usage: java fit.FitServer host port socketTicket -v verbose I think this is because I do not understand the jython mechanism for...
4
5926
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 application as a server. Something like this: In the java application: ServerSocket ss = new ServerSocket(localPort); //Listen for a connection to...
2
10504
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 through all the abstraction layers and such. Anyways here is my issue. The application sends a request for data to the server and the server...
3
11644
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' "Unix network programming" book described a TCP server (tcpcliserv04.c) and client (tcpcli04.c). I compiled and executed them successfully as follows:...
0
7541
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7734
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
7979
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
0
7826
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
5107
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3512
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3493
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1074
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
781
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

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.