c# - 打开 PDFSharp 文档并保存删除密码

标签 c# passwords pdfsharp

出于 2 个不同的原因,我在 2 个不同的应用程序中使用 PDFSharp。第一个是密码保护文件,第二个是给文件加水印。这些流程都在自己的应用程序/工作流程中单独工作。问题是应用程序 1 只知道密码,应用程序 2 只知道水印,应用程序 1 使用默认所有者密码和动态用户密码,应用程序 2 使用所有者密码打开文档以应用水印。问题是密码没有保留,似乎 PDFSharp 在保存文档时忽略了以前的 PDF 密码?!

有没有办法在应用水印时保持安全设置,而无需再次明确定义密码?

我在 PDFSharp 论坛上发布了这个,但他们忽略了它,这不是一个好兆头吗?! http://forum.pdfsharp.net/viewtopic.php?f=2&t=2003&p=5737#p5737

亲切的问候,

最佳答案

我认为这是 PDF sharp 的局限性,因为我在该论坛上没有得到他们的回复或帮助。我打开了那里的代码并进行了以下更改以更正错误。首先,我在 SecurityHandler.cs 类上添加了一个新属性

public string OwnerPassword
{
  set { SecurityHandler.OwnerPassword = value; }
}

/// <summary>
/// TODO: JOSH
/// </summary>
public bool MaintainOwnerAndUserPassword
{
    get { return SecurityHandler.MaintainOwnerAndUserPassword; }
    set { SecurityHandler.MaintainOwnerAndUserPassword = value; }
}

然后我将 PdfDocument.cs 类的 doSave 方法更改为如下所示:

    void DoSave(PdfWriter writer)
{
  if (this.pages == null || this.pages.Count == 0)
    throw new InvalidOperationException("Cannot save a PDF document with no pages.");

  try
  {
    bool encrypt = this.securitySettings.DocumentSecurityLevel != PdfDocumentSecurityLevel.None;
    if (encrypt)
    {
      PdfStandardSecurityHandler securityHandler = this.securitySettings.SecurityHandler;
      if (securityHandler.Reference == null)
        this.irefTable.Add(securityHandler);
      else
        Debug.Assert(this.irefTable.Contains(securityHandler.ObjectID));
      this.trailer.Elements[PdfTrailer.Keys.Encrypt] = this.securitySettings.SecurityHandler.Reference;
    }
    else
      this.trailer.Elements.Remove(PdfTrailer.Keys.Encrypt);

    PrepareForSave();

    if (encrypt && !securitySettings.SecurityHandler.MaintainOwnerAndUserPassword)
      this.securitySettings.SecurityHandler.PrepareEncryption();

...

最后,我将 PDFSecuritySettings.cs 上的 CanSave 方法更改为:

    internal bool CanSave(ref string message)
{
  if (this.documentSecurityLevel != PdfDocumentSecurityLevel.None)
  {
    if ((SecurityHandler.userPassword == null || SecurityHandler.userPassword.Length == 0) &&
        (SecurityHandler.ownerPassword == null || SecurityHandler.ownerPassword.Length == 0) &&
        !SecurityHandler.MaintainOwnerAndUserPassword)
    {
      message = PSSR.UserOrOwnerPasswordRequired;
      return false;
    }
  }
  return true;
}

这应该允许您设置 MaintainOwnerAndUserPassword 设置,假设您已经有一个散列的用户名和密码,它应该可以正常工作,

彻底结束。

关于c# - 打开 PDFSharp 文档并保存删除密码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10442548/

相关文章:

c# - 更改现有文本的文本颜色

c# - Resharper:尝试创建自定义规则/模式,其中评论必须以大写字母开头并以句点结尾

c# - 仅在文件不存在时才创建文件

c# - 在 ASP.NET MVC 中的静态字段中使用 Server.MapPath()

security - 目前哪种哈希函数是密码的最佳选择?

c# - PDFsharp/MigraDoc 脚注用法

javascript - html 表单发送敏感数据 javascript https

Python:如何让程序在用户输入时提示用户一定的固定次数?

c#-4.0 - PDFsharp编辑pdf文件

c# - PDFsharp - 如何创建第二页