加密 pdf 不适用于 PdfBox-Android

Encrypting a pdf is not working with PdfBox-Android

我用https://github.com/TomRoush/PdfBox-Android to encrypt a pdf like described here ...但是没用

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

Tom here 回答了我的问题后,我又试了一次,似乎我从未使用过其他 keyLength 值或遗漏了其他值。

所以不要使用声明

spp.setEncryptionKeyLength(keyLength);

那么你用40加密或者只用

spp.setEncryptionKeyLength(128);

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