且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用AES / ECB / NoPadding进行加密/解密

更新时间:2023-08-19 17:44:28

我在代码中看到另一个错误:

I saw another mistake in your code :

即使你的encyption方法得到工作,你的解密方法是不会奏效的。
确实你正在使用Base64进行加密,再加上AES。而且您使用Base64,然后AES解密整个事情。

Even if your encyption method get working, you're decryption method is not going to work. Indeed you are encrypting using Base64 followed bye AES. And you decrypt the whole thing using Base64 followed by AES.

我几乎肯定这两种类型的加密不是可交换的。
(您必须解密AES然后Base64)。

I am almost sure that this two type of encryption are not exchangeables. (you must decrypt AES then Base64).

考虑到这个答案: javax.crypto.IllegalBlockSizeException:使用填充密码进行解密时,输入长度必须为16的倍数
,不带使用填充(NoPadding arg),您必须使用长度为16的输入字符串。

Considering this answer : javax.crypto.IllegalBlockSizeException : Input length must be multiple of 16 when decrypting with padded cipher , without the use of padding (NoPadding arg), you have to use an input String with a length multiple of 16.

如果我用我的评论纠正你的代码,如果我们让密码管理填充,我们得到以下代码,这样做很好:

If we correct your code with my remark and if we let the cipher manage the padding, we get the following code, which works well :

private static String decrypt_data(String encData)
        throws NoSuchAlgorithmException, NoSuchPaddingException,
        InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
    String key = "bad8deadcafef00d";
    SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes(), "AES");
    Cipher cipher = Cipher.getInstance("AES");

    cipher.init(Cipher.DECRYPT_MODE, skeySpec);

    System.out.println("Base64 decoded: "
            + Base64.decode(encData.getBytes()).length);
    byte[] original = cipher
            .doFinal(Base64.decode(encData.getBytes()));
    return new String(original).trim();
}

private static String encrypt_data(String data)
        throws Exception {
    String key = "bad8deadcafef00d";
    SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes(), "AES");
    Cipher cipher = Cipher.getInstance("AES");

    cipher.init(Cipher.ENCRYPT_MODE, skeySpec);

    System.out.println("Base64 encoded: "
            + Base64.encode(data.getBytes()).length);

    byte[] original = Base64.encode(cipher.doFinal(data.getBytes()));
    return new String(original);
}