Reputation: 123
I want to decrypt a string, which is working with the right password. I tried to check the password with if(decrypt(Password, encryptedKey).contains(Key)){
But if the PW is wrong I get the following exception:
javax.crypto.BadPaddingException: pad block corrupted
So is there another way to check the password?
public static String decrypt(String seed, String encrypted) throws Exception {
byte[] rawKey = getRawKey(seed.getBytes());
byte[] enc = toByte(encrypted);
SecretKeySpec Spec = new SecretKeySpec(rawKey, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, Spec);
byte[] result = cipher.doFinal(enc);
return new String(result);
}
Upvotes: 2
Views: 1720
Reputation: 92752
Well, if it won't decrypt (and throws an exception) using an incorrect password, but will decrypt using the correct password, what's the problem? There isn't (or at least shouldn't be) an easier way to check the password than actually decrypting: an existence of a shortcut provides a weak spot which the attacker can target ("why try each of the possible passwords when there's a password hint under the doormat?").
If it decrypts without exception, the password is correct; if you get that exception, the password is incorrect.
This may not be optimal stylistically (as in "only using exceptions for exceptional states"), but won't lower your system's security, like storing the password alongside the data would (hashing the password before storage helps a bit, but it's easy to get wrong, and it still increases the system's complexity while reducing its security - see e.g. this for a taste of the complexities involved).
Upvotes: 2
Reputation: 2047
That would mean that your password would have to be stored somewhere in order for your program to compare it with the input password. You will have to hash that saved password is you don't want to create a backdoor for hackers. (the input password will then be hashed as well and compared to the stored password)
Upvotes: 2