简体   繁体   English

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

[英]iTextSharp read PDF with AES Encryption throws exception

I'm trying to open a PDF with itextsharp that was encrypted with AES 256 and display it. 我正在尝试使用AES 256加密的itextsharp打开PDF并显示它。 The PDF was encrypted with itextsharp as well. PDF也是用itextsharp加密的。 I'm using iTextSharp 5.5.0.0. 我正在使用iTextSharp 5.5.0.0。 This code works if the encryption is set to 'standard encryption'. 如果加密设置为“标准加密”,则此代码有效。

An exception is thrown on the closing bracket of the inner 'using': Arithmetic operation resulted in an overflow. 内部'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();

Update (forgot encryption code): 更新(忘记加密代码):

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

Am I missing something? 我错过了什么吗?

Here's a quick sample I put together that works to encrypt a PDF with 256-bit AES encryption: 这是我放在一起的快速示例,用于加密具有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);
                }
            }
        }

    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM