我正在尝试学习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 +"
" + 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时,为什么会得到无效的密钥异常(无效的密钥大小)? 密码限制为128位吗?

此加密方法是否始终生成一致的加密字符串长度11(设置为keyBitSize = 128时)?

此方法会截断任何长度更大的纯文本输入字符串吗?

在将加密的值存储在MySQL数据库中之前,使用这种方法对用户输入进行加密是否会是一种可靠的安全性形式?

您需要在jdk中单独安装JCE扩展,以获得无限制的密钥强度。 对于Oracle JDK 8,请点击链接。 您可以找到其他供应商的类似下载。

在我的jdk的jre / lib / security文件夹中,对吗?

是............

我只是意识到您提供的链接是针对Java SE的。 我正在运行Java EE ..它应该兼容吗?

Why does it get an Invalid Key Exception (invalid key size) when the keyBitSize is set to 256? Is cipher limited to 128 bits?

假设您正在使用OracleJDK,则需要Unlimited Strength JCE库(如注释所示)。 是的,进入jre / lib / security文件夹

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?

您正在打印字节数组引用,而不是任何加密值。 加密的结果是一个字节数组,您应该将该数组编码为可打印的字符(良好的做法是base64或hex)

您可以在我的博客中查看一些示例。

Would encrypting user input using this method before storing the encrypted values in a MySQL database a reliable form of security?

一点也不。 它与加密无关,这是您使用它的方式。

当涉及到用户身份验证凭据时,永远不要存储用户密码,即使加密也是如此。 那么原则上用户密码是可逆的。 有很多关于它的文章,例如。 G。 https://www.google.be/amp/s/nakedsecurity.sophos.com/2013/11/20/serious-security-how-to-store-your-users-passwords-safely/amp/

如今,存储身份验证凭据的最佳实践是使用盐腌的慢速哈希(pbkdf2,...)

关于最后一个问题(#4),我应该澄清一下,我正在存储用户数据,例如姓名,地址和信用卡。我想知道使用密码是否会提供一层安全保护,以防万一未经授权的用户进入数据库并以纯文本格式查看字段值。这样,他们将看到的只是存储为blob / varbinary而不是纯文本的随机字节数组。

我也已经在使用BCrypt将Web应用程序用户密码存储在我的数据库中。

@ jae-bin是的,可以加密敏感信息。您可能会看到链接的博客,因此对于加密本身,您应该使用正确的IV(初始化向量),编码(以便可以使用文本字段)和经过身份验证的加密

Nit:8u151以下的Oracle JDK或JRE需要策略jar。 8u15x仅需要在jre / lib / security / java.security中进行编辑,而8u161 up(包括9,10,11)已具有policy = unlimited。同样,用于打印阵列的规范或至少经典的版本也是stackoverflow.com/questions/409784/