Hello everyone,
I am currently developing a chat application and I want to encrypt all send messages. I am using the example below:
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.