2017-03-02 95 views
0

我使用https://github.com/TomRoush/PdfBox-Android来加密pdf所描述的here ......但它不起作用。加密PDF与PdfBox-Android不兼容

我用Foxit和AdobeReader检查结果。 AdobeReader说我的文件已损坏,但Foxit向我显示密码对话框。但是,然后我可以尝试我想要的福昕也无法解密我的文件。

如果我设置keyLength = 256我得到了上述描述,但我也尝试了其他2个keyLength值,但是文件未加密。

我错过了什么,或者是加密只是不使用Android上的这个库?

这里是我的代码

static { 
     Security.insertProviderAt(new org.spongycastle.jce.provider.BouncyCastleProvider(), 1); 
    } 

    public void createPdf() { 

    File root   = android.os.Environment.getExternalStorageDirectory(); 
    String path   = root.getAbsolutePath() + "/Download/crypt.pdf"; 


    int      keyLength = 256; 
    AccessPermission   ap   = new AccessPermission(); 
    StandardProtectionPolicy spp   = new StandardProtectionPolicy("12345", "", ap); 

    spp.setEncryptionKeyLength(keyLength); 
    spp.setPermissions(ap); 

    BouncyCastleProvider provider = new BouncyCastleProvider(); 
    Security.addProvider(provider); 

    PDFont  font  = PDType1Font.HELVETICA; 
    PDDocument document = new PDDocument(); 
    PDPage  page  = new PDPage(); 

    document.addPage(page); 

    try { 

     PDPageContentStream contentStream = new PDPageContentStream(document, page); 

     // Write Hello World in blue text 
     contentStream.beginText(); 
     contentStream.setNonStrokingColor(15, 38, 192); 
     contentStream.setFont(font, 12); 
     contentStream.newLineAtOffset(100, 700); 
     contentStream.showText("Hello World"); 
     contentStream.endText(); 
     contentStream.close(); 

     // Save the final pdf document to a file 
     document.protect(spp); 
     document.save(path); 
     document.close(); 

    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
} 
+0

该Android端口基于1.8.x版本,而不是某些2.0.x.因此,查看[1.8.x加密食谱条目](https://pdfbox.apache.org/1.8/cookbook/encryption.html),它告诉你仅支持40和128的密钥长度。因此,不管你得到什么256,都不应该使用。此外,Android端口使用SpongyCastle而不是BouncyCastle,所以请尝试使用该安全提供程序。 – mkl

+0

谢谢你......但正如我所说:我也尝试过40和128,但它不起作用。它也使用SpongyCastle ...(我想:-),因为我使用[静态{Security.insertProviderAt(new org.spongycastle.jce.provider.BouncyCastleProvider(),1); }]在我的活动顶部...(我会更新我的代码上面) – HowardS

+0

请注意,这些是单独的项目...我注意到,Android源代码库没有加密单元测试/解密:-( –

回答

0

Tom here的回答我的问题后,我又尝试一下,好像我从来没有使用过其他keyLength值,否则错过了什么。

所以只要不使用Statement

spp.setEncryptionKeyLength(keyLength); 

然后你用40或加密,只使用

spp.setEncryptionKeyLength(128); 

,但现在在END寄托都运作良好! :-)