AES确定性加密

没有:

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

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

本杰明·厄克特(Benjamin Urquhart):

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

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章