[英]javax.crypto.BadPaddingException: error
I am trying to run a simple encryption/decryption program. 我正在尝试运行一个简单的加密/解密程序。 I am getting a padding exception. 我收到填充异常。 There must be something hidden that I am not aware. 必须隐藏一些我不知道的东西。 I basically encrypted a string write it to a file, read it back, and decrypted it. 我基本上加密了一个字符串,然后将其写入文件,读回并解密。 The original encrypted array was decrypted without a problem. 原始的加密阵列已解密,没有问题。 I compared the original encrypted array with the array read back from the file, they were identical from what I can see. 我将原始的加密数组与从文件中读取的数组进行了比较,从我所看到的来看,它们是相同的。 The buffer from the file does not work, so there must be something difference. 文件中的缓冲区不起作用,因此必须有所不同。 I don't know what to do. 我不知道该怎么办。
import java.security.*;
import java.security.spec.InvalidKeySpecException;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.io.*;
public class sample
{
private static String _algo = "AES";
private static byte[] _key = new byte[16];
public static byte[] encrypt (String val) throws Exception
{
Key key = new SecretKeySpec (_key, _algo);
Cipher c = Cipher.getInstance (_algo);
c.init (Cipher.ENCRYPT_MODE, key);
byte[] encode = c.doFinal (val.getBytes());
return encode;
}
public static String decrypt (byte[] val) throws Exception
{
Key key = new SecretKeySpec (_key, _algo);
Cipher c = Cipher.getInstance (_algo);
c.init (Cipher.DECRYPT_MODE, key);
byte[] decode = c.doFinal (val);
String decodeStr = new String (decode);
return decodeStr;
}
public static void main (String[] args) throws Exception
{
String str = "Good bye cruel world";
//
// get password from command line
//
_key = args[0].getBytes();
byte[] encodeArray = sample.encrypt (str);
//
// write encrypted array to file
//
FileOutputStream os = new FileOutputStream ("data");
os.write (encodeArray);
os.close();
//
// decode and print out string
//
String decodeStr = sample.decrypt (encodeArray);
System.out.println ("decodeStr = " + decodeStr);
//
// read back encrypted string
byte[] buffer = new byte[64];
FileInputStream is = new FileInputStream ("data");
is.read (buffer);
is.close();
decodeStr = sample.decrypt (buffer);
System.out.println ("decodeStr = " + decodeStr);
}
}
Output: 输出:
java sample 1234567890123456
decodeStr = Good bye cruel world
Exception in thread "main" javax.crypto.BadPaddingException: Given final block not properly padded
at com.sun.crypto.provider.SunJCE_f.b(DashoA13*..)
at com.sun.crypto.provider.SunJCE_f.b(DashoA13*..)
at com.sun.crypto.provider.AESCipher.engineDoFinal(DashoA13*..)
at javax.crypto.Cipher.doFinal(DashoA13*..)
at sample.decrypt(sample.java:32)
at sample.main(sample.java:70)
The problem is that the byte buffer with a size of 64, which you are reading the file into, is too big. 问题在于,您正在将文件读取到的大小为64的字节缓冲区太大。 Change it to 32. 将其更改为32。
Or use the length of the file like this: 或像这样使用文件的长度:
byte[] buffer = new byte[(int)new File("data").length()];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.