How to encrypt and decrypt data to be transmitted via sockets?

1

I have a program that logs in with my server, however the connection is without any protection. I looked for some ways to protect but it seems that some of them have a pass code, in the client, but I need to make the connection encrypted, and prevent the person who has the client from being able to perceive how to intercept the connection of other users, like Should I resolve this?

    
asked by anonymous 09.05.2015 / 20:08

1 answer

2

You can encrypt the data to be sent sent and decrypt the data to be received via sockets, with 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;
}
}

Ibelievethatonewaytosolveyourproblemisfortheservertorequestaloginandforasecuritymeasure,theclientonlyinformsthehashofthislogintotheserver,andneverinplaintext.Theserverthenusesakeyassociatedwiththatlogin(itcanbeahashofthatuser'spassword,whichisalreadysavedontheserver)toencryptthedatausingAES.Intheclientyourepeatthealgorithm,makethepasswordhashanduseitastheAESkey.Ifthepasswordisthesameastheserver's,bothwillusethesamekeyandthecommunicationwilloccurinafluidandprotectedway.

Ithinkitisunnecessaryforyoutoenterthepasswordfortheserver,sincewithacorrectdecryptionofthedataitisalreadyassumedthattheclienthasenteredthecorrectpassword.Butifthisisnecessary,Irecommendthatyouneversendthepasswordinplaintext.Submitthepasswordhashand make sure you're doing this in a safe way.

Edited

At the suggestion of mgibsonbr , it is interesting that you use longer hashing algorithms such as PBKDF2, BCrypt, or scrypt. I believe that if you use it using SHA-3, but with a larger number of iterations (1000x, for example) will also have a similar effect.

    
09.05.2015 / 20:25