I'm trying to learn Java Cipher Crypto and just have a few questions about my code below:
public class Main2 {
public static void main(String[] args) {
Cipher cipher;
KeyGenerator keyGenerator;
SecureRandom secureRandom;
int keyBitSize = 128;
SecretKey secretKey;
byte[] plainText, plainText2;
byte[] cipherText, cipherText2;
try
{
cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
keyGenerator = KeyGenerator.getInstance("AES");
secureRandom = new SecureRandom();
keyGenerator.init(keyBitSize, secureRandom);
secretKey = keyGenerator.generateKey();
try
{
//pass secretKey to cipher.init()
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
try
{
plainText = "helloWorld".getBytes("UTF-8");
plainText2 = "helloWorld".getBytes("UTF-8");
cipherText = cipher.doFinal(plainText);
cipherText2 = cipher.doFinal(plainText2);
System.out.println(cipherText + "\n" + cipherText2);
}
catch (IllegalBlockSizeException e)
{
e.printStackTrace();
}
catch (BadPaddingException e)
{
e.printStackTrace();
}
catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
}
catch (InvalidKeyException e)
{
e.printStackTrace();
}
}
catch (NoSuchAlgorithmException e)
{
e.printStackTrace();
}
catch (NoSuchPaddingException e)
{
e.printStackTrace();
}
}
}
Why does it get an Invalid Key Exception (invalid key size) when the
keyBitSize
is set to 256? Is cipher limited to 128 bits?Does this encryption method always generate a consistent encrypted string length of 11 (when set to
keyBitSize = 128
)?Does this method truncate any plaintext input string of greater length?
Would encrypting user input using this method before storing the encrypted values in a MySQL database a reliable form of security?