How to encrypt PDF using Java?
I've been trying to encrypt PDF using Java So far, I can successfully encrypt other file types (. TXT,. PNG, etc.) When I use PDF, it will break the information when I decrypt it
That's why I use it to encrypt it:
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; }
To decrypt it:
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; }
to update:
This is what I use to read the file:
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; }
Use it to rewrite the file
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(); } }
Solution
I'm afraid your file reading code may be the culprit InputStream. The available () method returns only an estimate of the number of bytes that can be read I recommend that you read the entire file into a byte array using Google alternative methods or consider using library methods such as Apache Commons FileUtils Readfiletobytearray (file file) or ioutils toByteArray(InputStream input).
As a secondary check, I suggest you compare the file contents with byte arrays before encryption and after decryption I suspect they are the same (further indicating that file reading and / or writing is the culprit)