When downloading the pdf file, I specified the password "123456789987654abc211234567899klm7654321". When opening, I can remove a few characters, for example,
"123456789987654abc211234567899kl" - file will open anyway! But if I use
"123456789987654abc211234567899k" - file not open
help me understand what is the problem
private static void encryptPdf(
InputStream inputStream,
OutputStream outputStream,
String ownerPassword,
String userPassword) throws Exception
{
PDDocument document = PDDocument.load(inputStream);
if (document.isEncrypted())
{
return;
}
AccessPermission accessPermission = new AccessPermission();
StandardProtectionPolicy spp =
new StandardProtectionPolicy(ownerPassword, userPassword, accessPermission);
spp.setEncryptionKeyLength(40);
document.protect(spp);
document.save(outputStream);
document.close();
}
The first step in calculating the encryption key from the password for pdf encryption up to revision 4 is
The password string is generated from host system codepage characters (or system scripts) by first converting the string to PDFDocEncoding. If the input is Unicode, first convert to a codepage encoding, and then to PDFDocEncoding for backward compatibility. Pad or truncate the resulting password string to exactly 32 bytes. If the password string is more than 32 bytes long, use only its first 32 bytes; if it is less than 32 bytes long, pad it by appending the required number of additional bytes from the beginning of the following padding string:
<28 BF 4E 5E 4E 75 8A 41 64 00 4E 56 FF FA 01 08 2E 2E 00 B6 D0 68 3E 80 2F 0C A9 FE 64 53 69 7A>
That is, if the password string is n bytes long, append the first 32 - n bytes of the padding string to the end of the password string. If the password string is empty (zero-length), meaning there is no user password, substitute the entire padding string in its place.
(ISO 32000-2 section 7.6.4.3.2 "Algorithm 2: Computing a file encryption key in order to encrypt a document (revision 4 and earlier)")
For more modern encryption types you have a restriction, too, but generally less harsh:
The UTF-8 password string shall be generated from Unicode input by processing the input string with the SASLprep (Internet RFC 4013) profile of stringprep (Internet RFC 3454) using the Normalize and BiDi options, and then converting to a UTF-8 representation.
Truncate the UTF-8 representation to 127 bytes if it is longer than 127 bytes.
(ISO 32000-2 section 7.6.4.3.3 "Algorithm 2.A: Retrieving the file encryption key from an encrypted document in order to decrypt it (revision 6 and later)")