我一直在尝试使用 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();
}
}