BadPaddingException异常

03-07-22 shiqiang705

我在用DESede解密时,当字符数超过3时出BadPaddingException异常,源程序如下:

/*对称加密*/

/*生成密钥*/

import java.io.*;

import javax.crypto.*;

public class GenerateKey {

public static void main(String[] args) {

try {

KeyGenerator kg=KeyGenerator.getInstance("DESede");

//kg.init(168);

SecretKey k=kg.generateKey();

FileOutputStream f=new FileOutputStream("key1.dat");

ObjectOutputStream b=new ObjectOutputStream(f);

b.writeObject(k);

f.close();

} catch (Exception ex) {

}

}

}

import java.io.*;

import javax.crypto.*;

import java.security.*;

/**加密类*/

public class Encrypt {

/**将明文转换为密文*/

public static String getEnStr(String enStr) {

try {

FileInputStream f=new FileInputStream(Constant.KEK_PATH+"key1.dat");

ObjectInputStream b=new ObjectInputStream(f);

SecretKey k=(SecretKey)b.readObject();

Cipher cp=Cipher.getInstance("DESede");

cp.init(Cipher.ENCRYPT_MODE,k);

byte[] ptext=enStr.getBytes();

byte[] ctext=cp.doFinal(ptext);

return new String(ctext);

} catch (Exception ex) {

System.out.println("生成加密文件出错!");

return null;

}

}

}

import java.io.*;

import javax.crypto.*;

import java.security.*;

import javax.crypto.spec.*;

import wxzfxt.system.Constant;

/**解密操作类*/

public class Decrypt {

/**将密文转化为明文*/

public static String getDeStr(String deStr) {

try {

FileInputStream f=new FileInputStream(Constant.KEK_PATH+"key1.dat");

ObjectInputStream b=new ObjectInputStream(f);

SecretKey k=(SecretKey)b.readObject();

Cipher cp=Cipher.getInstance("DESede");

cp.init(Cipher.DECRYPT_MODE,k);

byte[] ctext=deStr.getBytes();

try {

byte[] ptext=cp.doFinal(ctext);

String myDecrypt=new String(ptext);

return myDecrypt;

} catch (IllegalStateException ex1) {

System.out.println("IllegalStateException");

return null;

} catch (IllegalBlockSizeException ex2) {

System.out.println("IllegalBlockSizeException");

return null;

} catch (BadPaddingException ex3) {

System.out.println("BadPaddingException");

return null;

}

} catch (Exception ex) {

System.out.println("解密操作出错!");

return null;

}

}

}