I improved my AES encryption code, I now generate a key from a password of any length. But now I dont know if I'm generating a 128, 192 or 256 bit AES key.
Here is my code:
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.Cipher;
public class AESCipher {
private Cipher cipher;
private SecretKey secretKey;
private SecretKeyFactory keyFactory;
private PBEKeySpec pbeKey;
private PBEParameterSpec paramSpec;
private byte[] salt = {111, 123, 56, 123, 99, 108, 45, 65};
private String password;
private final int iterationCount = 21;
/**
* Generates the key from the password.
*/
private void generateKey() throws Exception {
this.paramSpec = new PBEParameterSpec(this.salt, this.iterationCount);
this.pbeKey = new PBEKeySpec(this.password.toCharArray());
this.keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
this.secretKey = this.keyFactory.generateSecret(this.pbeKey);
this.cipher = Cipher.getInstance("PBEWithMD5AndDES");
}
/**
* Encrypts data.
* @param plainText
* Data to encrypt.
* @return
* Encrypted data.
* @throws Exception
* If something went wrong.
*/
public byte[] encrypt(String plainText) throws Exception {
byte[] encrypted = new byte[plainText.getBytes().length];
cipher.init(Cipher.ENCRYPT_MODE, this.secretKey, this.paramSpec);
encrypted = cipher.doFinal(plainText.getBytes());
return encrypted;
}
/**
* Decrypts data.
* @param cipherText
* Data to decrypt.
* @return
* Decrypted data.
* @throws Exception
* If something went wrong.
*/
public String decrypt(byte[] cipherText) throws Exception {
byte[] decryptedText = new byte[cipherText.length];
String decrypted;
cipher.init(Cipher.DECRYPT_MODE, this.secretKey, this.paramSpec);
decryptedText = cipher.doFinal(cipherText);
decrypted = new String(decryptedText);
return decrypted;
}
/**
* Class initializer.
* @param password
* Password that will be used for encryption.
*/
public AESCipher(String password) throws EncryptionException {
this.password = password;
try {
//generateSalt();
generateKey();
} catch(Exception error) {
throw new EncryptionException(error.getMessage());
}
}
}
How can I be sure this code will generate an AES 192 bit key?