Java如何检查值是否已经AES加密;

标签 java encryption aes

我创建了一个工具来使用 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/

相关文章:

ios - iOS 上使用 iso10126 填充的 AES256 解密

java - 解密java中在php中使用AES加密的字符串

java - hamcrest hasItem 和 hasProperty,断言是否存在具有属性值的对象

java - 如何在JAVA Swing中的表中添加CheckBox对象

java - 堆排序与插入排序 JMH 基准测试 : why my insertion impl. 花费的时间更少?

ruby - Ruby OpenSSL::Cipher.reset 清除 key 和 iv 也有剂量吗?

java - 加密和序列化时出现 NullPointerException 异常

java - 为什么 android HttpURLConnection 缓存输入流结果?

android - 从 Whatsapp 获取所有消息

java - 带密码的 Zip 字节数组