Failed to encrypt/descrypt
mzander opened this issue · 2 comments
mzander commented
Hi,
first of all thank you for the great library.
When I try to read a previously (crypted) stored text file I get those exception.
W/System.err: java.lang.RuntimeException: Failed to encrypt/descrypt
W/System.err: at com.sromku.simple.storage.security.SecurityUtil.encrypt(SecurityUtil.java:79)
W/System.err: at com.sromku.simple.storage.AbstractDiskStorage.encrypt(AbstractDiskStorage.java:411)
W/System.err: at com.sromku.simple.storage.AbstractDiskStorage.readFile(AbstractDiskStorage.java:386)
W/System.err: at com.sromku.simple.storage.AbstractDiskStorage.readFile(AbstractDiskStorage.java:161)
W/System.err: at com.sromku.simple.storage.InternalStorage.readFile(InternalStorage.java:18)
W/System.err: at com.sromku.simple.storage.AbstractDiskStorage.readTextFile(AbstractDiskStorage.java:169)
W/System.err: at com.sromku.simple.storage.InternalStorage.readTextFile(InternalStorage.java:18)
which is caused by
W/System.err: Caused by: javax.crypto.BadPaddingException: error:06065064:digital envelope routines:EVP_DecryptFinal_ex:bad decrypt
The keys are exactly the same as they were used for writing the file.
Thanks,
Moritz
mzander commented
I found that this is only the case when I am restarting the App and using the same keys for the stored file.
I am new to encryption but maybe this occurs because you are using always another random generated salt?
I mean this:
SecureRandom random = new SecureRandom();
byte[] salt = new byte[16]; // keyLength / 8 = salt length
random.nextBytes(salt);
KeySpec keySpec = new PBEKeySpec(secretKey.toCharArray(), salt, iterationCount, keyLength);
sromku commented
It's a bug and very bad thing to generate new random salt on every app session :(
Fixed in latest version 🎉
This looks like this:
// set encryption
String IVX = "abcdefghijklmnop"; // 16 lenght - not secret
String SECRET_KEY = "secret1234567890"; // 16 lenght - secret
byte[] SALT = "0000111100001111".getBytes(); // 16 byte array
// build configuration
EncryptConfiguration configuration = new EncryptConfiguration.Builder()
.setEncryptContent(IVX, SECRET_KEY, SALT)
.build();
// configure the simple storage
storage.setEncryptConfiguration(configuration);