iTextSharp使用AES加密读取PDF会引发异常

时间:2014-03-20 16:13:44

标签: c# .net pdf itextsharp itext

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

在内部的结束括号上抛出异常':算术运算导致溢出。

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();
}

我错过了什么吗?

1 个答案:

答案 0 :(得分:2)

以下是我放在一起的快速示例,它可以使用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);
                }
            }
        }

    }
}