【问题标题】:iTextSharp read PDF with AES Encryption throws exceptioniTextSharp 使用 AES 加密读取 PDF 引发异常
【发布时间】:2014-03-20 16:13:43
【问题描述】:

我正在尝试使用 AES 256 加密的 itextsharp 打开 PDF 并显示它。 PDF 也使用 itextsharp 加密。我正在使用 iTextSharp 5.5.0.0。如果加密设置为“标准加密”,则此代码有效。

内部'using'的右括号抛出异常:算术运算导致溢出。

string path = Server.MapPath("~/App_Data/pdf/foo.pdf");
string password = "openSesame";

Response.Clear();
Response.ClearHeaders();
Response.AddHeader("Expires", "0");
Response.AddHeader("Cache-Control", "private");
Response.AddHeader("content-disposition", "inline");
Response.ContentType = "application/pdf";

using (MemoryStream memoryStream = new MemoryStream())
{
    using (PdfReader reader = new PdfReader(path, Encoding.UTF8.GetBytes(password)))
    using (PdfStamper stamper = new PdfStamper(reader, memoryStream))
    {
    }

    Response.BinaryWrite(memoryStream.GetBuffer());
}

Response.End();

更新(忘记加密代码):

using (FileStream fileStream = new FileStream(path, FileMode.Create))
{
    PdfCopyFields copy = new PdfCopyFields(fileStream);
    var bytes = Encoding.UTF8.GetBytes(password);
    copy.SetEncryption(bytes, bytes, 0, PdfWriter.ENCRYPTION_AES_256);

    // add some documents with 'copy.AddDocument()';

    copy.Close();
}

我错过了什么吗?

【问题讨论】:

  • 你能添加你的copy初始化代码吗?
  • 已添加。你让我思考......我想知道它是否是 PdfCopyFields 中的东西(已过时)......我遇到了 PdfCopy 问题,所以我需要使用 PdfCopyFields,现在不记得为什么了。我将使用 PdfCopy 尝试我的代码。
  • 我已经确认,如果使用 PdfCopy 而不是 PdfCopyFields,则会引发相同的异常。

标签: c# .net pdf itextsharp itext


【解决方案1】:

这是我整理的一个快速示例,用于使用 256 位 AES 加密对 PDF 进行加密:

var openDialog = new OpenFileDialog();
openDialog.DefaultExt = "pdf";
if (openDialog.ShowDialog() == true)
{
    using (var input = openDialog.OpenFile())
    {
        var saveDialog = new SaveFileDialog();
        saveDialog.DefaultExt = "pdf";
        if (saveDialog.ShowDialog() == true)
        {
            using (var reader = new PdfReader(input)) 
            {
                using (var output = saveDialog.OpenFile())
                {
                    PdfEncryptor.Encrypt(
                        reader, output,
                        PdfWriter.ENCRYPTION_AES_256,
                        "password", "password",
                        PdfWriter.ALLOW_PRINTING);
                }
            }
        }

    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-02-08
    • 2023-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-01
    • 1970-01-01
    相关资源
    最近更新 更多