Questions on AES encryption in Java using crypto library

644 Views Asked by At

I was currently looking for a sample AES encryption and decryption using Java and I have stumbled upon something like this as a solution:

LINK

Other solutions offered the same approach. I managed to got it to work but I just have some questions on its implementation.

Questions:

  1. Why does the PBEKeySpec class need a password? what is it for? there is already a key, why does it need to have an additional token or password?

  2. I understand that the key and salt is part of the encrypted value of the original un-encrypted string. Why is that so? why not allow to store the generate key and salt somewhere else?

Thanks and I appreciate any form of help. Just want to understand why it was made that way.

1

There are 1 best solutions below

2
Juraj Martinka On

For easy-to-use and rock-solid java encryption library I recommend to use http://www.jasypt.org/

To your questions:

  1. password is often used to derive the encryption key; this is needed because many algorithms require keys to meet certain properties such as length and randomness which isn't satisfied by many of the passwords normally used by people. See also https://docs.oracle.com/javase/7/docs/api/javax/crypto/spec/PBEKeySpec.html

  2. A salt and an initialization vector are stored alongside the encrypted value (that is they are NOT encrypted) because it's convenient - you can easily retrieve them and use them to decrypt the original string. This is still safe because you typically only need these values to be unique not to be kept secret; e.g. salt helps you prevent rainbow table attacks by having a unique salt for each value. A useful resource explaining some terminology: https://crypto.stackexchange.com/questions/3965/what-is-the-main-difference-between-a-key-an-iv-and-a-nonce