views:

124

answers:

2

when you want to encrypt something dont you want the key to decrypt to be decided by you and not generator by some random number generator ?

i see this code in stackoverflow post. but i dont want the key to be generated randomly i want to the user to be asked to enter the key and on that bases the encryption should happen..

any suggestions how should i modify the code ?

SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
KeySpec spec = new PBEKeySpec(password, salt, 1024, 256);
SecretKey tmp = factory.generateSecret(spec);
SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES");
A: 

The whole idea of encryption is that noone except the needed parties can ever deduce the key since the key is the only secret.

If you choose keys yourself you're likely to follow some habitual pattern, so if you compomise one key you expose that pattern and the attacker can use that information to simplify finding other keys you use. Using a good random number generator eliminates this possibility and makes the encryption much more efficient.

sharptooth
Also through random generation the key typically is picked in the full "key space" whereby with user defined keys, these are typically limited to letters and numbers.
mjv
Well, you could compensate for that by asking a user for more letters and numbers and hashing the input to be of necessary width.
sharptooth
Yes, that's exactly what the OP's code, using PBKDF2, does.
erickson
A: 

The code you show doesn't generate a random key. The generated key is a function of the password, and will be exactly the same every time a given password is used.

In this case, the user should be asked to enter the password. That password is used as the seed for an algorithm that deterministically produces a string of bytes which can be used as a cryptographic key.

There is something that should be chosen randomly for each operation: the initialization vector used for ciphers in CBC mode. This produces different ciphertexts even when the same key is used to encrypt the same plaintext.

erickson