0

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?

schnaidar
  • 190
  • 4
  • 11
  • that would be the best way http://stackoverflow.com/questions/3624280/how-to-use-sharedpreferences-in-android-to-store-fetch-and-edit-values – SpyZip Jul 03 '14 at 13:23

1 Answers1

0

to permanently save those little things I would recommend to use the Shared Preferences. But if you want to you could use the Internal Storage. The main different is that the Shared Preferences only save primitive datatypes (such as int, byte, String) and in the Internal Storage you can wirte whole files (like savegames or temp files) With both types the user can't access the data.

To easily access the saved information you could write a class that handels that for you, so you don't have to instantiate the whole Classes from the ADK.

Greetings

oruckdeschel
  • 88
  • 1
  • 8
  • In the android-app i will probably work with SharePreferences, but my main question was about the server-side. Is it performant to write the Key at the start of the server programm as a file to the disk and then read it from this file at each en-/decrypting process? or is it better to store it in the memory?(if yes, how can i accomplish this the best?) – schnaidar Jul 03 '14 at 13:32
  • It would absolutely be better to save thos little data in the memory, because it would cost to much resources to read the key every time. To accomplish this I would generate an Object, which holdes the data in a Map or List or Set and then generate some getter and setter. This Object should be singleton. – oruckdeschel Jul 03 '14 at 13:49
  • thats what i think too, but how should is save them in the memory, so that i have access to them from all over my application? – schnaidar Jul 03 '14 at 13:50
  • generate an object in singleton and store the data there. maybe you could use http://en.wikipedia.org/wiki/Dependency_injection and inject this Object to every class you want to use it. – oruckdeschel Jul 03 '14 at 13:53