【发布时间】:2016-03-26 16:45:21
【问题描述】:
我在尝试解密时收到以下错误:
javax.crypto.IllegalBlockSizeException:使用填充密码解密时,输入长度必须是 16 的倍数
这是我实现的加密类:
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
public class StringEncrypter {
public static String encrypt(String key, String string, String algorithm) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, UnsupportedEncodingException {
Key aesKey = new SecretKeySpec(key.getBytes("UTF-8"), algorithm);
Cipher cipher = Cipher.getInstance(algorithm);
cipher.init(Cipher.ENCRYPT_MODE, aesKey);
byte[] encrypted = cipher.doFinal(string.getBytes());
return encrypted.toString();
}
public static String decrypt(String key, String encryptedString, String algorithm) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException, UnsupportedEncodingException {
Key aesKey = new SecretKeySpec(key.getBytes("UTF-8"), algorithm);
Cipher cipher = Cipher.getInstance(algorithm);
cipher.init(Cipher.DECRYPT_MODE, aesKey);
String decrypted = new String(cipher.doFinal(encryptedString.getBytes()));
return decrypted;
}
}
这就是我加密字符串的方式:
StringEncrypter.encrypt("0306868080306868", "ddd", "AES"); // [B@e19957c
当我尝试像这样解密上面的加密字符串时:
String decrypted = StringEncrypter.decrypt("0306868080306868", "[B@e19957c", "AES");
我收到了illegalBlockSizeException。
我在上面做错了什么?如何正确解密加密字符串?
【问题讨论】:
-
请注意,您似乎正在使用 ECB 加密,这是不安全的。您的代码中至少缺少一个(随机)IV。
-
@ArtjomB。它解释了如何生成输出,但用
new String(byte[])替换它会例如不能解决问题。 -
@MaartenBodewes 你是对的,但是将其编码为十六进制会
-
是的,首选:只是二进制,用于调试和显示键/IV 的:十六进制,以及更大尺寸数组的二进制编码:base64。压缩率成为真正问题时的专业基础。 Java 还没有十六进制,因此 base 64 成为首选格式。
标签: java encryption cryptography