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

问题描述 投票:3回答:2

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

我想避免双重加密我的表数据。我想检查现有记录是否已加密。有没有办法检查这个?

java encryption aes
2个回答
7
投票

加密后,添加一些前缀,如AES:。解密时,检查是否存在前缀(并明显删除它)。

大量的密码实现做类似的事情,其中​​前几个字节识别算法。

与任何良好的加密方案一样,只有密钥必须是秘密的。该算法可以公开而不会影响安全性。


唯一的边缘情况是真正的明文以前缀开头。如果您认为这值得考虑,那么您可以通过选择不太可能的前缀(可能利用明文知识)来降低风险。为了进一步保证,您可以查看输入的长度,因为真密文的长度保证是块大小的倍数。


2
投票

我同意迈克尔的观点,最好在密文前加上一些标记。但是如果你不能这样做,还有一种概率方法:

您无法100%确定地识别原始加密数据。但根据您的明文,您可以确定它是否未加密。例如,MSB可以识别ASCII文本。由于密文应该与随机噪声无法区分,因此加密数据不太可能具有相同的模式。

如果10个连续字节的MSB设置为零,则它成为密文的几率仅为2-10,即小于0.1%。

但毕竟您将密文编码为十六进制字符串,因此您需要在分析期间将其反转。

如果您的明文恰好是压缩数据,那么可能性不大,因为熵几乎与加密甚至随机数据一样高。

© www.soinside.com 2019 - 2024. All rights reserved.