【发布时间】:2018-06-13 10:53:53
【问题描述】:
我创建了一个工具来使用 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 加密字符串的字符串。这可能不太可能,但有可能。如果您无法明确定义输入应该是什么样子,我真的没有办法。
-
我认为解决您的问题的更好方法是问自己为什么甚至存在双重加密的机会。如果您有一个充满加密值的表,为什么要对某些内容进行双重加密。如果有可能发生这种情况,请解决它,因为我很确定这更容易解决。
-
呃,从外观上看,您使用的 IV 包含所有加密的全零。除非您为每次加密创建一个新密钥,否则您应该每次都生成一个新的 random IV。
-
旁白:这个 "new String(cipherBytes, "UTF8")" 是有问题的。加密结果只是一个字节数组,不能假定该字节数组也总是代表字符串的有效 UTF8 编码。
-
问题已经错了。
String不是二进制数据的容器。你不应该有这个问题。您只需设计您的应用程序协议,使其不会出现。
标签: java encryption aes