我在使用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();
}

}
}

解决方案 »

  1.   

    好像是在特殊的位置补位,我在学校学过DES算法,很麻烦的,当时老师让做一个加密解密算法,我做的就是这个,但我没做成功,呵呵。你查阅一下资料吧,有校验位,校验位没有作用的,应该只能在校验位进行补位,其他位置补位的话,会改变原文。如果你要是给很长的明文加密的话,太费事了,别用我给说的补位方法;如果你是想了解一下DES算法,那你可以补位试一试。
      

  2.   

    des算法,没有接触过,帮你顶
      

  3.   

    其实变通的方法很多,比如截掉多余的字节另外处理,或者转成base64,或者数字转成字符串连接
    或者开头补一个字节表示后面的有效字节数长度,然后再补反正不太可能直接用des
      

  4.   

    不会,不知道怎么补,能给我个例子么?下面这个代码好奇怪,同样的代码,每次运行的结果不一样,一会出错,一会正常怎么回事啊?import java.security.Key;
    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();
    }
    }
    }