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

Nir*_*wan 4 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;


    }
Run Code Online (Sandbox Code Playgroud)
  • 输入字符串:John Doee
  • 加密输出:4aa2173cb653f89e109b23218ecaea7f

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

Mic*_*ael 8

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

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

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


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

  • 如果表中的明文值以“ AES:”开头怎么办?该方案不可靠。 (2认同)