简体   繁体   中英

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

Using iText :

  // Assuming you provide the following yourself:
  File inputFile; 
  File outputFile;
  String userPassword;
  String ownerPassword;
  // A bit-field containing file permissions.
  int permissions = PDFWriter.ALLOW_PRINTING | PDFWriter.ALLOW_COPY;

  PdfReader reader = new PdfReader(inputFile);
  PdfEncryptor.encrypt(reader, new FileOutputStream(outputFile),
      ENCRYPTION_AES128, userPassword, ownerPassword, 
      permissions);

Here's the API for PDFEncryptor and PDFWriter (for the permissions).

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();
    }
}

iText支持加密。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM