Beispiel #1
0
        public static string getServerHash(string serverID, byte[] PublicKey, byte[] SecretKey)
        {
            byte[] serverid_raw = Encoding.GetEncoding("iso-8859-1").GetBytes(serverID);
            byte[] serverhash;
            using (SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider())
            {
                sha1.TransformBlock(serverid_raw, 0, serverid_raw.Length, serverid_raw, 0);
                sha1.TransformBlock(PublicKey, 0, PublicKey.Length, PublicKey, 0);
                sha1.TransformBlock(SecretKey, 0, SecretKey.Length, SecretKey, 0);
                sha1.TransformFinalBlock(new byte[] { }, 0, 0);
                serverhash = sha1.Hash;
            }
            bool negative = (serverhash[0] & 0x80) == 0x80;

            if (negative)
            {
                serverhash = TwosCompliment(serverhash);
            }
            string digest = GetHexString(serverhash).TrimStart('0');

            if (negative)
            {
                digest = "-" + digest;
            }
            return(digest);
        }
Beispiel #2
0
    static UInt64 CalculateHashForType(Type type)
    {
        using (SHA1 sha = new SHA1CryptoServiceProvider()) {
            foreach (var f in type.GetFields())
            {
                byte[] fieldNameBytes     = System.Text.UTF8Encoding.UTF8.GetBytes(f.Name);
                byte[] fieldTypeNameBytes = System.Text.UTF8Encoding.UTF8.GetBytes(f.FieldType.FullName);

                sha.TransformBlock(fieldNameBytes, 0, fieldNameBytes.Length, fieldNameBytes, 0);
                sha.TransformBlock(fieldTypeNameBytes, 0, fieldTypeNameBytes.Length, fieldTypeNameBytes, 0);
            }

            foreach (var p in type.GetProperties())
            {
                byte[] fieldNameBytes     = System.Text.UTF8Encoding.UTF8.GetBytes(p.Name);
                byte[] fieldTypeNameBytes = System.Text.UTF8Encoding.UTF8.GetBytes(p.PropertyType.FullName);

                sha.TransformBlock(fieldNameBytes, 0, fieldNameBytes.Length, fieldNameBytes, 0);
                sha.TransformBlock(fieldTypeNameBytes, 0, fieldTypeNameBytes.Length, fieldTypeNameBytes, 0);
            }


            byte[] typeNameBytes = System.Text.UTF8Encoding.UTF8.GetBytes(type.FullName);
            sha.TransformFinalBlock(typeNameBytes, 0, typeNameBytes.Length);
            byte[] hash = sha.Hash;

            for (uint i = 8; i < hash.Length; ++i)
            {
                hash[i & 7] %= hash[i];
            }

            return(BitConverter.ToUInt64(hash, 0));
        }
    }
Beispiel #3
0
        public static byte[] ComputeHash(byte[] data)
        {
            SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider();

            sha1.TransformBlock(_salt, 0, _salt.Length, _salt, 0);
            sha1.TransformFinalBlock(data, 0, data.Length);
            return(sha1.Hash);
        }
Beispiel #4
0
        public Navicat11Cipher(string CustomUserKey)
        {
            byte[] UserKey = Encoding.UTF8.GetBytes(CustomUserKey);
            var    sha1    = new SHA1CryptoServiceProvider();

            byte[] UserKeyHash = sha1.TransformFinalBlock(UserKey, 0, 8);
            blowfishCipher = new Blowfish(UserKeyHash);
        }
Beispiel #5
0
        public Navicat11Cipher()
        {
            byte[] UserKey = Encoding.UTF8.GetBytes("3DC5CA39");
            var    sha1    = new SHA1CryptoServiceProvider();

            sha1.TransformFinalBlock(UserKey, 0, UserKey.Length);
            blowfishCipher = new Blowfish(sha1.Hash);
        }
 byte[] GenKey(byte[] key)
 {
     for (int x = 0; x < 10000; x++)
     {
         SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider();
         sha1.TransformBlock(key, 0, key.Length, key, 0);
         key = sha1.TransformFinalBlock(ASCIIEncoding.ASCII.GetBytes("fuckoff"), 0, 7);
         sha1.Clear();
     }
     return(key);
 }
        /// <summary>
        /// Generate a SHA-1 hash using several byte arrays
        /// </summary>
        /// <param name="tohash">array of byte arrays to hash</param>
        /// <returns>Returns the hashed data</returns>

        private static byte[] digest(byte[][] tohash)
        {
            SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider();

            for (int i = 0; i < tohash.Length; i++)
            {
                sha1.TransformBlock(tohash[i], 0, tohash[i].Length, tohash[i], 0);
            }
            sha1.TransformFinalBlock(new byte[] { }, 0, 0);
            return(sha1.Hash);
        }
        private static byte[] PuTTYPassphraseToKey(string passphrase)
        {
            const int HASH_SIZE            = 20;
            SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider();

            byte[] pp = Encoding.UTF8.GetBytes(passphrase);

            byte[] buf = new byte[HASH_SIZE * 2];

            sha1.TransformBlock(new byte[] { 0, 0, 0, 0 }, 0, 4, null, 0);
            sha1.TransformFinalBlock(pp, 0, pp.Length);
            Buffer.BlockCopy(sha1.Hash, 0, buf, 0, HASH_SIZE);
            sha1.Initialize();
            sha1.TransformBlock(new byte[] { 0, 0, 0, 1 }, 0, 4, null, 0);
            sha1.TransformFinalBlock(pp, 0, pp.Length);
            Buffer.BlockCopy(sha1.Hash, 0, buf, HASH_SIZE, HASH_SIZE);
            sha1.Clear();

            byte[] key = new byte[32];
            Buffer.BlockCopy(buf, 0, key, 0, key.Length);
            return(key);
        }
        public static void UInt8(SHA1CryptoServiceProvider sha, uint word, bool isFinal = false)
        {
            gUInt64Buffer[0] = (byte)(word >> 0);

            if (isFinal)
            {
                sha.TransformFinalBlock(gUInt64Buffer, 0, sizeof(byte));
            }
            else
            {
                sha.TransformBlock(gUInt64Buffer, 0, sizeof(byte), null, 0);
            }
        }
Beispiel #10
0
        private static byte[] GetSha1Digest(byte[][] hash)
        {
            //叠叠乐?把所有byte叠一起然后算出hash
            SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider();

            for (int i = 0; i < hash.Length; i++)
            {
                sha1.TransformBlock(hash[i], 0, hash[i].Length, hash[i], 0);
            }
            //看不懂这行是什么意思
            sha1.TransformFinalBlock(new byte[] { }, 0, 0);
            return(sha1.Hash);
        }
Beispiel #11
0
        private bool Verify(int version, string privateMac, string privateHash,
                            string passphrase, string keyTypeName, string encryptionName, string comment, byte[] publicBlob, byte[] privateBlob)
        {
            byte[] macData;
            using (MemoryStream macDataBuff = new MemoryStream())
            {
                if (version == 1)
                {
                    WriteMacData(macDataBuff, privateBlob);
                }
                else
                {
                    WriteMacData(macDataBuff, keyTypeName);
                    WriteMacData(macDataBuff, encryptionName);
                    WriteMacData(macDataBuff, comment);
                    WriteMacData(macDataBuff, publicBlob);
                    WriteMacData(macDataBuff, privateBlob);
                }
                macDataBuff.Close();
                macData = macDataBuff.ToArray();
            }

            if (privateMac != null)
            {
                SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider();
                byte[] a = Encoding.ASCII.GetBytes("putty-private-key-file-mac-key");
                sha1.TransformBlock(a, 0, a.Length, null, 0);
                byte[] b = Encoding.UTF8.GetBytes(passphrase);
                sha1.TransformFinalBlock(b, 0, b.Length);
                byte[] key = sha1.Hash;
                sha1.Clear();

                System.Security.Cryptography.HMACSHA1 hmacsha1 = new System.Security.Cryptography.HMACSHA1(key);
                byte[] hash = hmacsha1.ComputeHash(macData);
                hmacsha1.Clear();
                string mac = BinToHex(hash);
                return(mac == privateMac);
            }
            else if (privateHash != null)
            {
                SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider();
                byte[] hash = sha1.ComputeHash(macData);
                sha1.Clear();
                string mac = BinToHex(hash);
                return(mac == privateHash);
            }
            else
            {
                return(true);
            }
        }
        private byte[] GetMsgHashed(Stream stream)
        {
            using (HashAlgorithm sha = new SHA1CryptoServiceProvider())
            {
                int    read = 0;
                byte[] buff = new byte[8192];
                while ((read = stream.Read(buff, 0, 8192)) > 0)
                {
                    sha.TransformBlock(buff, 0, read, buff, 0);
                }
                sha.TransformFinalBlock(buff, 0, 0);

                return(sha.Hash);
            }
        }
Beispiel #13
0
        //
        // Summary:
        //     When overridden in a derived class, finalizes the hash computation after
        //     the last data is processed by the cryptographic stream object.
        //
        // Returns:
        //     The computed hash code.
        protected override byte[] HashFinal()
        {
            byte[] hash = new byte[36];
            _md5.TransformFinalBlock(hash, 0, 0);
            _sha1.TransformFinalBlock(hash, 0, 0);
            var md5Hash  = _md5.Hash;
            var sha1Hash = _sha1.Hash;

            Buffer.BlockCopy(md5Hash, 0, hash, 0, 16);
            Buffer.BlockCopy(sha1Hash, 0, hash, 16, 20);
            Array.Clear(md5Hash, 0, 16);
            Array.Clear(sha1Hash, 0, 20);
            HashValue = hash;
            return(hash);
        }
Beispiel #14
0
 public static byte[] ComputeHashToBA(byte[] byteArr, bool useSalt = false)
 {
     if (useSalt)
     {
         SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider();
         sha1.TransformBlock(_salt, 0, _salt.Length, _salt, 0);
         sha1.TransformFinalBlock(byteArr, 0, byteArr.Length);
         return(sha1.Hash);
     }
     else
     {
         SHA1 sha1 = new SHA1CryptoServiceProvider();
         return(sha1.ComputeHash(byteArr));
     }
 }
Beispiel #15
0
        private byte[] GetMsgHashed(PdfSignatureAppearance sap)
        {
            HashAlgorithm sha = new SHA1CryptoServiceProvider();

            Stream s    = sap.RangeStream;
            int    read = 0;

            byte[] buff = new byte[8192];
            while ((read = s.Read(buff, 0, 8192)) > 0)
            {
                sha.TransformBlock(buff, 0, read, buff, 0);
            }
            sha.TransformFinalBlock(buff, 0, 0);

            return(sha.Hash);
        }
Beispiel #16
0
        public static void Test1(byte[] data)
        {
            var sha1 = new SHA1CryptoServiceProvider();

            for (int x = 0; x < 10; x++)
            {
                sha1.Initialize();
                for (int i = 0; i < 10; i++)
                {
                    sha1.TransformBlock(data, i * 10, 10, data, i * 10);
                }

                sha1.TransformFinalBlock(data, 100, 0);
                Console.WriteLine(BytesToStr(sha1.Hash));
            }
        }
Beispiel #17
0
        public static void UInt64(SHA1CryptoServiceProvider sha, ulong word, bool isFinal = false)
        {
            Bitwise.ByteSwap.ReplaceBytes(gUInt64Buffer, 0, word);
            if (BitConverter.IsLittleEndian)
            {
                Bitwise.ByteSwap.SwapUInt64(gUInt64Buffer, 0);
            }

            if (isFinal)
            {
                sha.TransformFinalBlock(gUInt64Buffer, 0, sizeof(ulong));
            }
            else
            {
                sha.TransformBlock(gUInt64Buffer, 0, sizeof(ulong), null, 0);
            }
        }
        /// <summary>Encrypts password using IBM's flavor of SHA1 algorithm</summary>
        /// <param name="userName">User name in ASCII</param>
        /// <param name="password">Password in ASCII</param>
        /// <param name="serverSeed">Server's seed</param>
        /// <param name="clientSeed">Client's seed</param>
        /// <returns>Encrypted password as EBCDIC byte stream</returns>
        public static byte[] EncryptPasswordSHA1(string userName, string password, ulong serverSeed, ulong clientSeed)
        {
            SHA1 sha = new SHA1CryptoServiceProvider();

            byte[] token                = sha.ComputeHash(Encoding.BigEndianUnicode.GetBytes(userName.ToUpper().PadRight(10) + password));
            byte[] serverSeedBytes      = Converters.UInt64ToBigEndian(serverSeed);
            byte[] clientSeedBytes      = Converters.UInt64ToBigEndian(clientSeed);
            byte[] userNameUnicodeBytes = Encoding.BigEndianUnicode.GetBytes(userName.ToUpper().PadRight(10));
            byte[] sequenceBytes        = Converters.UInt64ToBigEndian(1);

            sha = new SHA1CryptoServiceProvider();
            sha.TransformBlock(token, 0, token.Length, token, 0);
            sha.TransformBlock(serverSeedBytes, 0, serverSeedBytes.Length, serverSeedBytes, 0);
            sha.TransformBlock(clientSeedBytes, 0, clientSeedBytes.Length, clientSeedBytes, 0);
            sha.TransformBlock(userNameUnicodeBytes, 0, userNameUnicodeBytes.Length, userNameUnicodeBytes, 0);
            sha.TransformFinalBlock(sequenceBytes, 0, sequenceBytes.Length);
            return(sha.Hash);
        }
Beispiel #19
0
        public static void Stream(SHA1CryptoServiceProvider sha
                                  , System.IO.Stream inputStream
                                  , long inputOffset
                                  , long inputLength
                                  , bool isFinal = false)
        {
            const int k_read_block_size = 4096;

            Contract.Requires(inputStream != null);
            Contract.Requires(inputStream.CanSeek && inputStream.CanRead);
            Contract.Requires(inputOffset >= 0);
            Contract.Requires(inputLength > 0);

            var scratch_buffer = new byte[k_read_block_size];

            using (new IO.StreamPositionContext(inputStream))
            {
                inputStream.Seek(inputOffset, System.IO.SeekOrigin.Begin);

                for (long input_bytes_read = 0; input_bytes_read < inputLength;)
                {
                    long bytes_remaining   = inputLength - input_bytes_read;
                    int  read_block_length = System.Math.Min((int)bytes_remaining, scratch_buffer.Length);

                    Array.Clear(scratch_buffer, 0, scratch_buffer.Length);
                    for (int actual_bytes_read = 0; actual_bytes_read < read_block_length;)
                    {
                        int sub_block_offset = actual_bytes_read;
                        int sub_block_length = read_block_length - sub_block_offset;
                        actual_bytes_read += inputStream.Read(scratch_buffer, sub_block_offset, sub_block_length);
                    }

                    sha.TransformBlock(
                        scratch_buffer, 0, read_block_length,
                        null, 0);
                    input_bytes_read += read_block_length;
                }
            }

            if (isFinal)
            {
                sha.TransformFinalBlock(scratch_buffer, 0, 0);
            }
        }
        public void ComputeHashes()
        {
            try
            {
                SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider();

                this.CRC32 = 0;

                long totalSamples     = this.audioSource.Length;
                long processedSamples = 0;

                AudioBuffer buffer = new AudioBuffer(this.audioSource.PCM, 44100);
                while (this.audioSource.Read(buffer, 44100) > 0)
                {
                    byte[] bufferBytes = buffer.Bytes;
                    if (this.audioSource.Position == this.audioSource.Length)
                    {
                        sha1.TransformFinalBlock(bufferBytes, 0, buffer.ByteLength);
                    }
                    else
                    {
                        sha1.TransformBlock(bufferBytes, 0, buffer.ByteLength, null, 0);
                    }
                    this.CRC32 = Crc32.ComputeChecksum(this.CRC32, buffer.Bytes, 0, buffer.ByteLength);

                    processedSamples += buffer.Length;

                    ProgressChangedEventArgs eventArgs = new ProgressChangedEventArgs((double)processedSamples / totalSamples);
                    this.OnProgressChanged(eventArgs);
                    if (eventArgs.Cancel)
                    {
                        return;
                    }
                }

                this.SHA1 = sha1.Hash;
            }
            finally
            {
                this.audioSource.Close();
            }
        }
Beispiel #21
0
        private static void SetSigCryptoFromX509(PdfSignatureAppearance sigAppearance, X509Certificate2 card, X509Certificate[] chain)
        {
            sigAppearance.SetCrypto(null, chain, null, PdfSignatureAppearance.WINCER_SIGNED);
            var dic = new PdfSignature(PdfName.ADOBE_PPKMS, PdfName.ADBE_PKCS7_SHA1)
            {
                Date     = new PdfDate(sigAppearance.SignDate),
                Name     = PdfPKCS7.GetSubjectFields(chain[0]).GetField("CN"),
                Reason   = sigAppearance.Reason,
                Location = sigAppearance.Location
            };

            sigAppearance.CryptoDictionary = dic;
            const int csize = 4000;
            var       exc   = new Dictionary <PdfName, int> {
                { PdfName.CONTENTS, csize * 2 + 2 }
            };

            sigAppearance.PreClose(exc);

            HashAlgorithm sha = new SHA1CryptoServiceProvider();

            var s = sigAppearance.RangeStream;
            int read;
            var buff = new byte[8192];

            while ((read = s.Read(buff, 0, 8192)) > 0)
            {
                sha.TransformBlock(buff, 0, read, buff, 0);
            }
            sha.TransformFinalBlock(buff, 0, 0);
            var pk = SignMsg(sha.Hash, card, false);

            var outc = new byte[csize];

            var dic2 = new PdfDictionary();

            Array.Copy(pk, 0, outc, 0, pk.Length);

            dic2.Put(PdfName.CONTENTS, new PdfString(outc).SetHexWriting(true));

            sigAppearance.Close(dic2);
        }
        private byte[] ComputeSignature()
        {
            using (SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider())
            {
                foreach (DictionaryEntry entry in _templates)
                {
                    var keyBytes   = Encoding.UTF8.GetBytes((string)entry.Key);
                    var valueBytes = Encoding.UTF8.GetBytes((string)entry.Value);
                    sha1.TransformBlock(keyBytes, 0, keyBytes.Length, keyBytes, 0);
                    sha1.TransformBlock(_valueSeparator, 0, _valueSeparator.Length, _valueSeparator, 0);
                    sha1.TransformBlock(valueBytes, 0, valueBytes.Length, valueBytes, 0);
                    sha1.TransformBlock(_recordSeparator, 0, _recordSeparator.Length, _recordSeparator, 0);
                }

                var fallbackSignatureBytes = _fallback != null?_fallback.ComputeSignature() : new byte[0];

                sha1.TransformFinalBlock(fallbackSignatureBytes, 0, fallbackSignatureBytes.Length);

                return(sha1.Hash);
            }
        }
Beispiel #23
0
        public static string GetServerHash(byte[] serverId, byte[] secretKey, byte[] publicKey)
        {
            using var sha = new SHA1CryptoServiceProvider();
            sha.TransformBlock(serverId, 0, serverId.Length, serverId, 0);
            sha.TransformBlock(secretKey, 0, secretKey.Length, secretKey, 0);
            sha.TransformBlock(publicKey, 0, publicKey.Length, publicKey, 0);
            sha.TransformFinalBlock(new byte[0], 0, 0);

            var hash     = sha.Hash;
            var negative = (hash[0] & 0x80) == 0x80;

            if (negative)
            {
                int i;
                var carry = true;
                for (i = hash.Length - 1; i >= 0; i--)
                {
                    hash[i] = (byte)~hash[i];
                    if (!carry)
                    {
                        continue;
                    }
                    carry = hash[i] == 0xFF;
                    hash[i]++;
                }
            }

            var result = hash
                         .Aggregate(string.Empty, (current, t) => current + t.ToString("x2", CultureInfo.InvariantCulture))
                         .TrimStart('0');

            if (negative)
            {
                result = "-" + result;
            }

            return(result);
        }
Beispiel #24
0
        /// <summary>
        /// Firma un documento
        /// </summary>
        /// <param name="Source">Documento origen</param>
        /// <param name="Target">Documento destino</param>
        /// <param name="Certificate">Certificado a utilizar</param>
        /// <param name="Reason">Razón de la firma</param>
        /// <param name="Location">Ubicación</param>
        /// <param name="AddVisibleSign">Establece si hay que agregar la firma visible al documento</param>
        public void SignHashed(string Source, string Target, SysX509.X509Certificate2 Certificate, string Reason, string Location, bool AddVisibleSign, DatosPersonales datos)
        {
            X509CertificateParser objCP = new X509CertificateParser();

            Org.BouncyCastle.X509.X509Certificate[] objChain = new Org.BouncyCastle.X509.X509Certificate[] { objCP.ReadCertificate(Certificate.RawData) };

            PdfReader              objReader  = new PdfReader(Source);
            PdfStamper             objStamper = PdfStamper.CreateSignature(objReader, new FileStream(Target, FileMode.Create), '\0', null, true);
            PdfSignatureAppearance objSA      = objStamper.SignatureAppearance;

            if (AddVisibleSign)
            {
                objSA.SetVisibleSignature(new Rectangle(100f, objReader.XrefSize, 500, 100), 1, null);
            }

            objSA.SignDate = DateTime.Now;
            objSA.SetCrypto(null, objChain, null, null);
            objSA.Reason      = Reason;
            objSA.Location    = Location;
            objSA.Acro6Layers = true;
            objSA.Render      = PdfSignatureAppearance.SignatureRender.NameAndDescription;
            PdfSignature objSignature = new PdfSignature(PdfName.ADOBE_PPKMS, PdfName.ADBE_PKCS7_SHA1);

            objSignature.Date = new PdfDate(objSA.SignDate);
            objSignature.Name = PdfPKCS7.GetSubjectFields(objChain[0]).GetField("CN");
            if (objSA.Reason != null)
            {
                objSignature.Reason = objSA.Reason;
            }
            if (objSA.Location != null)
            {
                objSignature.Location = objSA.Location;
            }
            objSA.CryptoDictionary = objSignature;
            int intCSize = 4000;


            //  Hashtable objTable = new Hashtable();
            //  objTable[PdfName.CONTENTS] = intCSize * 2 + 2;
            Dictionary <PdfName, int> objTable = new Dictionary <PdfName, int>();
            PdfName pdfname = new PdfName("firma");

            // Add some elements to the dictionary. There are no
            // duplicate keys, but some of the values are duplicates.
            objTable.Add(pdfname, intCSize * 2 + 2);
            objSA.PreClose(objTable);

            HashAlgorithm objSHA1 = new SHA1CryptoServiceProvider();

            Stream objStream = objSA.RangeStream;
            int    intRead   = 0;

            byte[] bytBuffer = new byte[8192];
            while ((intRead = objStream.Read(bytBuffer, 0, 8192)) > 0)
            {
                objSHA1.TransformBlock(bytBuffer, 0, intRead, bytBuffer, 0);
            }
            objSHA1.TransformFinalBlock(bytBuffer, 0, 0);

            byte[] bytPK  = SignMsg(objSHA1.Hash, Certificate, false);
            byte[] bytOut = new byte[intCSize];

            PdfDictionary objDict = new PdfDictionary();

            Array.Copy(bytPK, 0, bytOut, 0, bytPK.Length);

            objDict.Put(pdfname, new PdfString(bytOut).SetHexWriting(true));
            try
            {
                objSA.Close(objDict);
            }
            catch (Exception ex)
            {
            }
        }
Beispiel #25
0
        public bool FirmarPDF(string pdfOriginal, string pdfFirmado, SysX509.X509Certificate2 certificado, string imagenFirma, bool firmaVisible, float puntoEsquinaInferiorIzquierdaX, float puntoEsquinaInferiorIzquierdaY, float puntoEsquinaSuperiorDerechaX, float puntoEsquinaSuperiorDerechaY, eTipoPagina paginaFirma, int pagina)
        {
            int numPagina = 0;

            try
            {
                X509CertificateParser objCP = new X509CertificateParser();
                Org.BouncyCastle.X509.X509Certificate[] objChain = new Org.BouncyCastle.X509.X509Certificate[] { objCP.ReadCertificate(certificado.RawData) };

                PdfReader              objReader  = new PdfReader(pdfOriginal);
                PdfStamper             objStamper = PdfStamper.CreateSignature(objReader, new FileStream(pdfFirmado, FileMode.Create), '\0');
                PdfSignatureAppearance objSA      = objStamper.SignatureAppearance;

                if (paginaFirma == eTipoPagina.Ultima)
                {
                    numPagina = objReader.NumberOfPages;
                }
                else
                {
                    if (pagina <= objReader.NumberOfPages)
                    {
                        numPagina = pagina;
                    }
                    else if (pagina > objReader.NumberOfPages)
                    {
                        numPagina = objReader.NumberOfPages;
                    }
                    else if (pagina < 1)
                    {
                        numPagina = 1;
                    }
                }
                if (firmaVisible)
                {
                    Rectangle rect = new Rectangle(puntoEsquinaInferiorIzquierdaX, puntoEsquinaInferiorIzquierdaY, puntoEsquinaSuperiorDerechaX, puntoEsquinaSuperiorDerechaY);
                    objSA.SetVisibleSignature(rect, numPagina, null);
                }


                objSA.CertificationLevel = PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED;

                objSA.SignDate = DateTime.Now;
                objSA.SetCrypto(null, objChain, null, null);
                objSA.Acro6Layers = true;
                objSA.Render      = PdfSignatureAppearance.SignatureRender.NameAndDescription;
                //objSA.SignatureGraphic = iTextSharp.text.Image.GetInstance(imagenFirma); //
                PdfSignature objSignature = new PdfSignature(PdfName.ADOBE_PPKMS, PdfName.ADBE_PKCS7_SHA1);
                objSignature.Date = new PdfDate(objSA.SignDate);
                objSignature.Name = PdfPKCS7.GetSubjectFields(objChain[0]).GetField("CN");
                if (objSA.Reason != null)
                {
                    objSignature.Reason = objSA.Reason;
                }
                if (objSA.Location != null)
                {
                    objSignature.Location = objSA.Location;
                }
                if (objSA.Contact != null)
                {
                    objSignature.Contact = objSA.Contact;
                }
                objSA.CryptoDictionary = objSignature;
                int intCSize = 4000;
                Dictionary <PdfName, int> objTable = new Dictionary <PdfName, int>();
                objTable[PdfName.CONTENTS] = intCSize * 2 + 2;
                objSA.PreClose(objTable);

                HashAlgorithm objSHA1 = new SHA1CryptoServiceProvider();

                Stream objStream = objSA.RangeStream;
                int    intRead   = 0;
                byte[] bytBuffer = new byte[8192];
                while ((intRead = objStream.Read(bytBuffer, 0, 8192)) > 0)
                {
                    objSHA1.TransformBlock(bytBuffer, 0, intRead, bytBuffer, 0);
                }
                objSHA1.TransformFinalBlock(bytBuffer, 0, 0);

                byte[] bytPK  = GenerarFirmar(objSHA1.Hash, certificado, false);
                byte[] bytOut = new byte[intCSize];

                PdfDictionary objDict = new PdfDictionary();

                Array.Copy(bytPK, 0, bytOut, 0, bytPK.Length);

                objDict.Put(PdfName.CONTENTS, new PdfString(bytOut).SetHexWriting(true));
                objSA.Close(objDict);

                return(true);
            }
            catch
            {
                throw;
            }
        }
Beispiel #26
0
        /// <summary>
        /// Firma un documento
        /// </summary>
        /// <param name="Source">Documento origen</param>
        /// <param name="Target">Documento destino</param>
        /// <param name="Certificate">Certificado a utilizar</param>
        /// <param name="Reason">Razón de la firma</param>
        /// <param name="Location">Ubicación</param>
        /// <param name="AddVisibleSign">Establece si hay que agregar la firma visible al documento</param>
        public static void SignHashed(string Source, string Target, SysX509.X509Certificate2 Certificate, string Reason, string Location, bool AddVisibleSign)
        {
            X509CertificateParser objCP = new X509CertificateParser();

            X509Certificate[] objChain = new X509Certificate[] { objCP.ReadCertificate(Certificate.RawData) };

            PdfReader              objReader  = new PdfReader(Source);
            PdfStamper             objStamper = PdfStamper.CreateSignature(objReader, new FileStream(Target, FileMode.Create), '\0');
            PdfSignatureAppearance objSA      = objStamper.SignatureAppearance;

            if (AddVisibleSign)
            {
                objSA.SetVisibleSignature(new Rectangle(50, 50, 150, 100), 2, null);
            }

            objSA.SignDate = DateTime.Now;
            objSA.SetCrypto(null, objChain, null, null);
            objSA.Reason      = Reason;
            objSA.Location    = Location;
            objSA.Acro6Layers = true;
            objSA.Render      = PdfSignatureAppearance.SignatureRender.NameAndDescription;
            PdfSignature objSignature = new PdfSignature(PdfName.ADOBE_PPKMS, PdfName.ADBE_PKCS7_SHA1);

            objSignature.Date = new PdfDate(objSA.SignDate);
            objSignature.Name = PdfPKCS7.GetSubjectFields(objChain[0]).GetField("CN");
            if (objSA.Reason != null)
            {
                objSignature.Reason = objSA.Reason;
            }
            if (objSA.Location != null)
            {
                objSignature.Location = objSA.Location;
            }
            objSA.CryptoDictionary = objSignature;
            int       intCSize = 4000;
            Hashtable objTable = new Hashtable();

            objTable[PdfName.CONTENTS] = intCSize * 2 + 2;
            objSA.PreClose(objTable);

            HashAlgorithm objSHA1 = new SHA1CryptoServiceProvider();

            Stream objStream = objSA.RangeStream;
            int    intRead   = 0;

            byte[] bytBuffer = new byte[8192];
            while ((intRead = objStream.Read(bytBuffer, 0, 8192)) > 0)
            {
                objSHA1.TransformBlock(bytBuffer, 0, intRead, bytBuffer, 0);
            }
            objSHA1.TransformFinalBlock(bytBuffer, 0, 0);

            byte[] bytPK  = SignMsg(objSHA1.Hash, Certificate, false);
            byte[] bytOut = new byte[intCSize];

            PdfDictionary objDict = new PdfDictionary();

            Array.Copy(bytPK, 0, bytOut, 0, bytPK.Length);

            objDict.Put(PdfName.CONTENTS, new PdfString(bytOut).SetHexWriting(true));
            objSA.Close(objDict);
        }
        public PdfDictionary GetEncryptionDictionary()
        {
            var dic = new PdfDictionary();

            if (PublicKeyHandler.GetRecipientsSize() > 0)
            {
                PdfArray recipients = null;

                dic.Put(PdfName.Filter, PdfName.Pubsec);
                dic.Put(PdfName.R, new PdfNumber(_revision));

                recipients = PublicKeyHandler.GetEncodedRecipients();

                if (_revision == STANDARD_ENCRYPTION_40)
                {
                    dic.Put(PdfName.V, new PdfNumber(1));
                    dic.Put(PdfName.Subfilter, PdfName.AdbePkcs7S4);
                    dic.Put(PdfName.Recipients, recipients);
                }
                else if (_revision == STANDARD_ENCRYPTION_128 && _encryptMetadata)
                {
                    dic.Put(PdfName.V, new PdfNumber(2));
                    dic.Put(PdfName.LENGTH, new PdfNumber(128));
                    dic.Put(PdfName.Subfilter, PdfName.AdbePkcs7S4);
                    dic.Put(PdfName.Recipients, recipients);
                }
                else
                {
                    dic.Put(PdfName.R, new PdfNumber(AES_128));
                    dic.Put(PdfName.V, new PdfNumber(4));
                    dic.Put(PdfName.Subfilter, PdfName.AdbePkcs7S5);

                    var stdcf = new PdfDictionary();
                    stdcf.Put(PdfName.Recipients, recipients);
                    if (!_encryptMetadata)
                    {
                        stdcf.Put(PdfName.Encryptmetadata, PdfBoolean.Pdffalse);
                    }

                    if (_revision == AES_128)
                    {
                        stdcf.Put(PdfName.Cfm, PdfName.Aesv2);
                    }
                    else
                    {
                        stdcf.Put(PdfName.Cfm, PdfName.V2);
                    }

                    var cf = new PdfDictionary();
                    cf.Put(PdfName.Defaultcryptfilter, stdcf);
                    dic.Put(PdfName.Cf, cf);
                    if (_embeddedFilesOnly)
                    {
                        dic.Put(PdfName.Eff, PdfName.Defaultcryptfilter);
                        dic.Put(PdfName.Strf, PdfName.Identity);
                        dic.Put(PdfName.Stmf, PdfName.Identity);
                    }
                    else
                    {
                        dic.Put(PdfName.Strf, PdfName.Defaultcryptfilter);
                        dic.Put(PdfName.Stmf, PdfName.Defaultcryptfilter);
                    }
                }

#if NET40
                SHA1   sh = new SHA1CryptoServiceProvider();
                byte[] encodedRecipient = null;
                var    seed             = PublicKeyHandler.GetSeed();
                sh.TransformBlock(seed, 0, seed.Length, seed, 0);
                for (var i = 0; i < PublicKeyHandler.GetRecipientsSize(); i++)
                {
                    encodedRecipient = PublicKeyHandler.GetEncodedRecipient(i);
                    sh.TransformBlock(encodedRecipient, 0, encodedRecipient.Length, encodedRecipient, 0);
                }
                if (!_encryptMetadata)
                {
                    sh.TransformBlock(MetadataPad, 0, MetadataPad.Length, MetadataPad, 0);
                }

                sh.TransformFinalBlock(seed, 0, 0);
                var mdResult = sh.Hash;
#else
                byte[] mdResult;
                using (var sh = IncrementalHash.CreateHash(HashAlgorithmName.SHA1))
                {
                    var seed = PublicKeyHandler.GetSeed();
                    sh.AppendData(seed, 0, seed.Length);
                    for (var i = 0; i < PublicKeyHandler.GetRecipientsSize(); i++)
                    {
                        var encodedRecipient = PublicKeyHandler.GetEncodedRecipient(i);
                        sh.AppendData(encodedRecipient, 0, encodedRecipient.Length);
                    }
                    if (!_encryptMetadata)
                    {
                        sh.AppendData(MetadataPad, 0, MetadataPad.Length);
                    }

                    mdResult = sh.GetHashAndReset();
                }
#endif

                SetupByEncryptionKey(mdResult, _keyLength);
            }
            else
            {
                dic.Put(PdfName.Filter, PdfName.Standard);
                dic.Put(PdfName.O, new PdfLiteral(PdfContentByte.EscapeString(OwnerKey)));
                dic.Put(PdfName.U, new PdfLiteral(PdfContentByte.EscapeString(UserKey)));
                dic.Put(PdfName.P, new PdfNumber(Permissions));
                dic.Put(PdfName.R, new PdfNumber(_revision));
                if (_revision == STANDARD_ENCRYPTION_40)
                {
                    dic.Put(PdfName.V, new PdfNumber(1));
                }
                else if (_revision == STANDARD_ENCRYPTION_128 && _encryptMetadata)
                {
                    dic.Put(PdfName.V, new PdfNumber(2));
                    dic.Put(PdfName.LENGTH, new PdfNumber(128));
                }
                else
                {
                    if (!_encryptMetadata)
                    {
                        dic.Put(PdfName.Encryptmetadata, PdfBoolean.Pdffalse);
                    }

                    dic.Put(PdfName.R, new PdfNumber(AES_128));
                    dic.Put(PdfName.V, new PdfNumber(4));
                    dic.Put(PdfName.LENGTH, new PdfNumber(128));
                    var stdcf = new PdfDictionary();
                    stdcf.Put(PdfName.LENGTH, new PdfNumber(16));
                    if (_embeddedFilesOnly)
                    {
                        stdcf.Put(PdfName.Authevent, PdfName.Efopen);
                        dic.Put(PdfName.Eff, PdfName.Stdcf);
                        dic.Put(PdfName.Strf, PdfName.Identity);
                        dic.Put(PdfName.Stmf, PdfName.Identity);
                    }
                    else
                    {
                        stdcf.Put(PdfName.Authevent, PdfName.Docopen);
                        dic.Put(PdfName.Strf, PdfName.Stdcf);
                        dic.Put(PdfName.Stmf, PdfName.Stdcf);
                    }
                    if (_revision == AES_128)
                    {
                        stdcf.Put(PdfName.Cfm, PdfName.Aesv2);
                    }
                    else
                    {
                        stdcf.Put(PdfName.Cfm, PdfName.V2);
                    }

                    var cf = new PdfDictionary();
                    cf.Put(PdfName.Stdcf, stdcf);
                    dic.Put(PdfName.Cf, cf);
                }
            }
            return(dic);
        }
Beispiel #28
0
        /// <summary>
        /// 将文件利用AES进行静态解密
        /// </summary>
        /// <param name="inputFile">输入的文件路径</param>
        /// <param name="outputFile">输出的文件路径</param>
        /// <param name="aesKey">AES密钥</param>
        /// <param name="aesIV">AES初始向量</param>
        public static void DecryptFile(string inputFile, string outputFile, byte[] aesKey, byte[] aesIV, StatusCallback callback = null)
        {
            if (string.IsNullOrEmpty(inputFile))
            {
                throw new ArgumentNullException("inputFile");
            }
            if (string.IsNullOrEmpty(outputFile))
            {
                throw new ArgumentNullException("outputFile");
            }
            if (!File.Exists(inputFile))
            {
                throw new ArgumentException("inputFile not exists");
            }
            if (aesKey == null)
            {
                throw new ArgumentNullException("aesKey");
            }
            if (aesIV == null)
            {
                throw new ArgumentNullException("aesIV");
            }
            FileStream fs_in = null, fs_out = null;

            try
            {
                fs_in  = new FileStream(inputFile, FileMode.Open, FileAccess.Read, FileShare.Read);
                fs_out = new FileStream(outputFile, FileMode.Create, FileAccess.Write, FileShare.None);
                var file_length      = fs_in.Length;
                var proceeded_length = 3;

                int type = fs_in.ReadByte();
                if (type != FLG_STATIC_KEY)
                {
                    fs_in.Close();
                    fs_out.Close();
                    throw new InvalidDataException("格式错误:该文件不是采用静态加密的文件");
                }
                var preserved = util.ReadBytes(fs_in, 2); //preserved for latter usage

                var       decrypted_stream = Crypto.AES_StreamDecrypt(fs_in, aesKey, CipherMode.CFB, aesIV);
                int       nread            = 0;
                const int buffer_size      = 4096;
                var       buffer           = new byte[buffer_size];
                var       sha1             = new SHA1CryptoServiceProvider();
                byte[]    SHA1             = util.ReadBytes(decrypted_stream, 20);
                do
                {
                    nread             = decrypted_stream.Read(buffer, 0, buffer_size);
                    proceeded_length += nread;
                    fs_out.Write(buffer, 0, nread);
                    sha1.TransformBlock(buffer, 0, nread, buffer, 0);
                    callback?.Invoke(inputFile, outputFile, proceeded_length, file_length);
                } while (nread != 0);
                sha1.TransformFinalBlock(buffer, 0, 0);
                var cur_sha1 = sha1.Hash;
                fs_out.Close();
                decrypted_stream.Close();
                var sha1_empty = new byte[20];
                if (util.Hex(cur_sha1) != util.Hex(SHA1) && util.Hex(SHA1) != util.Hex(sha1_empty))
                {
                    throw new InvalidDataException("SHA1检验不匹配:解密失败");
                }
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                fs_in?.Close();
                fs_out?.Close();
            }
        }
Beispiel #29
0
        /// <inheritdoc/>
        protected override void Run()
        {
            Wizard.TryInvoke((Action)(() => Wizard.TaskCount++));
            try
            {
                var propertyUpdater = new DispatcherTimer(
                    new TimeSpan(0, 0, 0, 1),
                    DispatcherPriority.Normal,
                    (object sender, EventArgs e) => _ShowLog?.RaiseCanExecuteChanged(),
                    Wizard.Dispatcher);
                propertyUpdater.Start();
                try
                {
                    // Get a random TCP port for openvpn.exe management interface.
                    var mgmtServer = new TcpListener(IPAddress.Loopback, 0);
                    mgmtServer.Start();
                    try
                    {
                        byte[] ovpn;
                        var    mgmtEndpoint = mgmtServer.LocalEndpoint as IPEndPoint;
                        var    mgmtPassword = Membership.GeneratePassword(16, 6);
                        try
                        {
                            // Prepare OpenVPN configuration.
                            var fs = new MemoryStream();
                            using (fs)
                                using (var sw = new StreamWriter(fs))
                                {
                                    if (Properties.SettingsEx.Default.OpenVPNRemoveOptions is StringCollection openVPNRemoveOptions)
                                    {
                                        // Remove options on the OpenVPNRemoveOptions list on the fly.
                                        using (var sr = new StringReader(ProfileConfig.Value))
                                        {
                                            string inlineTerm   = null;
                                            var    inlineRemove = false;
                                            for (; ;)
                                            {
                                                var line = sr.ReadLine();
                                                if (line == null)
                                                {
                                                    break;
                                                }

                                                var trimmedLine = line.Trim();
                                                if (!string.IsNullOrEmpty(trimmedLine))
                                                {
                                                    // Not an empty line.
                                                    if (inlineTerm == null)
                                                    {
                                                        // Not inside an inline option block = Regular parsing mode.
                                                        if (!trimmedLine.StartsWith("#") &&
                                                            !trimmedLine.StartsWith(";"))
                                                        {
                                                            // Not a comment.
                                                            var option = Configuration.ParseParams(trimmedLine);
                                                            if (option.Count > 0)
                                                            {
                                                                if (option[0].StartsWith("<") && !option[0].StartsWith("</") && option[0].EndsWith(">"))
                                                                {
                                                                    // Start of an inline option.
                                                                    var o = option[0].Substring(1, option[0].Length - 2);
                                                                    inlineTerm   = "</" + o + ">";
                                                                    inlineRemove = openVPNRemoveOptions.Contains(o);
                                                                    if (inlineRemove)
                                                                    {
                                                                        sw.WriteLine("# Commented by OpenVPNRemoveOptions setting:");
                                                                        line = "# " + line;
                                                                    }
                                                                }
                                                                else if (openVPNRemoveOptions.Contains(option[0]))
                                                                {
                                                                    sw.WriteLine("# Commented by OpenVPNRemoveOptions setting:");
                                                                    line = "# " + line;
                                                                }
                                                            }
                                                        }
                                                    }
                                                    else
                                                    {
                                                        // Inside an inline option block.
                                                        if (inlineRemove)
                                                        {
                                                            // Remove the inline option content.
                                                            line = "# " + line;
                                                        }

                                                        if (trimmedLine == inlineTerm)
                                                        {
                                                            // Inline option terminator found. Returning to regular parsing mode.
                                                            inlineTerm = null;
                                                        }
                                                    }
                                                }

                                                sw.WriteLine(line);
                                            }
                                        }
                                    }
                                    else
                                    {
                                        sw.Write(ProfileConfig.Value);
                                    }

                                    // Append eduVPN Client specific configuration directives.
                                    sw.WriteLine();
                                    sw.WriteLine();
                                    sw.WriteLine("# eduVPN Client for Windows");

                                    // Introduce ourself (to OpenVPN server).
                                    var assembly = Assembly.GetExecutingAssembly();
                                    var assemblyTitleAttribute = Attribute.GetCustomAttributes(assembly, typeof(AssemblyTitleAttribute)).SingleOrDefault() as AssemblyTitleAttribute;
                                    var assemblyVersion        = assembly?.GetName()?.Version;
                                    sw.WriteLine("setenv IV_GUI_VER " + Configuration.EscapeParamValue(assemblyTitleAttribute?.Title + " " + assemblyVersion?.ToString()));

                                    // Configure log file (relative to WorkingFolder).
                                    sw.WriteLine("log-append " + Configuration.EscapeParamValue(ConnectionId + ".txt"));

                                    // Configure interaction between us and openvpn.exe.
                                    sw.WriteLine("management " + Configuration.EscapeParamValue(mgmtEndpoint.Address.ToString()) + " " + Configuration.EscapeParamValue(mgmtEndpoint.Port.ToString()));
                                    sw.WriteLine("<management-client-pass>");
                                    sw.WriteLine(mgmtPassword);
                                    sw.WriteLine("</management-client-pass>");
                                    sw.WriteLine("management-hold");    // Wait for our signal to start connecting.
                                    sw.WriteLine("management-signal");  // Raise SIGUSR1 if our client dies/closes management interface.
                                    sw.WriteLine("remap-usr1 SIGTERM"); // SIGUSR1 (reconnect) => SIGTERM (disconnect)
                                    sw.WriteLine("management-query-passwords");

                                    // Ask when username/password is denied.
                                    sw.WriteLine("auth-retry interact");
                                    sw.WriteLine("auth-nocache");

                                    // Set Wintun interface to be used.
                                    sw.Write("windows-driver wintun\n");
                                    var    hash         = new SHA1CryptoServiceProvider();                                                                    // https://datatracker.ietf.org/doc/html/rfc4122#section-4.3
                                    byte[] bufferPrefix = { 0x6b, 0xa7, 0xb8, 0x11, 0x9d, 0xad, 0x11, 0xd1, 0x80, 0xb4, 0x00, 0xc0, 0x4f, 0xd4, 0x30, 0xc8 }; // https://datatracker.ietf.org/doc/html/rfc4122#appendix-C in network byte order
                                    hash.TransformBlock(bufferPrefix, 0, bufferPrefix.Length, bufferPrefix, 0);
                                    var bufferUri = Encoding.UTF8.GetBytes(new Uri(ConnectingProfile.Server.Base, ConnectingProfile.Id).AbsoluteUri);
                                    hash.TransformFinalBlock(bufferUri, 0, bufferUri.Length);
                                    var guid = new Guid(
                                        ((uint)hash.Hash[0] << 24) | ((uint)hash.Hash[1] << 16) | ((uint)hash.Hash[2] << 8) | hash.Hash[3], // time_low
                                        (ushort)(((uint)hash.Hash[4] << 8) | hash.Hash[5]),                                                 // time_mid
                                        (ushort)(((((uint)hash.Hash[6] << 8) | hash.Hash[7]) & 0x0fff) | 0x5000),                           // time_hi_and_version
                                        (byte)(((uint)hash.Hash[8] & 0x3f) | 0x80),                                                         // clock_seq_hi_and_reserved
                                        hash.Hash[9],                                                                                       // clock_seq_low
                                        hash.Hash[10], hash.Hash[11], hash.Hash[12], hash.Hash[13], hash.Hash[14], hash.Hash[15]);          // node[0-5]
                                    sw.Write("dev-node {" + guid + "}\n");

#if DEBUG
                                    // Renegotiate data channel every 5 minutes in debug versions.
                                    sw.WriteLine("reneg-sec 300");
#endif

                                    if (Environment.OSVersion.Version < new Version(6, 2))
                                    {
                                        // Windows 7 is using tiny 8kB send/receive socket buffers by default.
                                        // Increase to 64kB which is default from Windows 8 on.
                                        sw.WriteLine("sndbuf 65536");
                                        sw.WriteLine("rcvbuf 65536");
                                    }

                                    var openVPNAddOptions = Properties.SettingsEx.Default.OpenVPNAddOptions;
                                    if (!string.IsNullOrWhiteSpace(openVPNAddOptions))
                                    {
                                        sw.WriteLine();
                                        sw.WriteLine();
                                        sw.WriteLine("# Added by OpenVPNAddOptions setting:");
                                        sw.WriteLine(openVPNAddOptions);
                                    }
                                }
                            ovpn = fs.ToArray();
                        }
                        catch (OperationCanceledException) { throw; }
                        catch (Exception ex) { throw new AggregateException(string.Format(Resources.Strings.ErrorSavingProfileConfiguration, ConfigurationPath), ex); }

retry:
                        // Connect to OpenVPN Interactive Service to launch the openvpn.exe.
                        using (var openvpnInteractiveServiceConnection = new eduOpenVPN.InteractiveService.Session())
                        {
                            // Release TCP port for openvpn.exe management interface.
                            mgmtServer.Stop();

                            try
                            {
                                openvpnInteractiveServiceConnection.Connect(
                                    string.Format("openvpn{0}\\service", Properties.SettingsEx.Default.OpenVPNInteractiveServiceInstance),
                                    WorkingFolder,
                                    new string[] { "--config", "stdin", },
                                    Encoding.UTF8.GetString(ovpn),
                                    3000,
                                    Window.Abort.Token);
                            }
                            catch (OperationCanceledException) { throw; }
                            catch (Exception ex) { throw new AggregateException(Resources.Strings.ErrorInteractiveService, ex); }

                            try
                            {
                                // Connect to the openvpn.exe management interface.
                                var mgmtClient     = new TcpClient();
                                var reconnectCount = 0;
reconnect:
                                var mgmtClientTask = mgmtClient.ConnectAsync(mgmtEndpoint.Address, mgmtEndpoint.Port);
                                try { mgmtClientTask.Wait(30000, Window.Abort.Token); }
                                catch (AggregateException ex)
                                {
                                    if (ex.InnerException is SocketException ex2 && ex2.SocketErrorCode == SocketError.ConnectionRefused &&
                                        ++reconnectCount < 30 && !Window.Abort.Token.WaitHandle.WaitOne(1000))
                                    {
                                        Trace.TraceWarning("Failed to connect to openvpn.exe");
                                        goto reconnect;
                                    }
                                    throw ex.InnerException;
                                }
                                try
                                {
                                    // Create and start the management session.
                                    ManagementSession = new eduOpenVPN.Management.Session();
                                    ManagementSession.ByteCountReported  += ManagementSession_ByteCountReported;
                                    ManagementSession.FatalErrorReported += ManagementSession_FatalErrorReported;
                                    ManagementSession.HoldReported       += ManagementSession_HoldReported;
                                    ManagementSession.StateReported      += ManagementSession_StateReported;
                                    ManagementSession.Start(mgmtClient.GetStream(), mgmtPassword, Window.Abort.Token);

                                    // Initialize session and release openvpn.exe to get started.
                                    ManagementSession.SetVersion(3, Window.Abort.Token);
                                    ManagementSession.ReplayAndEnableState(Window.Abort.Token);
                                    ManagementSession.ReplayAndEnableEcho(Window.Abort.Token);
                                    ManagementSession.SetByteCount(5, Window.Abort.Token);
                                    ManagementSession.ReleaseHold(Window.Abort.Token);

                                    Wizard.TryInvoke((Action)(() =>
                                    {
                                        _Renew?.RaiseCanExecuteChanged();
                                        _Disconnect?.RaiseCanExecuteChanged();
                                        Wizard.TaskCount--;
                                    }));
                                    try
                                    {
                                        // Wait for the session to end gracefully.
                                        ManagementSession.Monitor.Join();
                                        if (!(ManagementSession.Error is OperationCanceledException) && !DisconnectInProgress)
                                        {
                                            goto retry;
                                        }
                                    }
                                    finally { Wizard.TryInvoke((Action)(() => Wizard.TaskCount++)); }
                                }
                                finally { mgmtClient.Close(); }
                            }
                            finally
                            {
                                Wizard.TryInvoke((Action)(() =>
                                {
                                    // Cleanup status properties.
                                    State = SessionStatusType.Disconnecting;
                                    StateDescription = Resources.Strings.OpenVPNStateTypeExiting;
                                    TunnelAddress = null;
                                    IPv6TunnelAddress = null;
                                    ConnectedAt = null;
                                    BytesIn = null;
                                    BytesOut = null;
                                }));

                                // Wait for openvpn.exe to finish. Maximum 30s.
                                try { Process.GetProcessById(openvpnInteractiveServiceConnection.ProcessId)?.WaitForExit(30000); }
                                catch (ArgumentException) { }
                            }
                        }
                    }
                    finally { mgmtServer.Stop(); }
                }
                finally { propertyUpdater.Stop(); }
            }
            finally { Wizard.TryInvoke((Action)(() => Wizard.TaskCount--)); }
        }
Beispiel #30
0
        /// <summary>
        /// Configura la informacion del certificado digital
        /// </summary>
        /// <param name="origen"></param>
        /// <param name="destino"></param>
        /// <param name="rutaCertificado"></param>
        /// <param name="pass"></param>
        public bool infoCertificado(string origen, string destino, string rutaCertificado, string pass)
        {
            bool resultado = false;

            try
            {
                //SAPbouiCOM.Framework.Application.SBO_Application.MessageBox("origen " + origen);
                //SAPbouiCOM.Framework.Application.SBO_Application.MessageBox("destino " + destino);
                //SAPbouiCOM.Framework.Application.SBO_Application.MessageBox("rutaCertificado " + rutaCertificado);
                //SAPbouiCOM.Framework.Application.SBO_Application.MessageBox("clave " + pass);

                //Se obtiene el certficado
                x509.X509Certificate2 certificado = new x509.X509Certificate2(rutaCertificado, pass);
                X509CertificateParser objCP       = new X509CertificateParser();

                Org.BouncyCastle.X509.X509Certificate[] objChain = new
                                                                   Org.BouncyCastle.X509.X509Certificate[] { objCP.ReadCertificate(certificado.RawData) };

                //Objeto de tipo documento pdf
                PdfReader objReader = new PdfReader(origen);
                //Crea el objeto para la firma digital
                PdfStamper objStamper = PdfStamper.CreateSignature(objReader,
                                                                   new FileStream(destino, FileMode.Create), '\0');
                PdfSignatureAppearance objSA = objStamper.SignatureAppearance;

                //Configuracion de informacion para la firma digital
                objSA.SignDate = DateTime.Now;
                objSA.SetCrypto(null, objChain, null, null);
                objSA.Reason      = "Comprobante Generado";
                objSA.Location    = "Uruguay";
                objSA.Acro6Layers = true;
                objSA.Render      = PdfSignatureAppearance.SignatureRender.NameAndDescription;

                PdfSignature objSignature = new PdfSignature(PdfName.ADOBE_PPKMS,
                                                             PdfName.ADBE_PKCS7_SHA1);
                objSignature.Date = new PdfDate(objSA.SignDate);
                objSignature.Name = PdfPKCS7.GetSubjectFields(objChain[0]).GetField("CN");

                if (objSA.Reason != null)
                {
                    objSignature.Reason = objSA.Reason;
                }

                if (objSA.Location != null)
                {
                    objSignature.Location = objSA.Location;
                }

                objSA.CryptoDictionary = objSignature;
                int intCSize = 4000;

                Hashtable objTable = new Hashtable();
                objTable[PdfName.CONTENTS] = intCSize * 2 + 2;
                objSA.PreClose(objTable);
                Stream objStream = objSA.RangeStream;

                HashAlgorithm objSHA1 = new SHA1CryptoServiceProvider();
                int           intRead = 0;

                byte[] bytBuffer = new byte[8192];
                while ((intRead = objStream.Read(bytBuffer, 0, 8192)) > 0)
                {
                    objSHA1.TransformBlock(bytBuffer, 0, intRead, bytBuffer, 0);
                }
                objSHA1.TransformFinalBlock(bytBuffer, 0, 0);

                byte[] bytPK  = firmarDocumento(objSHA1.Hash, certificado);
                byte[] bytOut = new byte[intCSize];

                PdfDictionary objDict = new PdfDictionary();
                Array.Copy(bytPK, 0, bytOut, 0, bytPK.Length);

                objDict.Put(PdfName.CONTENTS, new PdfString(bytOut).SetHexWriting(true));
                objStream.Close();
                objSA.Close(objDict);
                resultado = true;
            }
            catch (Exception ex)
            {
                SAPbouiCOM.Framework.Application.SBO_Application.MessageBox("ERROR: " + ex.ToString());
            }

            return(resultado);
        }