用于加密/解密pdf文件的Java API

时间:2010-09-09 11:17:45

标签: java pdf encryption

我需要加密和解密pdf文件。是否有免费或低成本的Java API可以做到这一点?基本上我需要隐藏普通用户的文件。关于以编程方式实现这一点的任何其他建议?

谢谢, 深

3 个答案:

答案 0 :(得分:7)

使用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);

以下是PDFEncryptorPDFWriter的API(适用于权限)。

答案 1 :(得分:7)

使用PDFBox(基于Decrypt.java代码):

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

答案 2 :(得分:5)

iText支持加密。