2010-09-09 443 views
7

我需要加密和解密pdf文件。有沒有免費或低成本的Java API呢?基本上我需要隱藏來自普通用戶的文件。任何其他建議,以編程方式實現?用於加密/解密pdf文件的Java API

感謝, 深

+1

你打算如何展示他們 「不正常」 的用戶?他們應該帶他們的私鑰(可能是智能卡)? – Bozho 2010-09-09 11:57:33

回答

6

使用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。

+0

謝謝弗雷德裏克。你也可以提供代碼來解密加密文件嗎? – 2010-09-10 16:55:53

+0

對於哪個版本的iText是可行的? – demaniak 2015-11-24 07:36:34

+0

它看起來像iText已經改變了一點,因爲這個答案被接受。 [Here's](http://developers.itextpdf.com/examples/security/clone-encrypting-decrypting-pdfs)如何在iText 7中加密和解密的示例。並且[here](http://itextsupport.com /apidocs/itext7/7.0.0/)是API文檔的更新位置。 – 2017-03-08 00:01:47

6

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