如何使用Java加密PDF?
发布时间:2020-12-14 06:02:33 所属栏目:Java 来源:网络整理
导读:我一直在尝试使用 Java加密PDF.到目前为止,我可以成功加密其他文件类型(.txt,.png等).当我使用PDF时,它会在我解密时打破信息. 这就是我用它来加密它: public byte[] cryptograph(Key key,byte[] content){ Cipher cipher; byte[] cryptograph = null; try {
|
我一直在尝试使用
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).
作为二次检查,我建议您在加密前和解密后对文件内容进行字节数组比较.我怀疑它们是相同的(进一步表明文件读取和/或写入是罪魁祸首). (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
