AES确定性加密

时间:2019-03-20 15:01:06

标签: java encryption aes java-security

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

    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 /…ºÁ´®

1 个答案:

答案 0 :(得分:2)

您要重新加密字符串,而不是解密

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