| | |
Encryption in Java
Please support our Java advertiser: Programming Forums - DaniWeb Sister Site
![]() |
•
•
Join Date: Mar 2009
Posts: 123
Reputation:
Solved Threads: 0
Hello everyone,
I am currently developing a chat application and I want to encrypt all send messages. I am using the example below:
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.
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)
import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import javax.crypto.NoSuchPaddingException; import javax.crypto.IllegalBlockSizeException; import javax.crypto.BadPaddingException; import java.security.Key; import java.security.Security; import java.security.NoSuchAlgorithmException; import java.security.InvalidKeyException; public class DESCryptoTest { public static void main(String[] args) { //Security.addProvider(new com.sun.crypto.provider.SunJCE()); try { KeyGenerator kg = KeyGenerator.getInstance("DES"); Key key = kg.generateKey(); Cipher cipher = Cipher.getInstance("DES"); byte[] data = "Hello World!".getBytes(); System.out.println("Original data : " + new String(data)); cipher.init(Cipher.ENCRYPT_MODE, key); byte[] result = cipher.doFinal(data); System.out.println("Encrypted data: " + new String(result)); cipher.init(Cipher.DECRYPT_MODE, key); byte[] original = cipher.doFinal(result); System.out.println("Decrypted data: " + new String(original)); System.out.println("Key : "+ key.toString()); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (NoSuchPaddingException e) { e.printStackTrace(); } catch (InvalidKeyException e) { e.printStackTrace(); } catch (IllegalStateException e) { e.printStackTrace(); } catch (IllegalBlockSizeException e) { e.printStackTrace(); } catch (BadPaddingException e) { e.printStackTrace(); } } }
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.
•
•
Join Date: Mar 2009
Posts: 123
Reputation:
Solved Threads: 0
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.
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.
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.
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.
•
•
Join Date: Apr 2008
Posts: 972
Reputation:
Solved Threads: 145
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)
Preferences prefs = Preferences.userRoot(); prefs.put(prefsItemName, prefsItemValue); ... prefs.get(prefsItemName, "");
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
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
Publilius Syrus
(~100 BC)
LJC - London Java Community, Graduate & Undergraduate Software Development Community, JAVAWUG (Java Web User Group), The London Android Group
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
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
•
•
Join Date: Apr 2008
Posts: 972
Reputation:
Solved Threads: 145
•
•
•
•
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.
For ultimate security both pairs of public/private keys could be generated from scratch for each session, although this is almost certainly overkill!
•
•
Join Date: Dec 2008
Posts: 53
Reputation:
Solved Threads: 6
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:
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:
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).
Java Syntax (Toggle Plain Text)
KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA"); kpg.initialize(2048); KeyPair kp = kpg.genKeyPair(); KeyFactory fact = KeyFactory.getInstance("RSA"); RSAPublicKeySpec pub = fact.getKeySpec(kp.getPublic(), RSAPublicKeySpec.class); 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)
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).
![]() |
Similar Threads
- encryption (Java)
- java is supposed to be secure? (Java)
- decrypting (Java)
- Simple problem with encryption (Java)
- Encryption -- Custom algorithm (Java)
- IE6SP2 update on ME - Java doesn't work (Windows 95 / 98 / Me)
Other Threads in the Java Forum
- Previous Thread: Storing objects in an array using inheritance and polymorphism
- Next Thread: another ActionListener question
| Thread Tools | Search this Thread |
account android api applet application array arrays automation bidirectional binary birt bluetooth chat class classes client code columns component data database designadrawingapplicationusingjavajslider draw eclipse editor error errors event exception expand fractal game givemetehcodez graphics gui guidancer homework html ide image inetaddress inheritance input integer intellij j2me java javaprojects jlabel jme jni jpanel jtextfield julia linux list loop map method methods midlethttpconnection mobile mobiledevelopmentcreatejar monitoring myaggfun netbeans newbie nullpointerexception open-source plazmic print problem program programming project property recursion ria scanner screen search server set size sms smsspam sort sourcelabs splash sql sqlite static string subclass support swing testautomation threads tree windows






