use of com.tom_roush.pdfbox.pdmodel.encryption.StandardSecurityHandler in project PdfBox-Android by TomRoush.
the class TestSymmetricKeyEncryption method encrypt.
// encrypt with keylength and permission, save, check sizes before and after encryption
// reopen, decrypt and return document
private PDDocument encrypt(int keyLength, boolean preferAES, int sizePriorToEncr, PDDocument doc, String prefix, AccessPermission permission, String userpassword, String ownerpassword) throws IOException {
StandardProtectionPolicy spp = new StandardProtectionPolicy(ownerpassword, userpassword, permission);
spp.setEncryptionKeyLength(keyLength);
spp.setPreferAES(preferAES);
// This must have no effect and should only log a warning.
doc.setAllSecurityToBeRemoved(true);
doc.protect(spp);
File pdfFile = new File(testResultsDir, prefix + keyLength + "-bit-" + (preferAES ? "AES" : "RC4") + "-encrypted.pdf");
doc.save(pdfFile);
doc.close();
long sizeEncrypted = pdfFile.length();
Assert.assertTrue(keyLength + "-bit " + (preferAES ? "AES" : "RC4") + " encrypted pdf should not have same size as plain one", sizeEncrypted != sizePriorToEncr);
// test with owner password => full permissions
PDDocument encryptedDoc = PDDocument.load(pdfFile, ownerpassword);
Assert.assertTrue(encryptedDoc.isEncrypted());
Assert.assertTrue(encryptedDoc.getCurrentAccessPermission().isOwnerPermission());
// Older encryption allows to get the user password when the owner password is known
PDEncryption encryption = encryptedDoc.getEncryption();
int revision = encryption.getRevision();
if (revision < 5) {
StandardSecurityHandler standardSecurityHandler = new StandardSecurityHandler();
int keyLengthInBytes = encryption.getVersion() == 1 ? 5 : encryption.getLength() / 8;
byte[] computedUserPassword = standardSecurityHandler.getUserPassword(ownerpassword.getBytes(Charsets.ISO_8859_1), encryption.getOwnerKey(), revision, keyLengthInBytes);
assertEquals(userpassword.substring(0, 32), new String(computedUserPassword, Charsets.ISO_8859_1));
}
encryptedDoc.close();
// test with user password => restricted permissions
encryptedDoc = PDDocument.load(pdfFile, userpassword);
Assert.assertTrue(encryptedDoc.isEncrypted());
Assert.assertFalse(encryptedDoc.getCurrentAccessPermission().isOwnerPermission());
assertEquals(permission.getPermissionBytes(), encryptedDoc.getCurrentAccessPermission().getPermissionBytes());
return encryptedDoc;
}
Aggregations