当我试图解密时,我得到了以下错误:
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了。
我在上面做错什么了?如何正确解密加密字符串?
发布于 2015-12-20 14:18:04
您需要为您的密钥和密文执行基64编码解码。在Java 8中有一个新的Base64类,您不能只将任何字节存储在字符串中,并不是所有的字节都代表可打印甚至有效的字符,密码的输出与随机没有区别。
此外,字节数组" class“(用[B表示)没有实现toString方法,这意味着您只需要从Object.toString中获取打印,即类名[B和对象实例的人类可读的标识符,而不是实际的密文。
发布于 2015-12-20 16:23:12
不能将字节(二进制)用作字符串。它不是等价物
你应该改信它。几种礼貌。Base64或Hexa,例如,您使用base64,它给出如下内容:
import javax.xml.bind.DatatypeConverter ;
byte[] bt= ... // what you get
// Conversion B64
String encodedb64=DatatypeConverter.printBase64Binary(bt);
// CONVERSION base 64 => byte
// base 64 => byte
byte [] byteArrayreverse=DatatypeConverter.parseBase64Binary(encodedb64);https://stackoverflow.com/questions/34381630
复制相似问题