I'm writing an Server/Client application with encrypted communication in Java (Client is on Android).
What is the best way to save the SecretKeySpec
, so I don't have to generate it each time I want to encode/decode a message?
I'm using this method, taken from this site (german):
String keyStr = "secret";
byte[] key = (keyStr).getBytes("UTF-8");
MessageDigest sha = MessageDigest.getInstance("MD5");
key = sha.digest(key);
key = Arrays.copyOf(key, 16);
SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
String text = "Some text"
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
byte[] encrypted = cipher.doFinal(text.getBytes());
Should I store it in a static variable? Or should I try a completely different approach?
EDIT: To clarify my question, my main problem is with the server program, how should I do it in the server program?