Abhijeet Patil Abhijeet Patil - 1 month ago 19
C# Question

I am using iText for pdf create and encryption

string inputfile = "input file path";
string outfile = "outfile file path";

using (Stream output = new FileStream(outfile, FileMode.Create, FileAccess.Write, FileShare.None))
{
PdfReader reader = new PdfReader(inputfile);
Dictionary<string, string> newInfo = new Dictionary<string, string>();
newInfo.Add("Title", "Title");
newInfo.Add("Subject", "Subject");
newInfo.Add("Keywords", "Keywords");
newInfo.Add("Creator", "Creator");
newInfo.Add("Author", "Author");
newInfo.Add("CustomInfo", "CustomeInformationCanStoreHere");
PdfEncryptor.Encrypt(reader,output,true,"*****","*****",PdfWriter.DO_NOT_ENCRYPT_METADATA, newInfo);
}


I have encrypted PDF file using above code(password and set option as PdfWriter.DO_NOT_ENCRYPT_METADATA)

As option suggests(DO_NOT_ENCRYPT_METADATA) I dont want metadata to be encrypt, but it still encrypt metadata like Title,Subject,Auther,Keywords info..

Is anything missing in above code.

public void manipulatePdf(string source, string destination) {
PdfReader reader = new PdfReader(source);
Stream output = new FileStream(destination, FileMode.Create, FileAccess.Write, FileShare.None);
PdfStamper stamper = new PdfStamper(reader, output);

Dictionary<string, string> newInfo = new Dictionary<string, string>();
newInfo.Add("Title", "Title");
newInfo.Add("Subject", "Subject");
newInfo.Add("Keywords", "Keywords");
newInfo.Add("Creator", "Creator");
newInfo.Add("Author", "Author");
newInfo.Add("CustomInfo", "CustomeInformationCanStoreHere");

stamper.MoreInfo = newInfo;

MemoryStream outStream = new MemoryStream();
XmpWriter xmpw = new XmpWriter(outStream,newInfo);
stamper.XmpMetadata = outStream.ToArray();
byte[] password = Encoding.ASCII.GetBytes("password");
stamper.SetEncryption(password, password, PdfWriter.ALLOW_PRINTING, PdfWriter.ENCRYPTION_AES_128 | PdfWriter.DO_NOT_ENCRYPT_METADATA);

xmpw.Close();
stamper.Close();
reader.Close();
}

Answer

Your interpretation of DO_NOT_ENCRYPT_METADATA is wrong. You think that this setting will not encrypt the info dictionary. That's not what that setting is about. That setting is about the XMP stream. XMP stands for the XML Metadata Platform and it is metadata that is stored as an XML stream inside a PDF (or inside other files such as images). When I look at your code, I see that you're not creating an XMP stream. See the ChangeMetadata example.

Furthermore, you should know that not every type of encryption supports DO_NOT_ENCRYPT_METADATA. For instance 40-bit standard encryption should ignore that setting (but I see that you're using 128-bit standard encryption so that should be fine).

Comments