private void CopyFoundArticles()
        {
            var array = FoundArticles
                        .List
                        .Select(x => Zipper.Unzip(x.ZippedTitle.ToByteArray()))
                        .ToArray();

            SetProgressBarMaximum(array.Count());

            var count         = 0;
            var temporaryList = new List <string>();

            SearchResultsListClear();
            foreach (var title in array)
            {
                temporaryList.Add(title);
                if (temporaryList.Count() > MaxSearchAppendCount)
                {
                    SearchResultsListAppend(temporaryList.ToArray());
                    temporaryList.Clear();
                }
                SetProgressBarValue(count++);
            }
            SearchResultsListAppend(temporaryList.ToArray());
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Decodes the given token, throwing a <seealso cref="CryptographicException"/> if no valid
        /// information could be extracted from it.
        /// </summary>
        public DecodingResult Decode(string token)
        {
            try
            {
                var encodedToken = Encoding.ASCII.GetString(_zipper.Unzip(Decrypt(token)));

                var parts = encodedToken.Split(new[] { PartSeparatorChar }, StringSplitOptions.RemoveEmptyEntries);

                if (parts.Length != 2)
                {
                    throw new CryptographicException("Token did not contain the expected number of parts!");
                }

                var properties        = Deserialize(parts[0]);
                var hasValidSignature = CanValidateSignature(parts[0], parts[1]);
                var isExpired         = IsExpired(properties);
                var isNotValidYet     = IsNotValidYet(properties);

                return(new DecodingResult(properties, new DecodingResultDetails(hasValidSignature, isExpired, isNotValidYet)));
            }
            catch (Exception exception)
            {
                throw new CryptographicException("Could not decode token", exception);
            }
        }
Ejemplo n.º 3
0
    public async Task <Message> Deserialize(TransportMessage transportMessage)
    {
        if (!transportMessage.Headers.TryGetValue(Headers.ContentEncoding, out var contentEncoding))
        {
            return(await _serializer.Deserialize(transportMessage));
        }

        if (contentEncoding != GzipEncodingHeader)
        {
            var message = $"The message {transportMessage.GetMessageLabel()} has a '{Headers.ContentEncoding}' with the" +
                          $" value '{contentEncoding}', but this serializer decorator only knows how to decompress" +
                          $" '{GzipEncodingHeader}'";

            throw new ArgumentException(message);
        }

        var headers        = transportMessage.Headers.Clone();
        var compressedBody = transportMessage.Body;

        headers.Remove(Headers.ContentEncoding);

        var uncompressedBody             = _zipper.Unzip(compressedBody);
        var uncompressedTransportMessage = new TransportMessage(headers, uncompressedBody);

        return(await _serializer.Deserialize(uncompressedTransportMessage));
    }
Ejemplo n.º 4
0
        /// <summary>
        /// Load the htmlbody from the web
        /// </summary>
        /// <param name="url">url of the ressource</param>
        /// <param name="forceDownload">Doesnt try to read from the local cache if <b>TRUE</b></param>
        /// <returns>the string represenation of the htmlBody that has been downloaded</returns>
        public string LoadFromUrl(string url, bool forceDownload)
        {
            var stopWatch = new Stopwatch();

            stopWatch.Start();
            string result;

            var hash = GetUrlHash(url);

            var fullPath = path + hash;

            if (!forceDownload)
            {
                if (!string.IsNullOrWhiteSpace(hash) && File.Exists(fullPath))
                {
                    try
                    {
                        return(Zipper.Unzip(File.ReadAllBytes(fullPath)));
                    }
                    catch
                    {
                        Debugger.Break();
                    }
                }
            }

            var myRequest = (HttpWebRequest)WebRequest.Create(url);

            myRequest.Method = "GET";

            try
            {
                WebResponse  myResponse = myRequest.GetResponse();
                StreamReader sr         = new StreamReader(myResponse.GetResponseStream(), System.Text.Encoding.UTF8);
                result = sr.ReadToEnd();
                sr.Close();
                myResponse.Close();

                try
                {
                    File.WriteAllBytes(fullPath, Zipper.Zip(result));
                }
                catch
                {
                    //TODO: fullPath ist u.U. bullshit, weil im Konstruktur bullshit übergeben wurde...
                }

                stopWatch.Stop();

                //don't bruteforce the server on purpose...
                Thread.Sleep(25 + rnd.Next(1, 50));
                return(result);
            }
            catch
            {
                return("");
            }
        }
Ejemplo n.º 5
0
 string GetEncodedTokenOrNull(string token)
 {
     try
     {
         return(Encoding.ASCII.GetString(_zipper.Unzip(Decrypt(token))));
     }
     catch
     {
         return(null);
     }
 }
Ejemplo n.º 6
0
        public static SignedLedger ReadZippedLedger(byte[] data)
        {
            if (data == null)
            {
                return(null);
            }

            using (var stream = new ByteStream(Zipper.Unzip(data)))
            {
                return(stream.ReadSignedLedger());
            }
        }
        private void SearchForArticleInGoogleToolStripMenuItemClick(object sender, EventArgs e)
        {
            var articleClicked = GetSelectedArticle();

            if (ReferenceEquals(articleClicked, null))
            {
                return;
            }
            var unzippedTitle = Zipper.Unzip(articleClicked.ZippedTitle.ToByteArray());

            System.Diagnostics.Process.Start("http://www.google.com.au/search?q=" + Uri.EscapeDataString(unzippedTitle));
        }
Ejemplo n.º 8
0
        public void GivenZipCreatedForForeignPlatform_ThenFilesExtractedCorrectlyAndAreNotCorrupted()
        {
            var directoryToZip = TestHelper.GetZipModuleSourceDirectory();

            var numItems = Directory.EnumerateFileSystemEntries(directoryToZip, "*", SearchOption.AllDirectories)
                           .Count();
            var numDirectories = Directory.EnumerateDirectories(directoryToZip, "*", SearchOption.AllDirectories)
                                 .Count();
            var inputFiles = Directory.EnumerateFiles(directoryToZip, "*", SearchOption.AllDirectories).ToList();

            using (var zipFile = new TempFile($"test-{Guid.NewGuid()}.zip"))
                using (var tempDir = new TempDirectory())
                {
                    // Generate zip for foreign platform
                    Zipper.Zip(
                        new CrossPlatformZipSettings
                    {
                        ZipFile          = zipFile,
                        Artifacts        = directoryToZip,
                        CompressionLevel = 9,
                        TargetPlatform   = IsWindows ? ZipPlatform.Unix : ZipPlatform.Windows
                    });

                    // Now unzip it
                    // Some unzips, especially on Unix extracting zips with Windows paths get it wrong, creating files like 'dir/dir2/file.txt' rather than directory structure
                    Zipper.Unzip(zipFile, tempDir);

                    var extractedItems = Directory.EnumerateFileSystemEntries(tempDir, "*", SearchOption.AllDirectories)
                                         .Count();
                    var extractedirectories =
                        Directory.EnumerateDirectories(tempDir, "*", SearchOption.AllDirectories).Count();
                    var extratedFiles = Directory.EnumerateFiles(tempDir, "*", SearchOption.AllDirectories).ToList();

                    numItems.Should().Be(extractedItems, "total number of extracted items should be the same");
                    numItems.Should().Be(extractedItems, "total number of extracted items should be the same");
                    numDirectories.Should().Be(
                        extractedirectories,
                        "total number of extracted directories should be the same - Unix may extract windows directories as files with / in name");
                    inputFiles.Count.Should().Be(extratedFiles.Count, "total number of extracted files should be the same");

                    // Check file hashes to to assert no corruption.
                    var inputFilesToCheck  = inputFiles.ToDictionary(f => f.Substring(directoryToZip.Length), f => f);
                    var outputFilesToCheck = extratedFiles.ToDictionary(f => f.Substring(tempDir.FullName.Length), f => f);

                    foreach (var kv in inputFilesToCheck)
                    {
                        var outputFile = outputFilesToCheck[kv.Key];
                        Md5Hash(kv.Value).Should().Be(Md5Hash(outputFile), "file should not be corrupted.");
                    }
                }
        }
Ejemplo n.º 9
0
        public void ZipUnzipToFromFile()
        {
            ZipContent original = new ZipContent();

            original.A = "A";
            original.B = 6;

            string pathToZip = AppDomain.CurrentDomain.BaseDirectory + "ZipUnzipToFromFile.zip";

            Zipper.Zip(original, pathToZip);
            ZipContent unziped = Zipper.Unzip <ZipContent>(pathToZip);

            Assert.AreEqual(original, unziped);
        }
        private String GetJsonArticle(Article article)
        {
            string result         = string.Empty;
            var    bucketFileName = Zipper.Unzip(article.ZippedBucketFileName.ToByteArray());
            var    jsonArticles   = GetJsonArticles(bucketFileName);
            var    jsonFileName   = Zipper.Unzip(article.ZippedJsonFileName.ToByteArray());

            if (jsonArticles.ContainsKey(jsonFileName))
            {
                result = jsonArticles[jsonFileName];
            }

            return(result);
        }
Ejemplo n.º 11
0
        public void ZippedCanBeUnzipedTest()
        {
            string testValue = "";

            for (int i = 0; i < 100; i++)
            {
                testValue += DateTime.Now.Ticks.ToString();
            }

            var zipped = Zipper.Zip(testValue);

            var unzipped = Zipper.Unzip(zipped);

            Assert.IsTrue(testValue == unzipped);
        }
Ejemplo n.º 12
0
        public void ZipTest()
        {
            using (CreateContext())
            {
                var signed = CreateSignedLedger();

                byte[] bytes;
                using (var stream = new ByteStream())
                {
                    stream.Write(signed);
                    bytes = stream.GetBytes();
                }

                var unzipped = Zipper.Unzip(Zipper.Zip(bytes));

                Debug.Assert(bytes.IsEqual(unzipped));
            }
        }
Ejemplo n.º 13
0
        public IBaseModel GetArticle(int chapter, int article, out string template)
        {
            var chapters     = GetChapterList();
            var chapterTitle = chapters[chapter];
            var articles     = GetArticlesTitlesByChapter(chapterTitle);

            var path = $"{Directory.GetCurrentDirectory()}\\Articles\\{chapterTitle}\\{articles[article]}.zip";

            var array = File.ReadAllBytes(path);

            template = articles[article].Substring(articles[article].Length - 1);

            var model = _zipper.Unzip(array, template);

            model.Chapter = chapterTitle;

            return(model);
        }
        public static CalculationModel CalPriceLoadByID(long id)
        {
            CalculationModel model = null;
            DataTable        dt    = new DataTable();

            using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DBConnectionString"].ConnectionString))
            {
                using (SqlCommand cmd = new SqlCommand("cal_CalPriceGetByID", conn))
                {
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.Add(new SqlParameter("@PriceID", id));
                    conn.Open();

                    try
                    {
                        SqlDataReader drd = cmd.ExecuteReader();
                        dt.Load(drd);
                    }
                    catch { }

                    conn.Close();
                }
            }

            if (dt != null && dt.Rows.Count > 0)
            {
                string sEncodeJson = String.Concat(
                    dt.Rows[0]["JsonData1"],
                    dt.Rows[0]["JsonData2"],
                    dt.Rows[0]["JsonData3"],
                    dt.Rows[0]["JsonData4"],
                    dt.Rows[0]["JsonData5"],
                    dt.Rows[0]["JsonData6"],
                    dt.Rows[0]["JsonData7"],
                    dt.Rows[0]["JsonData8"],
                    dt.Rows[0]["JsonData9"],
                    dt.Rows[0]["JsonData10"]
                    );

                model = Utility.JsonToObject <CalculationModel>(Zipper.Unzip(Convert.FromBase64String(sEncodeJson)));
            }

            return(model);
        }
Ejemplo n.º 15
0
 //=============================================================================================
 public static T GetFromCache <T>(string key, T defaultValue = default)
 {
     try
     {
         //-----------------------------------------------------------------------------------------
         if (_StoredValues is null)
         {
             OnInitialAccess();
         }
         //-----------------------------------------------------------------------------------------
         if (_StoredValues.ContainsKey(key))
         {
             //------------------------------------------------------------------------------------------
             if (_ExpirationTimes[key] <= DateTime.Now)
             {
                 //------------------------------------------------------------------------------------------
                 _StoredValues.Remove(key);
                 _ExpirationTimes.Remove(key);
                 //------------------------------------------------------------------------------------------
                 return(defaultValue);
                 //------------------------------------------------------------------------------------------
             }
             //------------------------------------------------------------------------------------------
             byte[] zippedValue = _StoredValues[key];
             //------------------------------------------------------------------------------------------
             string strValue = Zipper.Unzip(zippedValue);
             T      value    = JsonConvert.DeserializeObject <T>(strValue);
             //------------------------------------------------------------------------------------------
             return(value);
             //------------------------------------------------------------------------------------------
         }
         else
         {
             return(defaultValue);
         }
         //---------------------------------------------------------------------------------------------
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
Ejemplo n.º 16
0
        static string TamperSomehow(string token)
        {
            var zipper = new Zipper();

            var zippedBytes = Convert.FromBase64String(token);

            var str = Encoding.ASCII.GetString(zipper.Unzip(zippedBytes));

            Console.WriteLine("Unzipped contents:");
            Console.WriteLine(str);
            Console.WriteLine();

            var parts = str.Split(new [] { "|" }, StringSplitOptions.RemoveEmptyEntries);

            var jsonText = Encoding.UTF8.GetString(Convert.FromBase64String(parts[0]));

            Console.WriteLine("First part as JSON:");
            Console.WriteLine(jsonText);
            Console.WriteLine();

            var tamperedJsonText = jsonText.Replace(@"""joe""", @"""moe""");

            Console.WriteLine("Tampered JSON:");
            Console.WriteLine(tamperedJsonText);
            Console.WriteLine();

            var newStr = Convert.ToBase64String(Encoding.UTF8.GetBytes(tamperedJsonText))
                         + "|"
                         + parts[1];

            Console.WriteLine("New unzipped contents:");
            Console.WriteLine(newStr);
            Console.WriteLine();

            var tamperedZippedBytes = zipper.Zip(Encoding.ASCII.GetBytes(newStr));

            return(Convert.ToBase64String(tamperedZippedBytes));
        }
        private void TitleSearchTextBoxTextChanged(object sender, EventArgs e)
        {
            if (String.IsNullOrWhiteSpace(TitleSearchTextBox.Text))
            {
                if (FoundArticles.List.Count != SearchResultsListBox.Items.Count)
                {
                    SearchResultsListClear();
                    CopyFoundArticles();
                }
            }
            else
            {
                SetElementsEnabled(false);
                SearchResultsListBox.Items.Clear();
                var list = FoundArticles.List
                           .Select(article => Zipper.Unzip(article.ZippedTitle.ToByteArray()))
                           .Where(title => !String.IsNullOrWhiteSpace(title) &&
                                  title.ToLower().IndexOf(TitleSearchTextBox.Text.ToLower()) != -1)
                           .ToList();

                var count         = 0;
                var temporaryList = new List <string>();
                SearchResultsListClear();
                foreach (var title in list)
                {
                    temporaryList.Add(title);
                    if (temporaryList.Count() > MaxSearchAppendCount)
                    {
                        SearchResultsListAppend(temporaryList.ToArray());
                        temporaryList.Clear();
                    }
                    SetProgressBarValue(count++);
                }
                SearchResultsListAppend(temporaryList.ToArray());
            }
        }
Ejemplo n.º 18
0
 /// <inheritdoc cref="IZipAdapter.Unzip"/>
 public void Unzip(FilePath zip, DirectoryPath target)
 {
     _zipper.Unzip(zip, target);
 }
Ejemplo n.º 19
0
        public static CrypterInfo Obsolete_DecryptFile120(string inputFilePath, string outputDirectory, string password)
        {
            Output.Print("DECRYPTING OBSOLETE 120: " + inputFilePath);

            Stopwatch stopwatch = new Stopwatch();

            stopwatch.Start();

            // Needed for return
            bool   isDirectory    = false;
            string userOutputPath = "";

            try
            {
                // DECRYPT PROCESS
                using (FileStream source = new FileStream(inputFilePath, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    // Récupération du Header
                    byte[] metadataHeader = new byte[_metadataHeaderLength]; // Simplement "MCryptEncryptedData_{taille d'octets à lire}"
                    source.Seek(-_metadataHeaderLength, SeekOrigin.End);
                    source.Read(metadataHeader, 0, _metadataHeaderLength);

                    // Vérification si ce fichier est bien un fichier MCrypt
                    try
                    {
                        string metadataHeaderStringCheck = Encoding.Default.GetString(metadataHeader);
                        //Console.WriteLine(metadataHeaderString);

                        if (metadataHeaderStringCheck.Split('|')[0] != "MCryptEncryptedData")
                        {
                            Output.Print("Metadata header incorrect. This is not a MCrypt file.", Level.Error);
                            throw new Exception();
                        }
                    }
                    catch // Si une erreur survient, c'est que ce n'est pas
                    {
                        source.Flush();
                        source.Close();
                        throw new NotMCryptFileException();
                    }
                    Output.Print("MCrypt file detected!");

                    // Récupération de la fin du Header pour avoir le nombre de caractères du Body
                    string metadataHeaderString = Encoding.Default.GetString(metadataHeader);

                    int metadataBodyLength = int.Parse(metadataHeaderString.Split('|')[1]);
                    Output.Print("Metadata Body Length: " + metadataBodyLength);

                    byte[] metadataBody = new byte[metadataBodyLength];
                    source.Seek(-metadataBodyLength - _metadataHeaderLength, SeekOrigin.Current);
                    source.Read(metadataBody, 0, metadataBodyLength);

                    string[] metadataBodyStringSplit = Encoding.Default.GetString(metadataBody).Split('|');


                    // RAPPEL du format de metadataBody de la 120: Version de MCrypt, Type[File/Directory], extension, Hash, Salt, Iterations, BatchesLength


                    // Vérification du mot de passe
                    string passwordHash = metadataBodyStringSplit[3];
                    if (!BCrypt.Net.BCrypt.EnhancedVerify(password, passwordHash))
                    {
                        throw new WrongPasswordException();
                    }
                    Output.Print("Correct password!");


                    // Build output path
                    // Manage encrypted directories
                    isDirectory    = bool.Parse(metadataBodyStringSplit[1]);
                    userOutputPath = Path.Combine(outputDirectory, metadataBodyStringSplit[2]); // The path for user output.
                    string outputFilePath;                                                      // The path for decryption output
                    if (!isDirectory)
                    {
                        Output.Print("Decrypting a file.");
                        outputFilePath = userOutputPath;
                    }
                    else
                    {
                        Output.Print("Decrypting a directory.");
                        outputFilePath = Files.GetTempFilePath();
                        Output.Print(string.Format("Decrypting zipped directory in temp file. ({0})", outputFilePath));
                    }

                    // Récupération du salt
                    byte[] salt = Encoding.Default.GetBytes(metadataBodyStringSplit[4]);

                    // Récupération des itérations
                    int iterations = int.Parse(metadataBodyStringSplit[5]);

                    // Récupération des Bacthes Length
                    Output.Print("Batches Length: " + metadataBodyStringSplit[6]);
                    string[] metadataReadBufferSizeStringSplit = metadataBodyStringSplit[6].Split('/');
                    long[]   readBatchesLength = new long[metadataReadBufferSizeStringSplit.Length - 1];
                    for (int i = 0; i < metadataReadBufferSizeStringSplit.Length - 1; i++) // (- 1 car le dernier est vide)
                    {
                        readBatchesLength[i] = long.Parse(metadataReadBufferSizeStringSplit[i]);
                    }


                    // Set Aes
                    AesManaged aes = new AesManaged();
                    aes.BlockSize = aes.LegalBlockSizes[0].MaxSize;
                    aes.KeySize   = aes.LegalKeySizes[0].MaxSize;

                    // Set key, iv & mode
                    // NB: Rfc2898DeriveBytes initialization and subsequent calls to   GetBytes   must be eactly the same, including order, on both the encryption and decryption sides.
                    Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(password, salt, iterations);
                    aes.Key     = key.GetBytes(aes.KeySize / 8);
                    aes.IV      = key.GetBytes(aes.BlockSize / 8);
                    aes.Mode    = CipherMode.CBC;
                    aes.Padding = PaddingMode.PKCS7;

                    // Create decryptor
                    ICryptoTransform transform = aes.CreateDecryptor(aes.Key, aes.IV);


                    // Décryptage

                    using (FileStream destination = new FileStream(outputFilePath, FileMode.Create, FileAccess.Write, FileShare.Read))
                    {
                        // Remise à zéro du flux !!!
                        source.Seek(0, SeekOrigin.Begin);

                        long   readBytes      = 0;
                        long   totalReadBytes = source.Length - (_metadataHeaderLength + metadataBodyLength);
                        double batchesNumber  = readBatchesLength.Length;
                        Output.Print("Total bytes to decrypt: " + totalReadBytes);
                        Output.Print("Number of batches: " + batchesNumber);

                        int  batches        = 0;
                        long decryptedBytes = 0;

                        Output.Print("Decrypting batches...");

                        for (int i = 0; i < batchesNumber; i++)
                        {
                            using (MemoryStream ms = new MemoryStream())
                            {
                                using (CryptoStream cryptoStream = new CryptoStream(ms, transform, CryptoStreamMode.Write)) // we create a cryptoStream for each batch (because it's of single use)
                                {
                                    int bytesToRead = (int)readBatchesLength[i];

                                    byte[] readBuffer = new byte[bytesToRead];
                                    source.Read(readBuffer, 0, bytesToRead);
                                    cryptoStream.Write(readBuffer, 0, bytesToRead);

                                    cryptoStream.FlushFinalBlock();
                                    readBytes += bytesToRead;

                                    decryptedBytes += ms.Length;

                                    destination.Write(ms.ToArray(), 0, (int)ms.Length);
                                    ms.Flush();
                                }
                            }

                            batches++;
                            Output.Print(string.Format("Batch number {0} / {1} done. ({2} bytes)", batches, batchesNumber, readBatchesLength[i]));

                            GC.Collect(); // Nécessaire !!!!!
                        }

                        Output.Print(string.Format("Total decrypted bytes: {0}", decryptedBytes));
                    }


                    if (isDirectory)
                    {
                        Zipper.Unzip(outputFilePath, userOutputPath);
                        Files.OptimalFileDelete(outputFilePath);
                        Output.Print("Unzipped and deleted temp file containing directory.");
                    }
                }

                Output.Print("Decryption successful!");
            }
            catch (WrongPasswordException e)
            {
                throw e;
            }
            catch (Exception e)
            {
                throw new DecryptException(e.Message, e.InnerException);
            }
            finally
            {
                stopwatch.Stop();
                Output.Print(string.Format("Operation ended in {0} .", stopwatch.Elapsed));
            }

            return(new CrypterInfo(userOutputPath, isDirectory, CompressionMode.None)); // Il n'y avait pas de compression à cette époque
        }