DES加密遇到的问题(Java)

错误:java.io.IOException: javax.crypto.BadPaddingException: Given final block not properly padded.

一开始以为是下面这段代码的问题,换成另一段代码。

SecureRandom ran = new SecureRandom();
DESKeySpec dKey = new DESKeySpec(password.getBytes());
SecretKeyFactory kF = SecretKeyFactory.getInstance("DES");
SecretKey skey = kF.generateSecret(dKey);
SecureRandom ran = SecureRandom.getInstance("SHA1PRNG");
ran.setSeed(password.getBytes());
KeyGenerator kgen = KeyGenerator.getInstance("DES");
kgen.init(56,ran);
SecretKey skey = kgen.generateKey();

结果发现问题没有解决。问题在下面这段代码:

Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.DECRYPT_MODE, skey, ran);
byte[] buffer = new byte[1024];
InputStream in = new FileInputStream(file);
OutputStream out = new FileOutputStream(destFile);
CipherInputStream cin = new CipherIntputStream(in,cipher);
int r = 0;
while ((r = in.read(buffer))!=-1) {
      cin.write(buffer, 0, r);
}

改正之后的代码:

Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.DECRYPT_MODE, skey, ran);
byte[] buffer = new byte[1024];
InputStream in = new FileInputStream(file);
OutputStream out = new FileOutputStream(destFile);
CipherOutputStream cot = new CipherOutputStream(out,cipher);
int r = 0;
while ((r = in.read(buffer))!=-1) {
      cot.write(buffer, 0, r);
}

最后发现是模式与输出不同,加密模式应该用CipherInputStream,解密模式用CipherOutputStream,输入流与输出流要考虑清楚。直接复制加密代码作为解密代码时,要考虑清楚要更改的地方。

你可能感兴趣的:(学海无涯,java,eclipse)