我正在尝试学习 Java Cipher Crypto,但对下面的代码有一些疑问:
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();
}
}
}
为什么
keyBitSize
设置为 256 时会出现 Invalid Key Exception (invalid key size)?密码是否限制为 128 位?此加密方法是否始终生成一致的加密字符串长度 11(设置为 时
keyBitSize = 128
)?此方法是否会截断任何长度更长的纯文本输入字符串?
在将加密值存储到 MySQL 数据库之前使用这种方法加密用户输入是否是一种可靠的安全形式?