Be sure to write when you get the cipher object.
Cipher Cipher = cipher.getinstance ("des/ecb/nopadding");
Do not write
Cipher Cipher = cipher.getinstance ("DES");
Otherwise the decryption will be error:
Given final block not properly padded
The reason is cipher cipher = cipher.getinstance ("DES"), and cipher cipher = cipher.getinstance ("des/ecb/pkcs5padding"); When encrypted, you get a 16-length byte array.
When decrypting the error: Javax.crypto.BadPaddingException:Given final block not properly padded
Careful analysis, it is not difficult to find that the exception is thrown at the time of decryption, the encryption method is not a problem.
However, the only difference between the two methods is that the schema of the cipher object is different, which excludes the possibility of the program being written incorrectly. Then look at the abnormal revelation information, probably mean: the provided block of words does not fit the fill.
Originally in Des encryption, the last length of less than 64, it will be automatically filled to 64, then in our byte array to string conversion process, it can be filled with the invisible character changed, so the system throws an exception.
Problem found, how to solve it? It is also remembered that mail transmission usually keeps some information encoded, that is, Base64, which guarantees the integrity of the information. For ease of use, let's write a new way to encapsulate the original method:
Public StaticString Dataencrypt (String str,byte[] key) {String Encrypt=NULL; Try { byte[] ret = encode (Str.getbytes ("UTF-8"), key); Encrypt=NewString (Base64.encode (ret)); } Catch(Exception e) {System. out. Print (e); Encrypt=str; } returnencrypt; }
Public StaticString Datadecrypt (String str,byte[] key) {String Decrypt=NULL; Try { byte[] ret =Decode (Base64.decode (str), key); Decrypt=NewString (ret,"UTF-8"); } Catch(Exception e) {System. out. Print (e); Decrypt=str; } returnDecrypt; }
We changed the parameters of the method into strings, but why use UTF-8? Do you want to not specify its byte format? As you know, UTF-8 is an international character encoding, it is not a problem to transmit any strings, it can also be a perfect solution to the Chinese problem of the Java EE! So we'd better use UTF-8 coding to reduce unnecessary hassles.
Java Given final block not properly padded