我创建了一个工具来使用 AES 加密来加密我的表数据。
加密方式
public String encrypt(String plainText) throws Exception {
byte[] cipherBytes = null;
log.info("Started encryption...");
System.out.println("value before encryption :" + plainText);
log.info("value before encryption :" + plainText);
if (plainText != null && !plainText.isEmpty()) {
if (cipher != null && key != null) {
byte[] ivByte = new byte[cipher.getBlockSize()];
IvParameterSpec ivParamsSpec = new IvParameterSpec(ivByte);
cipher.init(Cipher.ENCRYPT_MODE, key, ivParamsSpec);
cipherBytes = cipher.doFinal(plainText.getBytes());
log.info("Completed encryption.");
log.info("Encrypted data : " + new String(cipherBytes, "UTF8"));
System.out.println("value after encryption" + Hex.encodeHexString(cipherBytes));
log.info("value after encryption" + Hex.encodeHexString(cipherBytes));
return Hex.encodeHexString(cipherBytes);
} else {
log.info("Encryption failed, cipher, key is null.");
throw new RuntimeException(
"Encryption failed, cipher, key is null.");
}
}
return plainText;
}
- 输入字符串:John Doee
- 加密输出:4aa2173cb653f89e109b23218ecaea7f
我想避免对我的表数据进行双重加密。我想检查现有记录是否已加密。有什么办法可以检查吗?
最佳答案
加密后,在前面加上一些前缀,例如AES:
。解密时,检查前缀是否存在(显然是将其删除)。
许多密码实现都做类似的事情,其中前几个字节标识算法。
与任何好的加密方案一样,只有 key 必须保密。该算法可以在不影响安全性的情况下公开。
唯一的边缘情况是真正的明文是否以前缀开头。如果您认为这值得考虑,那么您可以通过选择不太可能的前缀来降低风险(也许利用对明文的了解)。为了进一步保证,您可以查看输入的长度,因为真实密文的长度保证是 block 大小的倍数。
关于Java如何检查值是否已经AES加密;,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50835401/