A Javax.crypto.BadPaddingException:Given final block not properly padded1.1 error reason: There may be two reasons, any one cause will cause an error.
When 1 des is encrypted, the last one is less than 64, and it is automatically filled to 64. If after reading the encrypted file does not read the completion, such as InputStream's Read () method is very easy to read the case of incomplete, this time will be an error.
2 Key file error, encrypted key and decrypted key match, people generally do not make such a mistake, but if there is such a mistake, it is not easy to detect.
1.2 Workaround
If the key is out of the question, replace it with the correct key.
If there is a problem with the encrypted file, check the number of bytes in the encrypted file and the number of bytes successfully read. Full reads can be guaranteed in the following ways.
/ * Read the key file * /InputStream Keyinputstream = Sumaclassloader.class. getResourceAsStream ("Secret.key");if(Keyinputstream! =NULL){Try{System.out.println ("The Keyinputstream is"+ Keyinputstream);intCount =0; while(Count = =0) {The //available () method does not cause problems when reading local files, but for network files, there is an issue with latency, and sometimes it is 0 bytes to receive directly. Count = Keyinputstream.available (); } System.out.println ("The Count of Keyinputstream is"+ count);byteKeydata[] =New byte[Count];intReadcount =0; while(Readcount < count) {The //read () method does not guarantee a complete read count byte, it only guarantees a maximum of read count bytes and a minimum of one read. Readcount + = Keyinputstream.read (KeyData, Readcount, Count-readcount); } keyinputstream.close (); }}
In addition to the method of fully reading the data, you can try the following method.
If you are using the following method to get the cipher object
Cipher cipher = Cipher.getInstance("DES")
Then it is equivalent to
ipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding")
This means that when less than 64 bits are filled, it can be changed to the following ways:
Cipher cipher = Cipher.getInstance("DES/ECB/NoPadding");
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
JCA and JCE FAQ Rollup (continuous update)