我一直在尝试使用
Java加密PDF.到目前为止,我可以成功加密其他文件类型(.txt,.png等).当我使用PDF时,它会在我解密时打破信息.
这就是我用它来加密它:
public byte[] cryptograph(Key key,byte[] content){
Cipher cipher;
byte[] cryptograph = null;
try {
cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE,key);
cryptograph = cipher.doFinal(content);
} catch (Exception e) {
e.printstacktrace();
}
return cryptograph;
}
这要解密它:
public byte[] decrypt(Key key,byte[] textCryp){
Cipher cipher;
byte[] decrypted = null;
try {
cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE,key);
decrypted = cipher.doFinal(textCryp);
} catch (Exception e) {
e.printstacktrace();
}
return decrypted;
}
更新:
这是我用来读取文件的内容:
public byte[] getFile(){
byte[] content = null;
try {
InputStream is = new FileInputStream("test.pdf");
BufferedInputStream vf = new BufferedInputStream(is);
content = new byte[vf.available()];
vf.read(content);
} catch (FileNotFoundException e) {
e.printstacktrace();
} catch (IOException e) {
// Todo Auto-generated catch block
e.printstacktrace();
}
return content;
}
用它来重写文件
public static void saveDecrypt(byte[] bytes) throws IOException{
Document doc=new Document();
try {
PdfWriter.getInstance(doc,new FileOutputStream("fileDecrypted.pdf"));
doc.open();
doc.add(new Paragraph(new String(bytes)));
doc.close();
} catch (DocumentException e) {
// Todo Auto-generated catch block
e.printstacktrace();
}
}
解决方法
我担心你的文件阅读代码可能是罪魁祸首.
InputStream.available()方法仅返回可读取的字节数的估计值.我建议您将
Google alternative methods读取整个文件到字节数组或考虑使用库方法,如Apache Commons
FileUtils.readFileToByteArray(File file)或
IOUtils.toByteArray(InputStream input).
作为二次检查,我建议您在加密前和解密后对文件内容进行字节数组比较.我怀疑它们是相同的(进一步表明文件读取和/或写入是罪魁祸首).