You can encrypt the data to be sent and decrypt the data to be received via sockets, using the algorithm AES.
import java.util.Formatter;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
public class AES {
private byte[] chave;
private byte[] mensagem;
public AES(byte[] chave, byte[] mensagem) {
this.chave = chave;
this.mensagem = mensagem;
}
public AES() {
}
public static void main(String args[]) throws Exception {
byte[] mensagem = "oi".getBytes();
byte[] chave = "0123456789abcdef".getBytes();
System.out.println("Tamanho da chave: " + chave.length);
byte[] encriptado = Encripta(mensagem, chave);
System.out.println("String encriptada: " + new String(encriptado));
byte[] decriptado = Decripta(encriptado, chave);
System.out.println("String decriptada: " + new String(decriptado));
}
public static byte[] Encripta(byte[] msg, byte[] chave) throws Exception {
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(chave, "AES"));
byte[] encrypted = cipher.doFinal(msg);
return encrypted;
}
public static byte[] Decripta(byte[] msg, byte[] chave) throws Exception {
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(chave, "AES"));
byte[] decrypted = cipher.doFinal(msg);
return decrypted;
}
}
I believe that one way to solve your problem is for the server to request a login and for a security measure, the client informs only the hash of this login to the server, and never in plain text. Later the server uses a key associated with that login (it can be a piece of the password hash of that user, which is already saved on the server) to encrypt the data using the AES. In the client you repeat the algorithm, hash the password and use it as the AES key. If the password is equal to the server, both will use the same key and the communication will occur in a fluid and protected way.
I think it is unnecessary for you to inform the password to the server, since with a correct decryption of the data it is already understood that the client entered the correct password. But if this is necessary, I recommend that you never send the password in plain text. Send the password hash and make sure that you are doing this safely.
Edited
At the suggestion of mgibsonbr It is interesting that you use more time consuming hash algorithms, such as PBKDF2, Bcrypt or scrypt. I believe that if you use SHA-3, but with a greater amount of iterations (1000x, for example) it will also have a similar effect.
What language is used? Are you using any webserver How is Apache, Tomcat, IIS, etc, or your server a common program? I suggest simply using SSL/TLS, but to give an example I would need the language (virtually all of them have some library ready to assist with this, the most "annoying" is to properly configure the certificate).
– mgibsonbr