我在使用JDK中的DES算法时,遇到异常IllegalBlockSizeException ,我的数据必须是8的倍数,我如何补位,把数据添加到8位,并且不会改变明文和密文。
下面是我的测试代码,经测试,数据长度为11,不是8的倍数,怎么没有抛出异常啊???import java.security.Key;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;public class Securite {
public static void main(String[] args){
try{
KeyGenerator kg = KeyGenerator.getInstance("DES");
Key key = (Key)kg.generateKey();
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.ENCRYPT_MODE,key);
byte[] data = "Hello World".getBytes();
System.out.println(data.length);
System.out.println(new String(data));
byte[] result = cipher.doFinal(data);
System.out.println(result);
System.out.println(new String(result));
cipher.init(Cipher.DECRYPT_MODE,key);
byte[] original = cipher.doFinal(result);
System.out.println(new String(original));
}catch(Exception e){
e.printStackTrace();
}
}
}
下面是我的测试代码,经测试,数据长度为11,不是8的倍数,怎么没有抛出异常啊???import java.security.Key;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;public class Securite {
public static void main(String[] args){
try{
KeyGenerator kg = KeyGenerator.getInstance("DES");
Key key = (Key)kg.generateKey();
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.ENCRYPT_MODE,key);
byte[] data = "Hello World".getBytes();
System.out.println(data.length);
System.out.println(new String(data));
byte[] result = cipher.doFinal(data);
System.out.println(result);
System.out.println(new String(result));
cipher.init(Cipher.DECRYPT_MODE,key);
byte[] original = cipher.doFinal(result);
System.out.println(new String(original));
}catch(Exception e){
e.printStackTrace();
}
}
}
或者开头补一个字节表示后面的有效字节数长度,然后再补反正不太可能直接用des
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;public class Securite {
public static void main(String[] args){
String str1;
byte[] data,result;
try{
str1="Hellow";
KeyGenerator kg = KeyGenerator.getInstance("DES");
Key key = (Key)kg.generateKey();
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.ENCRYPT_MODE,key);
data = str1.getBytes();
result = cipher.doFinal(data);
str1=new String(result);
System.out.println(str1); cipher.init(Cipher.DECRYPT_MODE,key);
data=str1.getBytes();
result = cipher.doFinal(data);
str1=new String(result);
System.out.println(str1);
}catch(Exception e){
e.printStackTrace();
}
}
}