/// <summary>
        /// Method that will be called during the signing process
        /// </summary>
        /// <param name="data">Stream with the doc data that should be used in the hasing process</param>
        /// <returns></returns>
        public override byte[] Sign(Stream data)
        {
            // crea pdf pkcs7 for signing the document
            var sgn = new PdfPKCS7(null,
                                   _certificates.ToArray(),
                                   DigestAlgorithms.SHA256,
                                   false);

            // get hash for document bytes
            NakedHash = DigestAlgorithms.Digest(data, DigestAlgorithms.SHA256);

            // get attributes
            var docBytes = sgn.GetAuthenticatedAttributeBytes(NakedHash,
                                                              PdfSigner.CryptoStandard.CMS,
                                                              _ocspBytes?.ToList(),
                                                              _crlBytesCollection?.ToList());

            // hash it again
            using var hashMemoryStream = new MemoryStream(docBytes, false);
            var docBytesHash = DigestAlgorithms.Digest(hashMemoryStream, DigestAlgorithms.SHA256);


            //prepend sha256 prefix
            var totalHash = new byte[_sha256SigPrefix.Length + docBytesHash.Length];

            _sha256SigPrefix.CopyTo(totalHash, 0);
            docBytesHash.CopyTo(totalHash, _sha256SigPrefix.Length);
            HashToBeSignedByAma = totalHash;
            return(Array.Empty <byte>());
        }
Exemplo n.º 2
0
        /**
         */
        private byte[] ComputeOwnerKey(byte[] userPad, byte[] ownerPad)
        {
            byte[] ownerKey = new byte[32];

            byte[] digest = DigestAlgorithms.Digest("MD5", ownerPad);
            if (revision == STANDARD_ENCRYPTION_128 || revision == AES_128)
            {
                byte[] mkey = new byte[keyLength / 8];
                // only use for the input as many bit as the key consists of
                for (int k = 0; k < 50; ++k)
                {
                    Array.Copy(DigestAlgorithms.Digest("MD5", digest, 0, mkey.Length), 0, digest, 0, mkey.Length);
                }
                Array.Copy(userPad, 0, ownerKey, 0, 32);
                for (int i = 0; i < 20; ++i)
                {
                    for (int j = 0; j < mkey.Length; ++j)
                    {
                        mkey[j] = (byte)(digest[j] ^ i);
                    }
                    rc4.PrepareARCFOURKey(mkey);
                    rc4.EncryptARCFOUR(ownerKey);
                }
            }
            else
            {
                rc4.PrepareARCFOURKey(digest, 0, 5);
                rc4.EncryptARCFOUR(userPad, ownerKey);
            }

            return(ownerKey);
        }
 public override byte[] Sign(Stream data)
 {
     SHA256 sha = new SHA256CryptoServiceProvider();
     String hashAlgorithm = DigestAlgorithms.SHA256;
     Hash = DigestAlgorithms.Digest(data, DigestAlgorithms.GetMessageDigest(hashAlgorithm));
     return new byte[0];
 }
Exemplo n.º 4
0
        public static byte[] CreateDocumentId()
        {
            long   time = DateTime.Now.Ticks + Environment.TickCount;
            long   mem  = GC.GetTotalMemory(false);
            String s    = time + "+" + mem + "+" + (seq++);

            byte[] b = Encoding.ASCII.GetBytes(s);
            return(DigestAlgorithms.Digest("MD5", b));
        }
    public byte[] Sign(Stream data)
    {
        String hashAlgorithm = "SHA256";

        byte[] hash = DigestAlgorithms.Digest(data, hashAlgorithm);
        // call your external signature service to create a CMS signature
        // container for the given document hash and return the bytes of
        // that signature container.
        return(CALL_YOUR_EXTERNAL_SIGNATURE_SERVICE_TO_CREATE_A_CMS_SIGNATURE_CONTAINER_FOR(hash));
    }
Exemplo n.º 6
0
            private void SerObject(PdfObject obj, int level, ByteBuffer bb, HashSet2 <PdfObject> serialized)
            {
                if (level <= 0)
                {
                    return;
                }
                if (obj == null)
                {
                    bb.Append("$Lnull");
                    return;
                }

                if (obj.IsIndirect())
                {
                    if (serialized.Contains(obj))
                    {
                        return;
                    }
                    else
                    {
                        serialized.Add(obj);
                    }
                }
                obj = PdfReader.GetPdfObject(obj);
                if (obj.IsStream())
                {
                    bb.Append("$B");
                    SerDic((PdfDictionary)obj, level - 1, bb, serialized);
                    if (level > 0)
                    {
                        bb.Append(DigestAlgorithms.Digest("MD5", PdfReader.GetStreamBytesRaw((PRStream)obj)));
                    }
                }
                else if (obj.IsDictionary())
                {
                    SerDic((PdfDictionary)obj, level - 1, bb, serialized);
                }
                else if (obj.IsArray())
                {
                    SerArray((PdfArray)obj, level - 1, bb, serialized);
                }
                else if (obj.IsString())
                {
                    bb.Append("$S").Append(obj.ToString());
                }
                else if (obj.IsName())
                {
                    bb.Append("$N").Append(obj.ToString());
                }
                else
                {
                    bb.Append("$L").Append(obj.ToString());
                }
            }
Exemplo n.º 7
0
 internal static byte[] CalcDocBytesHash(Stream docBytes)
 {
     byte[] docBytesHash = null;
     try {
         docBytesHash = DigestAlgorithms.Digest(docBytes, SignTestPortUtil.GetMessageDigest(HASH_ALGORITHM));
     }
     catch (Exception) {
     }
     // dummy catch clause
     return(docBytesHash);
 }
Exemplo n.º 8
0
            public byte[] Sign(Stream data)
            {
                PrivateKeySignature signature = new PrivateKeySignature(pk.Key, "SHA256");
                String   hashAlgorithm        = signature.GetHashAlgorithm();
                PdfPKCS7 sgn = new PdfPKCS7(null, chain, hashAlgorithm, false);

                byte[]   hash        = DigestAlgorithms.Digest(data, hashAlgorithm);
                DateTime signingTime = DateTime.Now;

                byte[] sh           = sgn.getAuthenticatedAttributeBytes(hash, signingTime, null, null, CryptoStandard.CMS);
                byte[] extSignature = signature.Sign(sh);
                sgn.SetExternalDigest(extSignature, null, signature.GetEncryptionAlgorithm());
                return(sgn.GetEncodedPKCS7(hash, signingTime, null, null, null, CryptoStandard.CMS));
            }
Exemplo n.º 9
0
        /**
         *
         * ownerKey, documentID must be setuped
         */
        private void SetupGlobalEncryptionKey(byte[] documentID, byte[] userPad, byte[] ownerKey, long permissions)
        {
            this.documentID  = documentID;
            this.ownerKey    = ownerKey;
            this.permissions = permissions;
            // use variable keylength
            mkey = new byte[keyLength / 8];

            //fixed by ujihara in order to follow PDF refrence
            md5.Reset();
            md5.BlockUpdate(userPad, 0, userPad.Length);
            md5.BlockUpdate(ownerKey, 0, ownerKey.Length);

            byte[] ext = new byte[4];
            ext[0] = (byte)permissions;
            ext[1] = (byte)(permissions >> 8);
            ext[2] = (byte)(permissions >> 16);
            ext[3] = (byte)(permissions >> 24);
            md5.BlockUpdate(ext, 0, 4);
            if (documentID != null)
            {
                md5.BlockUpdate(documentID, 0, documentID.Length);
            }
            if (!encryptMetadata)
            {
                md5.BlockUpdate(metadataPad, 0, metadataPad.Length);
            }
            byte[] hash = new byte[md5.GetDigestSize()];
            md5.DoFinal(hash, 0);

            byte[] digest = new byte[mkey.Length];
            Array.Copy(hash, 0, digest, 0, mkey.Length);


            md5.Reset();
            // only use the really needed bits as input for the hash
            if (revision == STANDARD_ENCRYPTION_128 || revision == AES_128)
            {
                for (int k = 0; k < 50; ++k)
                {
                    Array.Copy(DigestAlgorithms.Digest("MD5", digest), 0, digest, 0, mkey.Length);
                }
            }
            Array.Copy(digest, 0, mkey, 0, mkey.Length);
        }
Exemplo n.º 10
0
        public virtual IAuthenticatedAttributes CreateAuthenticatedAttribute(IPdfPreSigningSession pdfPreSigningSession)
        {
            var pdfContentBytes = File.ReadAllBytes(pdfPreSigningSession.FilePath);

            using (var PdfReader = new PdfReader(pdfContentBytes))
            {
                using (var pdfStamper = PdfStamper.CreateSignature(PdfReader, null, '\0', pdfPreSigningSession.FilePath, true))
                {
                    var authenticatedAttributes = new AuthenticatedAttributes();
                    var publicKeyManager        = GetPublicKeyManager(pdfPreSigningSession);

                    authenticatedAttributes.PdfSignatureAppearance = pdfStamper.SignatureAppearance;

                    UpdatePdfSignatureAppearance(pdfPreSigningSession, PdfReader, authenticatedAttributes.PdfSignatureAppearance);

                    authenticatedAttributes
                    .PdfSignatureAppearance
                    .PreClose(new Dictionary <PdfName, int> {
                        { PdfName.CONTENTS, SIGNATURE_ESTIMATED_SIZE * 2 + 2 }
                    });

                    var pdfSignatureAppearanceData = authenticatedAttributes
                                                     .PdfSignatureAppearance
                                                     .GetRangeStream();

                    authenticatedAttributes.DigestedData = DigestAlgorithms
                                                           .Digest
                                                           (
                        pdfSignatureAppearanceData,
                        pdfPreSigningSession.HashAlgorithm
                                                           );

                    authenticatedAttributes.Value = publicKeyManager
                                                    .getAuthenticatedAttributeBytes
                                                    (
                        authenticatedAttributes.DigestedData,
                        null,
                        null,
                        CryptoStandard.CMS
                                                    );

                    return(authenticatedAttributes);
                }
            }
        }
Exemplo n.º 11
0
        /// <summary>
        /// Computes an attribute containing a time-stamp token of the provided data, from the provided TSA using the
        /// provided.
        /// </summary>
        /// <remarks>
        /// Computes an attribute containing a time-stamp token of the provided data, from the provided TSA using the
        /// provided. The hashing is performed by the method using the specified algorithm and a BouncyCastle provider.
        /// </remarks>
        /// <param name="signedData"></param>
        /// <exception cref="System.Exception">System.Exception</exception>
        protected internal virtual BcCms.Attribute GetTimeStampAttribute(DerObjectIdentifier oid
                                                                         , ITspSource tsa, AlgorithmIdentifier digestAlgorithm, byte[] messageImprint)
        {
            try
            {
                //jbonilla Hack para obtener el digest del TSA
                IDigest digest        = null;
                string  algorithmName = null;
                if (tsa is ITSAClient)
                {
                    //TODO jbonilla - ¿AlgorithmIdentifier?
                    digest        = ((ITSAClient)tsa).GetMessageDigest();
                    algorithmName = digest.AlgorithmName;
                }
                else
                {
                    digest        = DigestUtilities.GetDigest(DigestAlgorithm.SHA1.GetName());
                    algorithmName = DigestAlgorithm.SHA1.GetName();
                }
                byte[] toTimeStamp = DigestAlgorithms.Digest(digest, messageImprint);

                TimeStampResponse tsresp = tsa.GetTimeStampResponse(DigestAlgorithm.GetByName(algorithmName)
                                                                    , toTimeStamp);
                TimeStampToken tstoken = tsresp.TimeStampToken;
                if (tstoken == null)
                {
                    throw new ArgumentNullException("The TimeStampToken returned for the signature time stamp was empty."
                                                    );
                }
                BcCms.Attribute signatureTimeStamp = new BcCms.Attribute(oid, new DerSet(Asn1Object.FromByteArray
                                                                                             (tstoken.GetEncoded())));
                return(signatureTimeStamp);
            }
            catch (IOException e)
            {
                throw new RuntimeException(e);
            }
            catch (NoSuchAlgorithmException e)
            {
                throw new RuntimeException(e);
            }
        }
Exemplo n.º 12
0
        /// <summary>
        /// Methods which returns base64 digested PDF.
        /// </summary>
        /// <param name="unsignedPdf">Path to pdf which needs to be signed</param>
        /// <param name="tempPdf">Path to temporary pdf</param>
        /// <param name="signatureFieldName">Name of field</param>
        /// <returns></returns>
        public static string GetBytesToSign(string unsignedPdf, string tempPdf, string signatureFieldName)
        {
            if (File.Exists(tempPdf))
            {
                File.Delete(tempPdf);
            }

            using (PdfReader reader = new PdfReader(unsignedPdf))
            {
                using (FileStream os = File.OpenWrite(tempPdf))
                {
                    StampingProperties sp = new StampingProperties();
                    sp.UseAppendMode();

                    PdfSigner pdfSigner = new PdfSigner(reader, os, sp);
                    pdfSigner.SetFieldName(signatureFieldName);

                    PdfSignatureAppearance appearance = pdfSigner.GetSignatureAppearance();
                    appearance.SetPageNumber(1);
                    appearance.SetPageRect(new Rectangle(100, 100));
                    appearance.SetLocation("Varazdin");

                    //Creating container for emty signature, with atrivute where digest is calculated.
                    //ExternalHashingSignatureContainer external = new ExternalHashingSignatureContainer(PdfName.Adobe_PPKLite, PdfName.Adbe_pkcs7_detached);
                    //pdfSigner.SignExternalContainer(external, 8192);
                    //hash = external.Hash;

                    //Creating container for empty signature.
                    IExternalSignatureContainer external = new ExternalBlankSignatureContainer(PdfName.Adobe_PPKLite, PdfName.Adbe_x509_rsa_sha1);
                    pdfSigner.SignExternalContainer(external, 8192);

                    //Digest from created new temporary PDF with empty space for signature.
                    FileStream oso = File.OpenRead(temp);
                    hash = DigestAlgorithms.Digest(oso, DigestAlgorithms.SHA256);

                    return(Convert.ToBase64String(hash));
                }
            }
        }
Exemplo n.º 13
0
            public byte[] Sign(Stream inputStream)
            {
                try
                {
                    PrivateKeySignature signature = new PrivateKeySignature(pk, "SHA256");
                    String hashAlgorithm          = signature.GetHashAlgorithm();

                    PdfPKCS7 sgn  = new PdfPKCS7(null, chain, hashAlgorithm, false);
                    byte[]   hash = DigestAlgorithms.Digest(inputStream, hashAlgorithm);
                    byte[]   sh   = sgn.GetAuthenticatedAttributeBytes(hash, PdfSigner.CryptoStandard.CMS,
                                                                       null, null);
                    byte[] extSignature = signature.Sign(sh);
                    sgn.SetExternalDigest(extSignature, null, signature.GetEncryptionAlgorithm());

                    return(sgn.GetEncodedPKCS7(hash, PdfSigner.CryptoStandard.CMS, null,
                                               null, null));
                }
                catch (IOException ioe)
                {
                    throw new Exception(ioe.Message);
                }
            }
Exemplo n.º 14
0
            public byte[] Sign(Stream data)
            {
                BasicOcspResp basicResp = (BasicOcspResp)ocspResp.GetResponseObject();

                byte[] oc = basicResp.GetEncoded();
                Collection <byte[]> ocspCollection = new Collection <byte[]>();

                ocspCollection.Add(oc);
                String   hashAlgorithm = "SHA256";
                PdfPKCS7 sgn           = new PdfPKCS7(null, chain, hashAlgorithm, false);

                byte[] hash = DigestAlgorithms.Digest(data, DigestAlgorithms.GetMessageDigest(hashAlgorithm));

                byte[] sh = sgn.GetAuthenticatedAttributeBytes(hash, PdfSigner.CryptoStandard.CADES, ocspCollection,
                                                               null);

                //create sha256 message digest
                using (SHA256 sha256 = SHA256.Create()) {
                    sh = sha256.ComputeHash(sh);
                }

                //create hex encoded sha256 message digest
                String hexencodedDigest = new BigInteger(1, sh).ToString(16).ToUpper();

                JObject signed = PDFSigningService.Sign(baseURL, id, hexencodedDigest, access);
                String  sig    = (String)signed.GetValue("signature");

                //decode hex signature
                byte[] dsg = Hex.Decode(sig);

                //include signature on PDF
                sgn.SetExternalDigest(dsg, null, "RSA");

                //create TimeStamp Client
                ITSAClient tsc = new DSSTSAClient(access);

                return(sgn.GetEncodedPKCS7(hash, PdfSigner.CryptoStandard.CADES, tsc, ocspCollection, null));
            }
Exemplo n.º 15
0
 /**
  * Actual constructor for ImgJBIG2 images.
  * @param    width   the width of the image
  * @param    height  the height of the image
  * @param    data    the raw image data
  * @param    globals JBIG2 globals
  */
 public ImgJBIG2(int width, int height, byte[] data, byte[] globals) : base((Uri)null)
 {
     type         = Element.JBIG2;
     originalType = ORIGINAL_JBIG2;
     scaledHeight = height;
     this.Top     = scaledHeight;
     scaledWidth  = width;
     this.Right   = scaledWidth;
     bpc          = 1;
     colorspace   = 1;
     rawData      = data;
     plainWidth   = this.Width;
     plainHeight  = this.Height;
     if (globals != null)
     {
         this.global = globals;
         try {
             this.globalHash = DigestAlgorithms.Digest("MD5", this.global);
         } catch {
             //ignore
         }
     }
 }
Exemplo n.º 16
0
        public ActionResult Start(SignatureStartModel model)
        {
            byte[] toSignHash, rangeDigest;
            PdfSignatureAppearance sigAppearance;
            MemoryStream           signedPdfStream;

            try {
                // Decode Certificate
                var certificate = new X509CertificateParser().ReadCertificate(model.CertContent);

                // Create a PdfReader with the PDF that will be signed
                var reader = new PdfReader(Storage.GetSampleDocContent() /* here we're using a sample document */);

                // Open the Signed PDF stream and create a pdf stamper.
                signedPdfStream = new MemoryStream();
                var stamper = PdfStamper.CreateSignature(reader, signedPdfStream, '\0');

                // Create the signature appearance
                sigAppearance = stamper.SignatureAppearance;
                // Add a crypto dictionary to the signature appearance
                sigAppearance.CryptoDictionary = new PdfSignature(PdfName.ADOBE_PPKLITE, PdfName.ADBE_PKCS7_DETACHED);
                // Inform the pkcs7 padded max size, which is 8kb
                var exc = new Dictionary <PdfName, int>();
                exc.Add(PdfName.CONTENTS, 8192 * 2 + 2);
                // Preclose the signature apperance, only closing it after the signature is computed
                // (see the Complete method below)
                sigAppearance.PreClose(exc);

                // Compute the digests to be signed
                var pkcs7 = new PdfPKCS7(null, new X509Certificate[] { certificate }, DigestAlgorithm, false);
                using (var data = sigAppearance.GetRangeStream()) {
                    // Compute the Range Digest
                    rangeDigest = DigestAlgorithms.Digest(data, DigestAlgorithm);
                    // Compute the toSignHash
                    var authAttributes = pkcs7.getAuthenticatedAttributeBytes(rangeDigest, null, null, CryptoStandard.CMS);
                    using (var ms = new MemoryStream(authAttributes)) {
                        toSignHash = DigestAlgorithms.Digest(ms, DigestAlgorithm);
                    }
                }
            } catch (Exception ex) {
                ModelState.AddModelError("", ex.ToString());
                return(View());
            }

            // On the next step (Complete action), we'll need once again some information:
            // - The thumbprint of the selected certificate
            // - The content of the selected certificate used to validate the signature in complete action.
            // - The "to-sign-hash"
            // - The digest algorithm
            // We'll store these values on TempData, which is a temporary dictionary shared between actions during a redirect.
            TempData["SignatureCompleteModel"] = new SignatureCompleteModel()
            {
                CertThumb       = model.CertThumb,
                CertContent     = model.CertContent,
                ToSignHash      = toSignHash,
                DigestAlgorithm = DigestAlgorithm
            };

            // During the "post-signing" step (see method Complete(SignatureCompleteModel) below), iTextSharp requires references
            // to the same objects rangeDigest, sigAppearance and signedPdfStream used during this step. This means we have to
            // use the Session object to store these objects.
            //
            // Please notice that this has very serious implications if you intend to develop a web application that can be executed
            // simulteneously on multiple servers. Tipically, in such cases, uses of the Session object to store data between requests
            // are replaced by storing the data on a database or filesystem shared between the servers. However, since the objects
            // sigAppearance and signedPdfStream are complex, non-serializable objects, such strategy would not apply!
            Session.Add("ITextSessionModel", new ITextSessionModel()
            {
                RangeDigest        = rangeDigest,
                SignatureApperance = sigAppearance,
                SignedPdfStream    = signedPdfStream
            });
            // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
            // !!! WARNING: USING SESSION TO STORE COMPLEX, NON-SERIALIZABLE OBJECTS !!!
            //
            // (please see comments on the beggining on this file for alternatives)

            return(RedirectToAction("Complete"));
        }
Exemplo n.º 17
0
 protected C1_02_DigestBC(String password, String algorithm)
 {
     messageDigest = DigestAlgorithms.GetMessageDigest(algorithm);
     digest        = DigestAlgorithms.Digest(new MemoryStream(Encoding.UTF8.GetBytes(password)), messageDigest);
 }
Exemplo n.º 18
0
 // This method checks if the digest of the password is equal
 // to the digest of the text line which is passed as argument
 public bool CheckPassword(String password)
 {
     return(digest.SequenceEqual(DigestAlgorithms
                                 .Digest(new MemoryStream(Encoding.UTF8.GetBytes(password)), messageDigest)));
 }
Exemplo n.º 19
0
        // gets keylength and revision and uses revison to choose the initial values for permissions
        virtual public void SetupAllKeys(byte[] userPassword, byte[] ownerPassword, int permissions)
        {
            if (ownerPassword == null || ownerPassword.Length == 0)
            {
                ownerPassword = DigestAlgorithms.Digest("MD5", CreateDocumentId());
            }
            md5.Reset();
            permissions     |= (int)((revision == STANDARD_ENCRYPTION_128 || revision == AES_128 || revision == AES_256) ? (uint)0xfffff0c0 : (uint)0xffffffc0);
            permissions     &= unchecked ((int)0xfffffffc);
            this.permissions = permissions;
            if (revision == AES_256)
            {
                if (userPassword == null)
                {
                    userPassword = new byte[0];
                }
                documentID = CreateDocumentId();
                byte[] uvs = IVGenerator.GetIV(8);
                byte[] uks = IVGenerator.GetIV(8);
                key = IVGenerator.GetIV(32);
                // Algorithm 3.8.1
                IDigest md = DigestUtilities.GetDigest("SHA-256");
                md.BlockUpdate(userPassword, 0, Math.Min(userPassword.Length, 127));
                md.BlockUpdate(uvs, 0, uvs.Length);
                userKey = new byte[48];
                md.DoFinal(userKey, 0);
                System.Array.Copy(uvs, 0, userKey, 32, 8);
                System.Array.Copy(uks, 0, userKey, 40, 8);
                // Algorithm 3.8.2
                md.BlockUpdate(userPassword, 0, Math.Min(userPassword.Length, 127));
                md.BlockUpdate(uks, 0, uks.Length);
                byte[] tempDigest = new byte[32];
                md.DoFinal(tempDigest, 0);
                AESCipherCBCnoPad ac = new AESCipherCBCnoPad(true, tempDigest);
                ueKey = ac.ProcessBlock(key, 0, key.Length);
                // Algorithm 3.9.1
                byte[] ovs = IVGenerator.GetIV(8);
                byte[] oks = IVGenerator.GetIV(8);
                md.BlockUpdate(ownerPassword, 0, Math.Min(ownerPassword.Length, 127));
                md.BlockUpdate(ovs, 0, ovs.Length);
                md.BlockUpdate(userKey, 0, userKey.Length);
                ownerKey = new byte[48];
                md.DoFinal(ownerKey, 0);
                System.Array.Copy(ovs, 0, ownerKey, 32, 8);
                System.Array.Copy(oks, 0, ownerKey, 40, 8);
                // Algorithm 3.9.2
                md.BlockUpdate(ownerPassword, 0, Math.Min(ownerPassword.Length, 127));
                md.BlockUpdate(oks, 0, oks.Length);
                md.BlockUpdate(userKey, 0, userKey.Length);
                md.DoFinal(tempDigest, 0);
                ac    = new AESCipherCBCnoPad(true, tempDigest);
                oeKey = ac.ProcessBlock(key, 0, key.Length);
                // Algorithm 3.10
                byte[] permsp = IVGenerator.GetIV(16);
                permsp[0]  = (byte)permissions;
                permsp[1]  = (byte)(permissions >> 8);
                permsp[2]  = (byte)(permissions >> 16);
                permsp[3]  = (byte)(permissions >> 24);
                permsp[4]  = (byte)(255);
                permsp[5]  = (byte)(255);
                permsp[6]  = (byte)(255);
                permsp[7]  = (byte)(255);
                permsp[8]  = encryptMetadata ? (byte)'T' : (byte)'F';
                permsp[9]  = (byte)'a';
                permsp[10] = (byte)'d';
                permsp[11] = (byte)'b';
                ac         = new AESCipherCBCnoPad(true, key);
                perms      = ac.ProcessBlock(permsp, 0, permsp.Length);
            }
            else
            {
                //PDF refrence 3.5.2 Standard Security Handler, Algorithum 3.3-1
                //If there is no owner password, use the user password instead.
                byte[] userPad  = PadPassword(userPassword);
                byte[] ownerPad = PadPassword(ownerPassword);

                this.ownerKey = ComputeOwnerKey(userPad, ownerPad);
                documentID    = CreateDocumentId();
                SetupByUserPad(this.documentID, userPad, this.ownerKey, permissions);
            }
        }
Exemplo n.º 20
0
            private void SerObject(PdfObject obj, int level, ByteBuffer bb, Dictionary <RefKey, int> serialized)
            {
                if (level <= 0)
                {
                    return;
                }
                if (obj == null)
                {
                    bb.Append("$Lnull");
                    return;
                }

                PdfIndirectReference refe    = null;
                ByteBuffer           savedBb = null;

                if (obj.IsIndirect())
                {
                    refe = (PdfIndirectReference)obj;
                    RefKey key = new RefKey(refe);
                    if (serialized.ContainsKey(key))
                    {
                        bb.Append(serialized[key]);
                        return;
                    }
                    else
                    {
                        savedBb = bb;
                        bb      = new ByteBuffer();
                    }
                }
                obj = PdfReader.GetPdfObject(obj);
                if (obj.IsStream())
                {
                    bb.Append("$B");
                    SerDic((PdfDictionary)obj, level - 1, bb, serialized);
                    if (level > 0)
                    {
                        bb.Append(DigestAlgorithms.Digest("MD5", PdfReader.GetStreamBytesRaw((PRStream)obj)));
                    }
                }
                else if (obj.IsDictionary())
                {
                    SerDic((PdfDictionary)obj, level - 1, bb, serialized);
                }
                else if (obj.IsArray())
                {
                    SerArray((PdfArray)obj, level - 1, bb, serialized);
                }
                else if (obj.IsString())
                {
                    bb.Append("$S").Append(obj.ToString());
                }
                else if (obj.IsName())
                {
                    bb.Append("$N").Append(obj.ToString());
                }
                else
                {
                    bb.Append("$L").Append(obj.ToString());
                }

                if (savedBb != null)
                {
                    RefKey key = new RefKey(refe);
                    if (!serialized.ContainsKey(key))
                    {
                        serialized[key] = CalculateHash(bb.Buffer);
                    }
                    savedBb.Append(bb);
                }
            }