它正在正常工作。
请查看您使用的方法的文档:
/** Sets the encryption options for this document. The userPassword and the
* ownerPassword can be null or have zero length. In this case the ownerPassword
* is replaced by a random string. The open permissions for the document can be
* AllowPrinting, AllowModifyContents, AllowCopy, AllowModifyAnnotations,
* AllowFillIn, AllowScreenReaders, AllowAssembly and AllowDegradedPrinting.
* The permissions can be combined by ORing them.
* @param userPassword the user password. Can be null or empty
* @param ownerPassword the owner password. Can be null or empty
* @param permissions the user permissions
* @param strength128Bits <code>true</code> for 128 bit key length, <code>false</code> for 40 bit key length
* @throws DocumentException if the document is already open
*/
virtual public void SetEncryption(byte[] userPassword, byte[] ownerPassword, int permissions, bool strength128Bits)
因此,如果您不提供所有者密码的值,则记录的行为是 使用随机字符串,与您观察到的完全一样。
显然您尝试将 PDF 的权限设置为仅PdfWriter.AllowScreenReaders,但设置此权限选择仅适用于加密文件,并且对于加密需要非空所有者密码,因此 iText 为您选择一个。
另一方面,空的用户密码是可能的,因为在加密和解密期间使用它的过程中,无论如何都会将“默认密码字符串”附加到用户密码值。
附录
在回答 cmets 中的问题时...
“被随机字符串替换”到底是什么意思?该密码的格式是什么?
if (ownerPassword == null || ownerPassword.Length == 0)
ownerPassword = DigestAlgorithms.Digest("MD5", CreateDocumentId());
(PdfEncryption 方法SetupAllKeys)
CreateDocumentId 的定义如下:
public static byte[] CreateDocumentId() {
long time = DateTime.Now.Ticks + Environment.TickCount;
long mem = GC.GetTotalMemory(false);
String s = time + "+" + mem + "+" + (seq++);
byte[] b = Encoding.ASCII.GetBytes(s);
return DigestAlgorithms.Digest("MD5", b);
}
你还能找回密码吗?
密码未明确存储在任何地方以供以后检索。在这种情况下,即调用使用空所有者密码进行加密,假定调用者对知道密码不感兴趣。
如果您觉得这很奇怪,请注意,对于文档数据的实际加密,使用的是用户密码,而不是所有者密码。 (更准确地说,是从用户密码派生的值。)文档加密期间的所有者密码仅用于加密用户密码(更准确地说,是从用户密码派生的值)并将该值存储在 PDF 中。
当再次打开PDF并且用户提供密码时,测试是否可以立即用于文档数据解密(即是用户密码)或者是否可以将上述值解密为然后可以解密文档的用户密码(即它是所有者密码)。
在任何一种情况下,用户都可以访问 PDF,但如果它只是用户密码,而不是所有者密码,则 PDF 处理器应根据给定的权限值限制允许的操作。
因此,此处未提供所有者密码的调用者被解释为对在符合规范的 PDF 处理器中具有对 PDF 的完全访问权限的任何人不感兴趣,对于受限访问,用户密码就足够了。这与由于丢失密码而使文档无法解密无关...
它会使用指定的关键优势之一吗?
嗯,MD5 返回一个 128 位散列,但由于散列数据的结构众所周知,密码远没有真正随机的 128 位值强。另一方面,一个八字符的字符串通常也远没有那么强...