AES 确定性加密

AES deterministic encryption

我想实施确定性加密,我想弄清楚为什么解密在下面的代码中不起作用。解密后的文本与原始文本不同??

    public static String encryptID(String id) {

    String encryptedID = "";

    try {
        SecretKeySpec secretKey = new SecretKeySpec(Constants.ID_KEY.getBytes("UTF-8"), "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, secretKey, new IvParameterSpec(new byte[cipher.getBlockSize()]));

        encryptedID = new BASE64Encoder().encodeBuffer(cipher.doFinal(id.getBytes("UTF-8")));
    } catch (Exception e) {
        log.error("Encryption error. Unable to encrypt ID.", e);
        encryptedID = "ERROR";
    }

    return encryptedID;
}

public static String decryptID(String encryptedID) {

    String decryptedID = "";

    try {
        SecretKeySpec secretKey = new SecretKeySpec(Constants.ID_KEY.getBytes("UTF-8"), "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, secretKey, new IvParameterSpec(new byte[cipher.getBlockSize()]));

        byte[] decodedValue = cipher.doFinal(new BASE64Decoder().decodeBuffer(encryptedID));
        decryptedID = new String(decodedValue);

    } catch (Exception e) {
        e.printStackTrace();
    }
    return decryptedID;

}

测试代码:

    @Test
    public void testEncryption() {

    String ecryptedID = DataUtil.encryptID("123456789");
    System.out.println(ecryptedID);
    System.out.println(DataUtil.decryptID(ecryptedID)); 

}

输出:
KB8P+heBaNSaibJoJSImLQ==
—#@†zXÝ£^þhµORCôìÊ ^f/…ºÁ´®

您正在再次加密字符串而不是解密它

public static String decryptID(String encryptedID) {
...
                   |||||||
                   vvvvvvv
cipher.init(Cipher.ENCRYPT_MODE, secretKey, new IvParameterSpec(new byte[cipher.getBlockSize()]));