【问题标题】:Encrypting a pdf is not working with PdfBox-Android加密 pdf 不适用于 PdfBox-Android
【发布时间】:2017-03-02 09:12:41
【问题描述】:

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

我使用 Foxit 和 Adob​​eReader 检查结果。 AdobeReader 说我的文件已损坏,但 Foxit 显示密码对话框。但是我可以尝试我想要的 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();
    }
}

【问题讨论】:

  • 那个 Android 端口基于 1.8.x 版本,而不是某些 2.0.x。因此,查看1.8.x encryption cookbook entry,它告诉您只支持密钥长度 40 和 128。因此,不应使用您为 256 获得的任何东西。此外,Android 端口使用 SpongyCastle 而不是 BouncyCastle,因此请尝试使用该安全提供程序。
  • 谢谢...但正如我所说:我也尝试过 40 和 128 但它不起作用。它还使用 SpongyCastle ...(我想 :-) 因为我使用 [static { Security.insertProviderAt(new org.spongycastle.jce.provider.BouncyCastleProvider(), 1); }] 在我的活动顶部...(我将在上面更新我的代码)
  • 请注意,这些是单独的项目...我注意到 android 源代码存储库没有用于加密/解密的单元测试 :-(

标签: android pdf encryption pdfbox


【解决方案1】:

Tom here 回答我的问题后,我再次尝试,似乎我从未使用过其他 keyLength 值或错过了其他内容。

所以不要使用语句

spp.setEncryptionKeyLength(keyLength);

然后你用 40 加密或只使用

spp.setEncryptionKeyLength(128);

但现在一切都运行良好!! :-)

【讨论】:

    猜你喜欢
    • 2011-08-22
    • 2012-03-30
    • 1970-01-01
    • 2015-05-27
    • 1970-01-01
    • 2013-01-19
    • 2013-01-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多