Reputation: 664
I try to save a Key in a file, and it save something, but when I try to load it to desencrypt the text, I have this exception:
"Invalid Key:Invalid AES key length: 59 bytes".
My code is the next:
SecretKey key;
key = KeyGenerator.getInstance("AES").generateKey();
byte[] encoded = key.getEncoded();
String newKey = new String(encoded, "UTF-8");
out.write(newKey);
Then I wrote the encrypted text. And then I try to load the key and desencrypt the saved text with that key, but i have the error "Invalid Key:Invalid AES key length: 59 bytes". The code is the next:
byte[] encoded = String.valueOf(fileIn.nextLine()).getBytes();//Key data
key = new SecretKeySpec(encoded, "AES");
dcipher = Cipher.getInstance("AES");
dcipher.init(Cipher.DECRYPT_MODE, key);
I need to save the key because is the only way to desencrypt the text days after, I think. I save an encrypted text and then I need to load that text desencrypted, some days after, for example.
Can anyone help me? Thanks!
Upvotes: 0
Views: 58
Reputation: 269847
A cryptographic key is not text. It's a string of bytes that can take any value and it's extremely unlikely that they will form a valid UTF-8 encoding.
Do not create a String
from your key. Just save the bytes to a file. The conversion corrupts the key by replacing byte sequences that are invalid under UTF-8 with the encoding for �, the default replacement character.
If you have to save your key in a text format, encode it with base-64 or some other encoding for not-textual data.
Here's an example, following the pattern of the code in the question:
SecretKey key = KeyGenerator.getInstance("AES").generateKey();
String encoded = Base64.getEncoder().encodeToString(key.getEncoded());
out.write(encoded);
byte[] raw = Base64.getDecoder().decode(fileIn.nextLine());
key = new SecretKeySpec(raw, "AES");
Cipher dcipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
dcipher.init(Cipher.DECRYPT_MODE, key);
Note that in decrypting, a complete transformation (including mode and padding) is specified. You might choose a different mode, but you should be explicit in what you choose, both in encryption and decryption. Otherwise, if you switch providers, different defaults might be chosen, and you won't be able to decrypt your data.
Upvotes: 1
Reputation: 664
I can solve it with that:
byte[] data = Files.readAllBytes(Paths.get(fileName.replaceAll("myPath")));
key = new SecretKeySpec(data, "AES");
Upvotes: 0