Java AES 加密 解密 结果不一致



import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class AES1 {

    public static byte[] encryptAES(byte key[], byte data[]) throws Exception {
        SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");

        Cipher cipher = Cipher.getInstance("AES/CTR/NoPadding");

        cipher.init(Cipher.ENCRYPT_MODE, skeySpec, new IvParameterSpec(new byte[16]));

        return cipher.doFinal(data);
    }


    public static byte[] decryptAES(byte key[], byte msg[]) throws Exception {
        SecretKeySpec skeySpec = new SecretKeySpec(key, "AES");

        Cipher cipher = Cipher.getInstance("AES/CTR/NoPadding");

        cipher.init(Cipher.DECRYPT_MODE, skeySpec, new IvParameterSpec(new byte[16]));

        return cipher.doFinal(msg);
    }


    public static void main(String[] args) {
        String key = "1234567890123456";
        String text = "1234567890";
        String encrypt = "";
        String decrypt = "";


        try {
            encrypt = new String(encryptAES(key.getBytes("UTF-8"), text.getBytes("UTF-8")));
            System.out.println("encrypt : " + byte2hex(encrypt.getBytes("UTF-8")));

            decrypt = new String(decryptAES(key.getBytes("UTF-8"), encrypt.getBytes("UTF-8")));
            System.out.println("decrypt : " + decrypt);

            System.out.println("text.equals(decrypt): " + text.equals(decrypt));

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

    public static String byte2hex(byte[] b) {
        String a = "";
        for (int i = 0; i < b.length; i++) {
            String hex = Integer.toHexString(b[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            a = a + hex;
        }
        return a;
    }
}


代码如上,使用的是 AES 的 CTR 无填充加密算法,但是解密后所得串与原串不相等。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值