protected internal virtual byte[] GenerateOwnerPasswordIfNullOrEmpty(byte[] ownerPassword)
 {
     if (ownerPassword == null || ownerPassword.Length == 0)
     {
         ownerPassword = md5.Digest(PdfEncryption.GenerateNewDocumentId());
     }
     return(ownerPassword);
 }
Ejemplo n.º 2
0
        void CreateEncrypt(PdfElement elem)
        {
            var cf = elem.Get <PdfElement>("CF");

            if (cf != null)
            {
                var stdCf = cf.Get <PdfElement>("StdCF");
                if (stdCf != null)
                {
                }
            }
            var pValue = elem.Get <PdfInteger>("P").Value;
            var vValue = elem.Get <PdfInteger>("V").Value;
            var rValue = elem.Get <PdfInteger>("R").Value;
            var oValue = elem.Get <PdfString>("O").ToISOBytes();
            var uValue = elem.Get <PdfString>("U").ToISOBytes();
            var filter = elem.Get <PdfName>("Filter")?.Name;

            EncryptAlg cryptoMode = EncryptAlg.STANDARD_ENCRYPTION_128;

            switch (rValue)
            {
            case 4:
                if (vValue != 4)
                {
                    throw new PdfException($"Invalid encrypt. V={vValue}, P={vValue}");
                }
                var cfObj    = elem.Get <PdfDictionary>("CF");
                var stdCfObj = cfObj.Get <PdfDictionary>("StdCF");
                if (stdCfObj != null)
                {
                    if (stdCfObj.Get <PdfName>("CFM")?.Name == "V2")
                    {
                        cryptoMode = EncryptAlg.STANDARD_ENCRYPTION_128;
                    }
                }
                break;

            default:
                throw new NotImplementedException($"Decrypt value {rValue}");
            }

            _decryptor = new PdfEncryption();
            _decryptor.SetCryptoMode(cryptoMode, 0);

            if (filter == "Standard")
            {
                if (rValue != 5)
                {
                    _decryptor.SetupByOwnerPassword(_documentId, uValue, oValue, pValue);
                    Int32 checkLen = (rValue == 3 || rValue == 4) ? 16 : 32;
                    if (!EqualsArray(uValue, _decryptor.UserKey, checkLen))
                    {
                        _decryptor.SetupByUserPassword(_documentId, oValue, pValue);
                    }
                }
            }
        }
Ejemplo n.º 3
0
        public virtual void Decrypt(PdfEncryption decryptor, Int32 key, Int32 revision)
        {
            PdfStream stream = Stream;

            if (stream == null)
            {
                throw new PdfException("There is no stream for Decrypt");
            }
            decryptor.SetHashKey(key, revision);
            stream.Decrypt(decryptor);
            Decode();
        }
Ejemplo n.º 4
0
        /**
         * Checks if the timestamp refers to this document.
         * @throws java.security.NoSuchAlgorithmException on error
         * @return true if it checks false otherwise
         * @since   2.1.6
         */
        public bool VerifyTimestampImprint()
        {
            if (timeStampToken == null)
            {
                return(false);
            }
            TimeStampTokenInfo info    = timeStampToken.TimeStampInfo;
            MessageImprint     imprint = info.TstInfo.MessageImprint;
            String             algOID  = info.MessageImprintAlgOid;

            byte[] md        = PdfEncryption.DigestComputeHash(algOID, digest);
            byte[] imphashed = imprint.GetHashedMessage();
            bool   res       = Arrays.AreEqual(md, imphashed);

            return(res);
        }
Ejemplo n.º 5
0
        public static Org.BouncyCastle.Asn1.Asn1EncodableVector GetTimestamp(byte[] signature, string url, string user, string pass)
        {
            byte[] tsImprint = PdfEncryption.DigestComputeHash("SHA256", signature);

            int        size = 6500;
            ITSAClient tsc  = new TSAClientBouncyCastle(url, user, pass, size, "SHA256");
            String     ID_TIME_STAMP_TOKEN = "1.2.840.113549.1.9.16.2.14";         // RFC 3161 id-aa-timeStampToken

            Asn1InputStream tempstream = new Asn1InputStream(new MemoryStream(tsc.GetTimeStampToken(tsImprint)));

            Asn1EncodableVector unauthAttributes = new Asn1EncodableVector();

            Asn1EncodableVector v = new Asn1EncodableVector();

            v.Add(new DerObjectIdentifier(ID_TIME_STAMP_TOKEN));             // id-aa-timeStampToken
            Asn1Sequence seq = (Asn1Sequence)tempstream.ReadObject();

            v.Add(new DerSet(seq));

            unauthAttributes.Add(new DerSequence(v));
            return(unauthAttributes);
        }
Ejemplo n.º 6
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 = PdfEncryption.DigestComputeHash("MD5", this.global);
         } catch {
             //ignore
         }
     }
 }
Ejemplo n.º 7
0
        internal static OcspReq GenerateOcspRequestWithNonce(CertificateID id)
        {
            OcspReqGenerator gen = new OcspReqGenerator();

            gen.AddRequest(id);

            // create details for nonce extension
            IDictionary extensions = new Hashtable();

            extensions[OcspObjectIdentifiers.PkixOcspNonce] = new X509Extension(false, new DerOctetString(new DerOctetString(PdfEncryption.GenerateNewDocumentId()).GetEncoded()));

            gen.SetRequestExtensions(new X509Extensions(extensions));
            return(gen.Generate());
        }
Ejemplo n.º 8
0
        /**
         * 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
            IDictionary extensions = new Hashtable();

            extensions[OcspObjectIdentifiers.PkixOcspNonce] = new X509Extension(false, new DerOctetString(new DerOctetString(PdfEncryption.CreateDocumentId()).GetEncoded()));

            gen.SetRequestExtensions(new X509Extensions(extensions));

            return(gen.Generate());
        }
Ejemplo n.º 9
0
 private static byte[] HashBytesSha1(byte[] b)
 {
     return(PdfEncryption.DigestComputeHash("SHA1", b));
 }
Ejemplo n.º 10
0
        public virtual void Decrypt(PdfEncryption decryptor, String key)
        {
            var sp = key.Split(' ');

            Decrypt(decryptor, Int32.Parse(sp[0]), Int32.Parse(sp[1]));
        }
Ejemplo n.º 11
0
        /**
         * This method provides that encoding and the parameters must be
         * exactly the same as in {@link #getEncodedPKCS7(byte[],Calendar)}.
         *
         * @param secondDigest the content digest
         * @param signingTime the signing time
         * @return the byte array representation of the authenticatedAttributes ready to be signed
         */
        private DerSet GetAuthenticatedAttributeSet(byte[] secondDigest, DateTime signingTime, byte[] ocsp, ICollection <byte[]> crlBytes, bool cades)
        {
            Asn1EncodableVector attribute = new Asn1EncodableVector();
            Asn1EncodableVector v         = new Asn1EncodableVector();

            v.Add(new DerObjectIdentifier(SecurityIDs.ID_CONTENT_TYPE));
            v.Add(new DerSet(new DerObjectIdentifier(SecurityIDs.ID_PKCS7_DATA)));
            attribute.Add(new DerSequence(v));
            v = new Asn1EncodableVector();
            v.Add(new DerObjectIdentifier(SecurityIDs.ID_SIGNING_TIME));
            v.Add(new DerSet(new DerUtcTime(signingTime)));
            attribute.Add(new DerSequence(v));
            v = new Asn1EncodableVector();
            v.Add(new DerObjectIdentifier(SecurityIDs.ID_MESSAGE_DIGEST));
            v.Add(new DerSet(new DerOctetString(secondDigest)));
            attribute.Add(new DerSequence(v));

            bool haveCrl = false;

            if (crlBytes != null)
            {
                foreach (byte[] bCrl in crlBytes)
                {
                    if (bCrl != null)
                    {
                        haveCrl = true;
                        break;
                    }
                }
            }
            if (ocsp != null || haveCrl)
            {
                v = new Asn1EncodableVector();
                v.Add(new DerObjectIdentifier(SecurityIDs.ID_ADBE_REVOCATION));

                Asn1EncodableVector revocationV = new Asn1EncodableVector();

                if (haveCrl)
                {
                    Asn1EncodableVector v2 = new Asn1EncodableVector();
                    foreach (byte[] bCrl in crlBytes)
                    {
                        if (bCrl == null)
                        {
                            continue;
                        }
                        Asn1InputStream t = new Asn1InputStream(bCrl);
                        v2.Add(t.ReadObject());
                    }
                    revocationV.Add(new DerTaggedObject(true, 0, new DerSequence(v2)));
                }

                if (ocsp != null)
                {
                    DerOctetString      doctet = new DerOctetString(ocsp);
                    Asn1EncodableVector vo1    = new Asn1EncodableVector();
                    Asn1EncodableVector v2     = new Asn1EncodableVector();
                    v2.Add(OcspObjectIdentifiers.PkixOcspBasic);
                    v2.Add(doctet);
                    DerEnumerated       den = new DerEnumerated(0);
                    Asn1EncodableVector v3  = new Asn1EncodableVector();
                    v3.Add(den);
                    v3.Add(new DerTaggedObject(true, 0, new DerSequence(v2)));
                    vo1.Add(new DerSequence(v3));
                    revocationV.Add(new DerTaggedObject(true, 1, new DerSequence(vo1)));
                }

                v.Add(new DerSet(new DerSequence(revocationV)));
                attribute.Add(new DerSequence(v));
            }
            if (cades)
            {
                v = new Asn1EncodableVector();
                v.Add(new DerObjectIdentifier(SecurityIDs.ID_AA_SIGNING_CERTIFICATE_V2));

                Asn1EncodableVector aaV2   = new Asn1EncodableVector();
                AlgorithmIdentifier algoId = new AlgorithmIdentifier(new DerObjectIdentifier(digestAlgorithmOid), null);
                aaV2.Add(algoId);
                byte[] dig = PdfEncryption.DigestComputeHash(GetHashAlgorithm(), signCert.GetEncoded());
                aaV2.Add(new DerOctetString(dig));

                v.Add(new DerSet(new DerSequence(new DerSequence(new DerSequence(aaV2)))));
                attribute.Add(new DerSequence(v));
            }

            return(new DerSet(attribute));
        }
Ejemplo n.º 12
0
        /**
         * Gets the bytes for the PKCS7SignedData object. Optionally the authenticatedAttributes
         * in the signerInfo can also be set, OR a time-stamp-authority client
         * may be provided.
         * @param secondDigest the digest in the authenticatedAttributes
         * @param signingTime the signing time in the authenticatedAttributes
         * @param tsaClient TSAClient - null or an optional time stamp authority client
         * @return byte[] the bytes for the PKCS7SignedData object
         * @since   2.1.6
         */
        public byte[] GetEncodedPKCS7(byte[] secondDigest, DateTime signingTime, ITSAClient tsaClient, byte[] ocsp, ICollection <byte[]> crlBytes, bool cades)
        {
            if (externalDigest != null)
            {
                digest = externalDigest;
                if (RSAdata != null)
                {
                    RSAdata = externalRSAdata;
                }
            }
            else if (externalRSAdata != null && RSAdata != null)
            {
                RSAdata = externalRSAdata;
                sig.BlockUpdate(RSAdata, 0, RSAdata.Length);
                digest = sig.GenerateSignature();
            }
            else
            {
                if (RSAdata != null)
                {
                    RSAdata = new byte[messageDigest.GetDigestSize()];
                    messageDigest.DoFinal(RSAdata, 0);
                    sig.BlockUpdate(RSAdata, 0, RSAdata.Length);
                }
                digest = sig.GenerateSignature();
            }

            // Create the set of Hash algorithms
            Asn1EncodableVector digestAlgorithms = new Asn1EncodableVector();

            foreach (string dal in digestalgos.Keys)
            {
                Asn1EncodableVector algos = new Asn1EncodableVector();
                algos.Add(new DerObjectIdentifier(dal));
                algos.Add(DerNull.Instance);
                digestAlgorithms.Add(new DerSequence(algos));
            }

            // Create the contentInfo.
            Asn1EncodableVector v = new Asn1EncodableVector();

            v.Add(new DerObjectIdentifier(SecurityIDs.ID_PKCS7_DATA));
            if (RSAdata != null)
            {
                v.Add(new DerTaggedObject(0, new DerOctetString(RSAdata)));
            }
            DerSequence contentinfo = new DerSequence(v);

            // Get all the certificates
            //
            v = new Asn1EncodableVector();
            foreach (X509Certificate xcert in certs)
            {
                Asn1InputStream tempstream = new Asn1InputStream(new MemoryStream(xcert.GetEncoded()));
                v.Add(tempstream.ReadObject());
            }

            DerSet dercertificates = new DerSet(v);

            // Create signerinfo structure.
            //
            Asn1EncodableVector signerinfo = new Asn1EncodableVector();

            // Add the signerInfo version
            //
            signerinfo.Add(new DerInteger(signerversion));

            v = new Asn1EncodableVector();
            v.Add(CertificateInfo.GetIssuer(signCert.GetTbsCertificate()));
            v.Add(new DerInteger(signCert.SerialNumber));
            signerinfo.Add(new DerSequence(v));

            // Add the digestAlgorithm
            v = new Asn1EncodableVector();
            v.Add(new DerObjectIdentifier(digestAlgorithmOid));
            v.Add(DerNull.Instance);
            signerinfo.Add(new DerSequence(v));

            // add the authenticated attribute if present
            if (secondDigest != null /*&& signingTime != null*/)
            {
                signerinfo.Add(new DerTaggedObject(false, 0, GetAuthenticatedAttributeSet(secondDigest, signingTime, ocsp, crlBytes, cades)));
            }
            // Add the digestEncryptionAlgorithm
            v = new Asn1EncodableVector();
            v.Add(new DerObjectIdentifier(digestEncryptionAlgorithmOid));
            v.Add(DerNull.Instance);
            signerinfo.Add(new DerSequence(v));

            // Add the digest
            signerinfo.Add(new DerOctetString(digest));

            // When requested, go get and add the timestamp. May throw an exception.
            // Added by Martin Brunecky, 07/12/2007 folowing Aiken Sam, 2006-11-15
            // Sam found Adobe expects time-stamped SHA1-1 of the encrypted digest
            if (tsaClient != null)
            {
                byte[] tsImprint = PdfEncryption.DigestComputeHash(tsaClient.GetDigestAlgorithm(), digest);
                byte[] tsToken   = tsaClient.GetTimeStampToken(tsImprint);
                if (tsToken != null)
                {
                    Asn1EncodableVector unauthAttributes = BuildUnauthenticatedAttributes(tsToken);
                    if (unauthAttributes != null)
                    {
                        signerinfo.Add(new DerTaggedObject(false, 1, new DerSet(unauthAttributes)));
                    }
                }
            }

            // Finally build the body out of all the components above
            Asn1EncodableVector body = new Asn1EncodableVector();

            body.Add(new DerInteger(version));
            body.Add(new DerSet(digestAlgorithms));
            body.Add(contentinfo);
            body.Add(new DerTaggedObject(false, 0, dercertificates));

            // Only allow one signerInfo
            body.Add(new DerSet(new DerSequence(signerinfo)));

            // Now we have the body, wrap it in it's PKCS7Signed shell
            // and return it
            //
            Asn1EncodableVector whole = new Asn1EncodableVector();

            whole.Add(new DerObjectIdentifier(SecurityIDs.ID_PKCS7_SIGNED_DATA));
            whole.Add(new DerTaggedObject(0, new DerSequence(body)));

            MemoryStream bOut = new MemoryStream();

            Asn1OutputStream dout = new Asn1OutputStream(bOut);

            dout.WriteObject(new DerSequence(whole));
            dout.Close();

            return(bOut.ToArray());
        }
Ejemplo n.º 13
0
        private static OcspReq GenerateOCSPRequest(X509Certificate signerCert,
                                                   X509Certificate checkerCert,
                                                   X509Certificate issuerCert,
                                                   AsymmetricKeyParameter checkerKey)
        {
            // Generate the id for the certificate we are looking for
            CertificateID id = new CertificateID(CertificateID.HashSha1, issuerCert, signerCert.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));

            X509Certificate [] chain = new X509Certificate[2];
            chain[0] = checkerCert;
            chain[1] = signerCert;

            gen.SetRequestorName(checkerCert.SubjectDN);

            return(gen.Generate(checkerCert.SigAlgOid, checkerKey, chain));
        }
Ejemplo n.º 14
0
        public void Decrypt(PdfEncryption decryptor)
        {
            var result = decryptor.DecryptByteArray(Bytes);

            Bytes = result;
        }