Exemple #1
0
        public override void ToPdf(PdfWriter writer, Stream os)
        {
            byte[]        b      = PdfReader.GetStreamBytesRaw(this);
            PdfEncryption crypto = null;

            if (writer != null)
            {
                crypto = writer.Encryption;
            }
            PdfObject objLen = Get(PdfName.LENGTH);
            int       nn     = b.Length;

            if (crypto != null)
            {
                nn = crypto.CalculateStreamSize(nn);
            }
            Put(PdfName.LENGTH, new PdfNumber(nn));
            SuperToPdf(writer, os);
            Put(PdfName.LENGTH, objLen);
            os.Write(STARTSTREAM, 0, STARTSTREAM.Length);
            if (length > 0)
            {
                if (crypto != null && !crypto.IsEmbeddedFilesOnly())
                {
                    b = crypto.EncryptByteArray(b);
                }
                os.Write(b, 0, b.Length);
            }
            os.Write(ENDSTREAM, 0, ENDSTREAM.Length);
        }
Exemple #2
0
        // methods overriding some methods in PdfObject

        /**
         * Returns the PDF representation of this <CODE>PdfString</CODE>.
         *
         * @return        an array of <CODE>byte</CODE>s
         */

        public override void ToPdf(PdfWriter writer, Stream os)
        {
            byte[]        b      = GetBytes();
            PdfEncryption crypto = null;

            if (writer != null)
            {
                crypto = writer.Encryption;
            }
            if (crypto != null && !crypto.IsEmbeddedFilesOnly())
            {
                b = crypto.EncryptByteArray(b);
            }
            if (hexWriting)
            {
                ByteBuffer buf = new ByteBuffer();
                buf.Append('<');
                int len = b.Length;
                for (int k = 0; k < len; ++k)
                {
                    buf.AppendHex(b[k]);
                }
                buf.Append('>');
                os.Write(buf.ToByteArray(), 0, buf.Size);
            }
            else
            {
                b = PdfContentByte.EscapeString(b);
                os.Write(b, 0, b.Length);
            }
        }
Exemple #3
0
        internal void Decrypt(PdfReader reader)
        {
            PdfEncryption decrypt = reader.Decrypt;

            if (decrypt != null)
            {
                originalValue = value;
                decrypt.SetHashKey(objNum, objGen);
                bytes = PdfEncodings.ConvertToBytes(value, null);
                bytes = decrypt.DecryptByteArray(bytes);
                value = PdfEncodings.ConvertToString(bytes, null);
            }
        }
 public PdfEncryption(PdfEncryption enc) : this()
 {
     mkey        = (byte[])enc.mkey.Clone();
     ownerKey    = (byte[])enc.ownerKey.Clone();
     userKey     = (byte[])enc.userKey.Clone();
     permissions = enc.permissions;
     if (enc.documentID != null)
     {
         documentID = (byte[])enc.documentID.Clone();
     }
     revision          = enc.revision;
     keyLength         = enc.keyLength;
     encryptMetadata   = enc.encryptMetadata;
     embeddedFilesOnly = enc.embeddedFilesOnly;
     publicKeyHandler  = enc.publicKeyHandler;
 }
Exemple #5
0
        /**
         * Constructs a <CODE>PdfIndirectObject</CODE>.
         *
         * @param        number            the objecti number
         * @param        generation        the generation number
         * @param        objecti            the direct objecti
         */

        internal PdfIndirectObject(int number, int generation, PdfObject objecti, PdfWriter writer)
        {
            this.writer     = writer;
            this.number     = number;
            this.generation = generation;
            this.objecti    = objecti;
            PdfEncryption crypto = null;

            if (writer != null)
            {
                crypto = writer.Encryption;
            }
            if (crypto != null)
            {
                crypto.SetHashKey(number, generation);
            }
        }
Exemple #6
0
 /**
 * Sets the certificate encryption options for this document. An array of one or more public certificates
 * must be provided together with an array of the same size for the permissions for each certificate.
 *  The open permissions for the document can be
 *  AllowPrinting, AllowModifyContents, AllowCopy, AllowModifyAnnotations,
 *  AllowFillIn, AllowScreenReaders, AllowAssembly and AllowDegradedPrinting.
 *  The permissions can be combined by ORing them.
 * Optionally DO_NOT_ENCRYPT_METADATA can be ored to output the metadata in cleartext
 * @param certs the public certificates to be used for the encryption
 * @param permissions the user permissions for each of the certicates
 * @param encryptionType the type of encryption. It can be one of STANDARD_ENCRYPTION_40, STANDARD_ENCRYPTION_128 or ENCRYPTION_AES128.
 * @throws DocumentException if the document is already open
 */
 public void SetEncryption(X509Certificate[] certs, int[] permissions, int encryptionType)
 {
     if (pdf.IsOpen())
         throw new DocumentException("Encryption can only be added before opening the document.");
     crypto = new PdfEncryption();
     if (certs != null) {
         for (int i=0; i < certs.Length; i++) {
             crypto.AddRecipient(certs[i], permissions[i]);
         }
     }
     crypto.SetCryptoMode(encryptionType, 0);
     crypto.GetEncryptionDictionary();
 }
Exemple #7
0
 /** Sets the encryption options for this document. The userPassword and the
 *  ownerPassword can be null or have zero length. In this case the ownerPassword
 *  is replaced by a random string. The open permissions for the document can be
 *  AllowPrinting, AllowModifyContents, AllowCopy, AllowModifyAnnotations,
 *  AllowFillIn, AllowScreenReaders, AllowAssembly and AllowDegradedPrinting.
 *  The permissions can be combined by ORing them.
 * @param userPassword the user password. Can be null or empty
 * @param ownerPassword the owner password. Can be null or empty
 * @param permissions the user permissions
 * @param encryptionType the type of encryption. It can be one of STANDARD_ENCRYPTION_40, STANDARD_ENCRYPTION_128 or ENCRYPTION_AES128.
 * Optionally DO_NOT_ENCRYPT_METADATA can be ored to output the metadata in cleartext
 * @throws DocumentException if the document is already open
 */
 public void SetEncryption(byte[] userPassword, byte[] ownerPassword, int permissions, int encryptionType)
 {
     if (pdf.IsOpen())
         throw new DocumentException("Encryption can only be added before opening the document.");
     crypto = new PdfEncryption();
     crypto.SetCryptoMode(encryptionType, 0);
     crypto.SetupAllKeys(userPassword, ownerPassword, permissions);
 }
 public PdfEncryption(PdfEncryption enc)
     : this()
 {
     mkey = (byte[])enc.mkey.Clone();
     ownerKey = (byte[])enc.ownerKey.Clone();
     userKey = (byte[])enc.userKey.Clone();
     permissions = enc.permissions;
     if (enc.documentID != null)
     documentID = (byte[])enc.documentID.Clone();
     revision = enc.revision;
     keyLength = enc.keyLength;
     encryptMetadata = enc.encryptMetadata;
     embeddedFilesOnly = enc.embeddedFilesOnly;
     publicKeyHandler = enc.publicKeyHandler;
 }
Exemple #9
0
        public override void ToPdf(PdfWriter writer, Stream os)
        {
            if (inputStream != null && compressed)
            {
                Put(PdfName.FILTER, PdfName.FLATEDECODE);
            }
            PdfEncryption crypto = null;

            if (writer != null)
            {
                crypto = writer.Encryption;
            }
            if (crypto != null)
            {
                PdfObject filter = Get(PdfName.FILTER);
                if (filter != null)
                {
                    if (PdfName.CRYPT.Equals(filter))
                    {
                        crypto = null;
                    }
                    else if (filter.IsArray())
                    {
                        PdfArray a = ((PdfArray)filter);
                        if (a.Size > 0 && PdfName.CRYPT.Equals(a[0]))
                        {
                            crypto = null;
                        }
                    }
                }
            }
            PdfObject nn = Get(PdfName.LENGTH);

            if (crypto != null && nn != null && nn.IsNumber())
            {
                int sz = ((PdfNumber)nn).IntValue;
                Put(PdfName.LENGTH, new PdfNumber(crypto.CalculateStreamSize(sz)));
                SuperToPdf(writer, os);
                Put(PdfName.LENGTH, nn);
            }
            else
            {
                SuperToPdf(writer, os);
            }
            os.Write(STARTSTREAM, 0, STARTSTREAM.Length);
            if (inputStream != null)
            {
                rawLength = 0;
                ZDeflaterOutputStream  def = null;
                OutputStreamCounter    osc = new OutputStreamCounter(os);
                OutputStreamEncryption ose = null;
                Stream fout = osc;
                if (crypto != null && !crypto.IsEmbeddedFilesOnly())
                {
                    fout = ose = crypto.GetEncryptionStream(fout);
                }
                if (compressed)
                {
                    fout = def = new ZDeflaterOutputStream(fout, compressionLevel);
                }

                byte[] buf = new byte[4192];
                while (true)
                {
                    int n = inputStream.Read(buf, 0, buf.Length);
                    if (n <= 0)
                    {
                        break;
                    }
                    fout.Write(buf, 0, n);
                    rawLength += n;
                }
                if (def != null)
                {
                    def.Finish();
                }
                if (ose != null)
                {
                    ose.Finish();
                }
                inputStreamLength = osc.Counter;
            }
            else
            {
                if (crypto != null && !crypto.IsEmbeddedFilesOnly())
                {
                    byte[] b;
                    if (streamBytes != null)
                    {
                        b = crypto.EncryptByteArray(streamBytes.ToArray());
                    }
                    else
                    {
                        b = crypto.EncryptByteArray(bytes);
                    }
                    os.Write(b, 0, b.Length);
                }
                else
                {
                    if (streamBytes != null)
                    {
                        streamBytes.WriteTo(os);
                    }
                    else
                    {
                        os.Write(bytes, 0, bytes.Length);
                    }
                }
            }
            os.Write(ENDSTREAM, 0, ENDSTREAM.Length);
        }
Exemple #10
0
 /** Creates new PdfStamperImp.
 * @param reader the read PDF
 * @param os the output destination
 * @param pdfVersion the new pdf version or '\0' to keep the same version as the original
 * document
 * @param append
 * @throws DocumentException on error
 * @throws IOException
 */
 internal PdfStamperImp(PdfReader reader, Stream os, char pdfVersion, bool append)
     : base(new PdfDocument(), os)
 {
     if (!reader.IsOpenedWithFullPermissions)
         throw new BadPasswordException("PdfReader not opened with owner password");
     if (reader.Tampered)
         throw new DocumentException("The original document was reused. Read it again from file.");
     reader.Tampered = true;
     this.reader = reader;
     file = reader.SafeFile;
     this.append = append;
     if (append) {
         if (reader.IsRebuilt())
             throw new DocumentException("Append mode requires a document without errors even if recovery was possible.");
         if (reader.IsEncrypted())
             crypto = new PdfEncryption(reader.Decrypt);
         pdf_version.SetAppendmode(true);
         file.ReOpen();
         byte[] buf = new byte[8192];
         int n;
         while ((n = file.Read(buf)) > 0)
             this.os.Write(buf, 0, n);
         file.Close();
         prevxref = reader.LastXref;
         reader.Appendable = true;
     }
     else {
         if (pdfVersion == 0)
             base.PdfVersion = reader.PdfVersion;
         else
             base.PdfVersion = pdfVersion;
     }
     base.Open();
     pdf.AddWriter(this);
     if (append) {
         body.Refnum = reader.XrefSize;
         marked = new IntHashtable();
         if (reader.IsNewXrefType())
             fullCompression = true;
         if (reader.IsHybridXref())
             fullCompression = false;
     }
     initialXrefSize = reader.XrefSize;
 }
        /**
         * Generates an OCSP request using BouncyCastle.
         * @param issuerCert	certificate of the issues
         * @param serialNumber	serial number
         * @return	an OCSP request
         * @throws OCSPException
         * @throws IOException
         */
        private static OcspReq GenerateOCSPRequest(X509Certificate issuerCert, BigInteger serialNumber)
        {
            // Generate the id for the certificate we are looking for
            CertificateID id = new CertificateID(CertificateID.HashSha1, issuerCert, serialNumber);

            // basic request generation with nonce
            OcspReqGenerator gen = new OcspReqGenerator();

            gen.AddRequest(id);

            // create details for nonce extension
            ArrayList oids   = new ArrayList();
            ArrayList values = new ArrayList();

            oids.Add(OcspObjectIdentifiers.PkixOcspNonce);
            values.Add(new X509Extension(false, new DerOctetString(new DerOctetString(PdfEncryption.CreateDocumentId()).GetEncoded())));

            gen.SetRequestExtensions(new X509Extensions(oids, values));

            return(gen.Generate());
        }