943,533 Members | Top Members by Rank

Ad:
  • Java Discussion Thread
  • Unsolved
  • Views: 2158
  • Java RSS
You are currently viewing page 1 of this multi-page discussion thread
Apr 6th, 2009
0

Encryption in Java

Expand Post »
Hello everyone,
I am currently developing a chat application and I want to encrypt all send messages. I am using the example below:

Java Syntax (Toggle Plain Text)
  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.
Similar Threads
Reputation Points: 6
Solved Threads: 0
Junior Poster
neutralfox is offline Offline
124 posts
since Mar 2009
Apr 6th, 2009
-7

Re: Encryption in Java

Quote ...
Can someone help me please!! Is there any other way to secure, encrypt message while sending over the network?
You could use SSL?
Moderator
Featured Poster
Reputation Points: 1764
Solved Threads: 574
Moderator
jbennet is offline Offline
16,485 posts
since Apr 2005
Apr 6th, 2009
0

Re: Encryption in Java

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.
Reputation Points: 6
Solved Threads: 0
Junior Poster
neutralfox is offline Offline
124 posts
since Mar 2009
Apr 6th, 2009
-7

Re: Encryption in Java

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.
Moderator
Featured Poster
Reputation Points: 1764
Solved Threads: 574
Moderator
jbennet is offline Offline
16,485 posts
since Apr 2005
Apr 7th, 2009
0

Re: Encryption in Java

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:
Java Syntax (Toggle Plain Text)
  1. Preferences prefs = Preferences.userRoot();
  2. prefs.put(prefsItemName, prefsItemValue);
  3. ...
  4. prefs.get(prefsItemName, "");
Featured Poster
Reputation Points: 1907
Solved Threads: 947
Posting Expert
JamesCherrill is offline Offline
5,754 posts
since Apr 2008
Apr 7th, 2009
0

Re: Encryption in Java

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
Moderator
Featured Poster
Reputation Points: 2786
Solved Threads: 871
Code tags enforcer
peter_budo is offline Offline
6,653 posts
since Dec 2004
Apr 7th, 2009
0

Re: Encryption in Java

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
Reputation Points: 10
Solved Threads: 3
Newbie Poster
hkansal is offline Offline
21 posts
since Mar 2009
Apr 7th, 2009
-7

Re: Encryption in Java

Quote ...
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.
Moderator
Featured Poster
Reputation Points: 1764
Solved Threads: 574
Moderator
jbennet is offline Offline
16,485 posts
since Apr 2005
Apr 7th, 2009
0

Re: Encryption in Java

Click to Expand / Collapse  Quote originally posted by jbennet ...
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!
Featured Poster
Reputation Points: 1907
Solved Threads: 947
Posting Expert
JamesCherrill is offline Offline
5,754 posts
since Apr 2008
Apr 7th, 2009
1

Re: Encryption in Java

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:

Java Syntax (Toggle Plain Text)
  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:

Java Syntax (Toggle Plain Text)
  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).
Reputation Points: 120
Solved Threads: 7
Junior Poster in Training
neilcoffey is offline Offline
53 posts
since Dec 2008

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in Java Forum Timeline: Storing objects in an array using inheritance and polymorphism
Next Thread in Java Forum Timeline: another ActionListener question





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC