【发布时间】:2013-12-02 08:03:48
【问题描述】:
我得到了这段代码:
static ReadableByteChannel readChannel = null;
static WritableByteChannel writeChannel = null;
static SecretKey key = makeKeyFromPassword("chuj".getBytes());
public static SecretKey makeKeyFromPassword(byte[] password) {
try {
key = KeyGenerator.getInstance("DES").generateKey();
byte[] encoded = key.getEncoded();
return new SecretKeySpec(encoded, "DES");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public static void run(int mode) throws Exception {
ByteBuffer readBuffer = ByteBuffer.allocate(1024);
ByteBuffer writeBuffer = ByteBuffer.allocate(1024);
//initializing cipher...
Cipher cipher = javax.crypto.Cipher.getInstance("DES");
cipher.init(mode, key);
int read = -1;
while((read = readChannel.read(readBuffer)) != -1){
readBuffer.flip();
cipher.doFinal(readBuffer, writeBuffer);
writeChannel.write(writeBuffer);
readBuffer.clear();
writeBuffer.clear();
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub\
FileOutputStream fos = null;
String inFileString = "C:\\test.txt"; // Valid file pathname
String fileString = "C:\\des.txt"; // Valid file pathname
int mode = Cipher.ENCRYPT_MODE;
FileSystem fs = FileSystems.getDefault();
Path fp = fs.getPath(inFileString);
try {
readChannel = FileChannel.open(fp, EnumSet.of(StandardOpenOption.READ));
fos = new FileOutputStream(fileString);
writeChannel = Channels.newChannel(fos);
run(mode);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
加密工作无一例外。 但是当我尝试解密数据时(模式 == DECRYPT_MODE 并切换文件名)
javax.crypto.BadPaddingException: Given final block not properly padded
at com.sun.crypto.provider.CipherCore.doFinal(CipherCore.java:811)
at com.sun.crypto.provider.DESCipher.engineDoFinal(DESCipher.java:357)
at javax.crypto.CipherSpi.bufferCrypt(CipherSpi.java:767)
at javax.crypto.CipherSpi.engineDoFinal(CipherSpi.java:721)
at javax.crypto.Cipher.doFinal(Cipher.java:2382)
at Test.run(Test.java:57)
at Test.main(Test.java:77)
弹出来。
我尝试了不同的键,但没有成功。 任何帮助将不胜感激。 [我必须使用频道,此代码仅用于测试部分大类]
【问题讨论】:
标签: java encryption padding des