What I am trying to do is encrypt a string into a byte[] with javax.crypto, send it through a DatagramSocket, then on the receiving side, decrypt it.
public static final String UNICODE = "UTF-8";
private SecretKey key;
private Cipher cipher;
public StringHandler() {
try {
key = generateKey("AES");
cipher = Cipher.getInstance("AES");
} catch (Exception e) {
e.printStackTrace();
}
}
private SecretKey generateKey(String type) throws Exception {
KeyGenerator gen = KeyGenerator.getInstance(type);
SecretKey key = gen.generateKey();
return key;
}
public byte[] encrypt(String msg) {
try {
byte[] data = msg.getBytes(UNICODE);
cipher.init(Cipher.ENCRYPT_MODE, key);
return cipher.doFinal(data);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public String decrypt(byte[] data) {
try {
cipher.init(Cipher.DECRYPT_MODE, key);
return new String(cipher.doFinal(data), UNICODE);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
I read on a website how to encrypt and decrypt data, and I wrote this class. From what I can tell, the security key has to be the same on both sides for it to decrypt properly. Is there any way to convert it to a string or something, then get it from a string on the server side? Currently I have no idea how decrypt it on a different program.