ASP.NET Core 用密码加密 PDF

需要使用 itext-dotnet :https://github.com/itext/itext-dotnet



使用Nuget:

Install-Package itext

Install-Package itext.bouncy-castle-adapter


使用密码加密PDF:

        public static bool EncryptPdf(string inputPath, string outputPath)
        {
            bool result = false;
            try
            {
                string pdfUserPassword = "1234";
                string pdfOwnerPassword = "5678";

                WriterProperties wp = new WriterProperties();
                wp.SetStandardEncryption(Encoding.Default.GetBytes(pdfUserPassword), Encoding.Default.GetBytes(pdfOwnerPassword), EncryptionConstants.ALLOW_PRINTING, EncryptionConstants.ENCRYPTION_AES_256);


                using (FileStream pdfStream = new FileStream(outputPath, FileMode.Create))
                {
                    using (var existingPdf = new PdfReader(inputPath))
                    {
                        using (PdfWriter newPdf = new PdfWriter(pdfStream, wp))
                        {
                            using (PdfDocument pdfDocument = new PdfDocument(existingPdf, newPdf))
                            {
                                pdfDocument.Close();
                            }
                        }
                    }
                }

                result = true;
            }
            catch (Exception e)
            {
                Console.WriteLine($"error:{e}");
            }
            return result;
        }



EncryptionConstants 的值见文档:

https://api.itextpdf.com/iText/dotnet/8.0.3/classi_text_1_1_kernel_1_1_pdf_1_1_encryption_constants.html#abcc4c990311762a6bf941c30114b2e71


在控制器调用后:

        public IActionResult Index()
        {
            bool result = PdfHelper.EncryptPdf("F:\\pdf\\compressed.tracemonkey-pldi-09.pdf", "F:\\pdf\\compressed.tracemonkey-pldi-15.pdf");
            return Content(result.ToString());
        }



打开生成的 PDF ,提示口令:

image


输入用户口令后,看下文档的 属性 -- 安全性

和我们设置允许用户打印的权限一致

image




当我们进行其他操作时,会再次提示输入口令

image



如果输入的管理员口令,再次查看文档的 属性-- 安全性

可以发现功能可以使用

image




如果只是限制功能,设置用户密码为 NULL 就可以了,权限设置为 0,则禁止所有权限,写法如下:

wp.SetStandardEncryption(null, Encoding.Default.GetBytes(pdfOwnerPassword), 0, EncryptionConstants.ENCRYPTION_AES_256);


看下文档安全性:

image



上面可以看到,如果设置用户密码为 NULL,则文档不需要密码即可打开,权限按照程序设置为准

如果设置管理密码也为 NULL,则 iText 则会生成一个随机密码,iText的实现如下:

      if (ownerPassword != null)
      {
        this.ownerPassword = ownerPassword;
      }
      else
      {
        this.ownerPassword = new byte[16];
        EncryptionProperties.RandomBytes(this.ownerPassword);
      }



所以当自己也不想知道管理密码的时候,可以直接:

wp.SetStandardEncryption(null, null, 0, EncryptionConstants.ENCRYPTION_AES_256);
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章