Reputation: 98
I'm trying to open a PDF with itextsharp that was encrypted with AES 256 and display it. The PDF was encrypted with itextsharp as well. I'm using 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.
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?
Upvotes: 3
Views: 2209
Reputation: 29895
Here's a quick sample I put together that works to encrypt a PDF with 256-bit AES encryption:
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);
}
}
}
}
}
Upvotes: 2