How do i store an encryption key in a file?
Greetings fellow java programmers. I have constructed a chat application and my last requirement seems to be a simple encryption. So i have created a DESede encryption/decryption class. Thing is , every time i call the class it creates a new key. i know where the problem is in that. However i need to have this key in my server too as it is necesarry. Therefore i just want to create a DESede key and save it in a file(any type of file as long as it works will do). After that i will only call a class that loads the key from the file and does the encryption/decryption. I am fully aware that this type of security has flaws. But for now this is my objective. Any help appreciated. Thank you in advance!
Re: How do i store an encryption key in a file?
You can create a key from a particular String and can store the string in a file. Then you can read the content of the file to create the same key any time you want.
This is a example for AES:
Code:
static public String encrypt(String message, String key) throws Exception {
byte[] raw = Base64Decoder.decodeToBytes(key);
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
// Instantiate the cipher
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
System.out.println("msg is" + message + "\n raw is" + raw);
byte[] encrypted = cipher.doFinal(message.getBytes());
String cryptedValue = new String(encrypted);
System.out.println("encrypted string: " + cryptedValue);
return cryptedValue;
}
Re: How do i store an encryption key in a file?
This seems quite usefull! I can use any word as the string who initialises the key? Or is it something that has to be writen in a particular way? also, can this secretkeyspec work in place of the ordinary <<key>> i have? (these questions may seem a bit basic and silly, though i have never got busy with encryption before and its sort of a new world for me). Thank you for your help.
Re: How do i store an encryption key in a file?
Do you think :
byte[] init = base64.decodeBuffer(dec);
will do the same job? because a method such as the one you wrote does not exist within the base64 given methods.