Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java API for encrypting / decrypting pdf files

I need to encrypt and decrypt pdf files. Is there a free or low cost Java API that does that ? Basically I need to hide files from normal users. Any other suggestion on achieving that programatically ?

Thanks, Deep

like image 876
DG. Avatar asked Sep 09 '10 11:09

DG.


People also ask

How do I decrypt my PDF File?

How to unlock a PDF to remove password security: Open the PDF in Acrobat. Use the “Unlock” tool: Choose “Tools” > “Protect” > “Encrypt” > “Remove Security.”

How do I Encrypt a PDF attachment?

Add a password to Adobe Acrobat (pdf)Open the PDF and choose Tools > Protect > Encrypt > Encrypt with Password. If you receive a prompt, click Yes to change the security. Select Require a Password to Open the Document, then type the password in the corresponding field.

Can PDF be decrypted?

Most PDFs can be unlocked! Files with an owner password can be unlocked instantly. However, if the file is thoroughly encrypted, you can only unlock the file by providing the correct password. Just upload your file and the password will be removed from your PDF.


1 Answers

Using PDFBox (based on Decrypt.java code) :

PDDocument document = null;

try
{
    document = PDDocument.load( infile );

    if( document.isEncrypted() )
    {
        DecryptionMaterial decryptionMaterial = null;
        decryptionMaterial = new StandardDecryptionMaterial(password);
        document.openProtection(decryptionMaterial);
        AccessPermission ap = document.getCurrentAccessPermission();
        if(ap.isOwnerPermission())
        {
            document.setAllSecurityToBeRemoved(true);
            document.save( outfile );
        }
        else
        {
            throw new IOException(
            "Error: You are only allowed to decrypt a document with the owner password." );
        }
    }
    else
    {
        System.err.println( "Error: Document is not encrypted." );
    }
}
finally
{
    if( document != null )
    {
        document.close();
    }
}
like image 197
Anthony O. Avatar answered Oct 31 '22 12:10

Anthony O.