Encryption in Java

Reply

Join Date: Mar 2009
Posts: 123
Reputation: neutralfox is an unknown quantity at this point 
Solved Threads: 0
neutralfox neutralfox is offline Offline
Junior Poster

Encryption in Java

 
0
  #1
Apr 6th, 2009
Hello everyone,
I am currently developing a chat application and I want to encrypt all send messages. I am using the example below:

  1. import javax.crypto.Cipher;
  2. import javax.crypto.KeyGenerator;
  3. import javax.crypto.NoSuchPaddingException;
  4. import javax.crypto.IllegalBlockSizeException;
  5. import javax.crypto.BadPaddingException;
  6. import java.security.Key;
  7. import java.security.Security;
  8. import java.security.NoSuchAlgorithmException;
  9. import java.security.InvalidKeyException;
  10. public class DESCryptoTest {
  11. public static void main(String[] args) {
  12. //Security.addProvider(new com.sun.crypto.provider.SunJCE());
  13. try {
  14. KeyGenerator kg = KeyGenerator.getInstance("DES");
  15. Key key = kg.generateKey();
  16.  
  17. Cipher cipher = Cipher.getInstance("DES");
  18.  
  19. byte[] data = "Hello World!".getBytes();
  20. System.out.println("Original data : " + new String(data));
  21.  
  22. cipher.init(Cipher.ENCRYPT_MODE, key);
  23. byte[] result = cipher.doFinal(data);
  24. System.out.println("Encrypted data: " + new String(result));
  25.  
  26. cipher.init(Cipher.DECRYPT_MODE, key);
  27. byte[] original = cipher.doFinal(result);
  28.  
  29. System.out.println("Decrypted data: " + new String(original));
  30.  
  31. System.out.println("Key : "+ key.toString());
  32.  
  33. }
  34.  
  35. catch (NoSuchAlgorithmException e) {
  36. e.printStackTrace();
  37. }
  38. catch (NoSuchPaddingException e) {
  39. e.printStackTrace();
  40. }
  41. catch (InvalidKeyException e) {
  42. e.printStackTrace();
  43. }
  44. catch (IllegalStateException e) {
  45. e.printStackTrace();
  46. }
  47. catch (IllegalBlockSizeException e) {
  48. e.printStackTrace();
  49. }
  50. catch (BadPaddingException e) {
  51. e.printStackTrace();
  52. }
  53. }
  54. }

But the problem is that I don't know how to save the key, heres it works because its in the same class.

Can someone help me please!! Is there any other way to secure, encrypt message while sending over the network?

Thanks for the answer.
Reply With Quote Quick reply to this message  
Join Date: Apr 2005
Posts: 16,146
Reputation: jbennet is a name known to all jbennet is a name known to all jbennet is a name known to all jbennet is a name known to all jbennet is a name known to all jbennet is a name known to all 
Solved Threads: 530
Moderator
Featured Poster
jbennet's Avatar
jbennet jbennet is offline Offline
Moderator

Re: Encryption in Java

 
-7
  #2
Apr 6th, 2009
Can someone help me please!! Is there any other way to secure, encrypt message while sending over the network?
You could use SSL?
If i am helpful, please give me reputation points.
Reply With Quote Quick reply to this message  
Join Date: Mar 2009
Posts: 123
Reputation: neutralfox is an unknown quantity at this point 
Solved Threads: 0
neutralfox neutralfox is offline Offline
Junior Poster

Re: Encryption in Java

 
0
  #3
Apr 6th, 2009
No, I want to use an encryption technique! Its for learning purposes. But how to use SSL on a chat program and what is the purpose of this protocol, I just know that its secure, does the SSL layer use some encryption mechanisms?

I still want to know how to use the piece of code above. The problem is just the key, how to store the key, because it keeps on generating a new key, if i can store the Key key then i will be able to continue.


Thanks for the answer. Bye.
Last edited by neutralfox; Apr 6th, 2009 at 11:45 pm.
Reply With Quote Quick reply to this message  
Join Date: Apr 2005
Posts: 16,146
Reputation: jbennet is a name known to all jbennet is a name known to all jbennet is a name known to all jbennet is a name known to all jbennet is a name known to all jbennet is a name known to all 
Solved Threads: 530
Moderator
Featured Poster
jbennet's Avatar
jbennet jbennet is offline Offline
Moderator

Re: Encryption in Java

 
-7
  #4
Apr 6th, 2009
yes, SSL/TLS is an enecrypted protocol for key-based data transmission

http://en.wikipedia.org/wiki/Secure_Sockets_Layer

Re: your program. If you just want to save the key why not use the printwriter and stream/buffered reader classes to read/write to a text file.
Last edited by jbennet; Apr 6th, 2009 at 11:50 pm.
If i am helpful, please give me reputation points.
Reply With Quote Quick reply to this message  
Join Date: Apr 2008
Posts: 972
Reputation: JamesCherrill is just really nice JamesCherrill is just really nice JamesCherrill is just really nice JamesCherrill is just really nice JamesCherrill is just really nice 
Solved Threads: 146
JamesCherrill JamesCherrill is offline Offline
Posting Shark

Re: Encryption in Java

 
0
  #5
Apr 7th, 2009
Have a look at the Preferences class. It allows you to store & retrieve simple strings, ints, booleans etc in a very easy way, without having to bother about the details of where and how they are stored, basically:
  1. Preferences prefs = Preferences.userRoot();
  2. prefs.put(prefsItemName, prefsItemValue);
  3. ...
  4. prefs.get(prefsItemName, "");
Reply With Quote Quick reply to this message  
Join Date: Dec 2004
Posts: 4,188
Reputation: peter_budo has much to be proud of peter_budo has much to be proud of peter_budo has much to be proud of peter_budo has much to be proud of peter_budo has much to be proud of peter_budo has much to be proud of peter_budo has much to be proud of peter_budo has much to be proud of peter_budo has much to be proud of peter_budo has much to be proud of 
Solved Threads: 482
Moderator
Featured Poster
peter_budo's Avatar
peter_budo peter_budo is online now Online
Code tags enforcer

Re: Encryption in Java

 
0
  #6
Apr 7th, 2009
I'm not networking guy but I may chip in with little.
Any chat application always has server side and client side of application otherwise trying to connect numerous users together would quickly become nightmare. There you will have private encryption key for server and public. There are variety ways of working out public key, but most common is called "handshake" where client after establishing connection send a random number to server and receive unique public key.

I found few examples/resources, they may not be exactly spot on, but hopefully you will find them useful Handshake.java for SSL handshake message in Jessie application, Using JSSE for secure socket communication or this Sun tutorials on Socket Communications and Cryptography. There is also this book Cryptography with Java, but is targeting cryptography and you may not find to much on networking
Learn to see in another's calamity the ills which you should avoid.
Publilius Syrus
(~100 BC)

LJC - London Java Community, Graduate & Undergraduate Software Development Community, JAVAWUG (Java Web User Group), The London Android Group
Reply With Quote Quick reply to this message  
Join Date: Mar 2009
Posts: 21
Reputation: hkansal is an unknown quantity at this point 
Solved Threads: 3
hkansal's Avatar
hkansal hkansal is offline Offline
Newbie Poster

Re: Encryption in Java

 
0
  #7
Apr 7th, 2009
Hello NeutralFox,

Actually it's good that you cannot save the key. That makes your application more secure - Randomness increases security. All you need is an algorithm to use this evil.

Here is what you can do-
Since your server would be up and running to accept connections, generate a key whenever the server is started. You can save that Key object in the runtime(right?).
Each time a client connects to the server and authenticates, you send the key to the client and to next client and so on as the clients keep coming in.
Generate a new key everytime you bounce the server.

The above method has the following analysis:
Advantages:
1. The key is new everytime the server starts fresh.
2. The key object is to be generated and saved only at runtime and not hardcoded.
3. You can use groups of keys or individual keys or a single key.
4. High performance boost as the message encryption is no longer the network's headache.

Limitations:
1. The first time you send the key, that too needs to be .. hehe.. encrypted.

There is a method to workaround that. If you can think, well and good, else we are always there

Regards,
HKansal
Reply With Quote Quick reply to this message  
Join Date: Apr 2005
Posts: 16,146
Reputation: jbennet is a name known to all jbennet is a name known to all jbennet is a name known to all jbennet is a name known to all jbennet is a name known to all jbennet is a name known to all 
Solved Threads: 530
Moderator
Featured Poster
jbennet's Avatar
jbennet jbennet is offline Offline
Moderator

Re: Encryption in Java

 
-7
  #8
Apr 7th, 2009
Each time a client connects to the server and authenticates, you send the key to the client
As you dont have the key yet, the key would have to be sent unencrypted which means it can be sniffed, defeating the point of the encryption.
If i am helpful, please give me reputation points.
Reply With Quote Quick reply to this message  
Join Date: Apr 2008
Posts: 972
Reputation: JamesCherrill is just really nice JamesCherrill is just really nice JamesCherrill is just really nice JamesCherrill is just really nice JamesCherrill is just really nice 
Solved Threads: 146
JamesCherrill JamesCherrill is offline Offline
Posting Shark

Re: Encryption in Java

 
0
  #9
Apr 7th, 2009
Originally Posted by jbennet View Post
As you dont have the key yet, the key would have to be sent unencrypted which means it can be sniffed, defeating the point of the encryption.
I think the only ways round this involve at least one public/private key pair, eg client generates random key (or half a key), encrypts it with server's public key (which it can safely get via a plain-text request) and sends it to the server; only server can decrypt it. The server then generates a random (half) key and sends that back to the client using the client's public key for encryption ditto. Even if the link is totally public, only the client and the server know both random key halves, and are thus able to decrypt messages encrypted using them.
For ultimate security both pairs of public/private keys could be generated from scratch for each session, although this is almost certainly overkill!
Reply With Quote Quick reply to this message  
Join Date: Dec 2008
Posts: 53
Reputation: neilcoffey will become famous soon enough neilcoffey will become famous soon enough 
Solved Threads: 6
neilcoffey neilcoffey is offline Offline
Junior Poster in Training

Re: Encryption in Java

 
1
  #10
Apr 7th, 2009
As people have mentioned, you need to use asymmetric encryption at the very start of the conversation to send the sessiion key to the server. Use RSA for this. Essentially, you create a public/private RSA key pair as follows:

  1. KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
  2. kpg.initialize(2048);
  3. KeyPair kp = kpg.genKeyPair();
  4. KeyFactory fact = KeyFactory.getInstance("RSA");
  5. RSAPublicKeySpec pub = fact.getKeySpec(kp.getPublic(), RSAPublicKeySpec.class);
  6. RSAPrivateKeySpec priv = fact.getKeySpec(kp.getPrivate(), RSAPrivateKeySpec.class);

Each of the key spec objects has methods that give you a couple of BigIntegers. Save the private ones in one file and the public ones in another. The private ones are kept secret on your server; the public ones are not secret and are distributed to your clients. Now, when a client needs to start a converstaion, it creates some random bytes that will be the encryption key for that session. Then sends that key to the server by encrypting with an RSA cipher instance, initted with the public key; the server inits its with the private key to decrypt. Then, the rest of the conversation uses a regular symmetric encryption system (e.g. AES) with that key.

Don't use DES: it's slow and insecure. If you've not reason to use anything else, use AES.

Note that there are details you need to think about to make this really secure. With block ciphers such as AES, you must basically make sure you "never encrypt the same thing twice" with the same key. One way to do this is to use the cipher in "counter mode" (there are other modes: google for details). For example:

  1. Cipher c = Cipher.getInstance("AES/CTR/PKCS5NOPADDING");

Call getIV() on the cipher to get the "initialisation vector"-- effectively, the initial value of the counter. Then send this to the server before the beginning of the encrypted data. The server inits its cipher with a corresponding IvParameterSpec.

You also need to think about "replay attacks": an attack where an eavesdropper records the entire encrypted conversation and simply plays it back to the server. So when you first "log in" to the server, it should generate some random "nonce" string of bytes, which at the beginning of the conversation your client will build into the data it encrypts (and the server then checks for and allows only once).
Reply With Quote Quick reply to this message  
Reply

This thread is more than three months old.
Perhaps start a new thread instead?
Message:


Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC