Beispiel #1
0
        public void MixedUpdateTest()
        {
            Adler32 checksum = new Adler32();
            int     i        = 0;

            checksum.Reset();

            while (i < LicenseData.Length / 4)
            {
                checksum.Update(LicenseData[i++]);
            }

            for (int j = 0; j < 2; j++)
            {
                checksum.Update(LicenseData, i, LicenseData.Length / 4);
                i += LicenseData.Length / 4;
            }

            while (i < LicenseData.Length)
            {
                checksum.Update(LicenseData[i++]);
            }

            Assert.AreEqual(LicenseChecksum, checksum.Value);
        }
Beispiel #2
0
        /// <summary>
        /// Sets the preset dictionary.  This should only be called, if
        /// needsDictionary() returns true and it should set the same
        /// dictionary, that was used for deflating.  The getAdler()
        /// function returns the checksum of the dictionary needed.
        /// </summary>
        /// <param name="buffer">
        /// The dictionary.
        /// </param>
        /// <param name="index">
        /// The index into buffer where the dictionary starts.
        /// </param>
        /// <param name="count">
        /// The number of bytes in the dictionary.
        /// </param>
        /// <exception cref="InvalidOperationException">
        /// No dictionary is needed.
        /// </exception>
        /// <exception cref="SharpZipBaseException">
        /// The adler checksum for the buffer is invalid
        /// </exception>
        public void SetDictionary(byte[] buffer, int index, int count)
        {
            if (buffer == null)
            {
                throw new ArgumentNullException(nameof(buffer));
            }

            if (index < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(index));
            }

            if (count < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(count));
            }

            if (!IsNeedingDictionary)
            {
                throw new InvalidOperationException("Dictionary is not needed");
            }

            adler?.Update(new ArraySegment <byte>(buffer, index, count));

            if (adler != null && (int)adler.Value != readAdler)
            {
                throw new SharpZipBaseException("Wrong adler checksum");
            }
            adler?.Reset();
            outputWindow.CopyDict(buffer, index, count);
            mode = DECODE_BLOCKS;
        }
Beispiel #3
0
        /// <summary>
        /// Fill the window
        /// </summary>
        public void FillWindow()
        {
            /* If the window is almost full and there is insufficient lookahead,
             * move the upper half to the lower one to make room in the upper half.
             */
            if (strstart >= WSIZE + MAX_DIST)
            {
                SlideWindow();
            }

            /* If there is not enough lookahead, but still some input left,
             * read in the input
             */
            while (lookahead < DeflaterConstants.MIN_LOOKAHEAD && inputOff < inputEnd)
            {
                int more = 2 * WSIZE - lookahead - strstart;

                if (more > inputEnd - inputOff)
                {
                    more = inputEnd - inputOff;
                }

                System.Array.Copy(inputBuf, inputOff, window, strstart + lookahead, more);
                adler.Update(inputBuf, inputOff, more);

                inputOff  += more;
                totalIn   += more;
                lookahead += more;
            }

            if (lookahead >= MIN_MATCH)
            {
                UpdateHash();
            }
        }
Beispiel #4
0
        public void Adler_32_Performance()
        {
            var rand = new Random(1);

            var buffer = new byte[BufferSize];

            rand.NextBytes(buffer);

            var adler = new Adler32();

            Assert.AreEqual(0x00000001, adler.Value);

            var sw = new Stopwatch();

            sw.Start();

            adler.Update(buffer);

            sw.Stop();
            Console.WriteLine($"Adler32 Hashing of 256 MiB: {sw.Elapsed.TotalSeconds:f4} second(s)");

            adler.Update(check);
            Assert.AreEqual(0xD4897DA3, adler.Value);

            exceptionTesting(adler);
        }
Beispiel #5
0
        public void TestChecksum()
        {
            byte[] arr1 =
            {
                0x2C, 0x00, 0x00, 0x00, 0x2C, 0x00, 0x00, 0x00, 0xBD, 0x8C, 0x08, 0x00, 0x19, 0x31, 0x08, 0x00,
                0xD1, 0xAF, 0x08, 0x00, 0x69, 0x0F, 0x08, 0x00, 0xF4, 0xAF, 0x08, 0x00, 0x66, 0x94, 0x00, 0x05
            };
            byte[]  arr2    = { 0x1F, 0x0F, 0x08, 0x00, 0xD6, 0xAF, 0x08, 0x00, 0xC0, 0x82, 0x20, 0x00 };
            Adler32 adler32 = new Adler32();

            adler32.Update(arr1);
            adler32.Update(arr2);
            Debug.WriteLine(adler32.Checksum.ToString("X8"));
            Assert.AreEqual(0xC02709D3, adler32.Checksum);

            arr1 = new byte[]
            {
                0x2C, 0x00, 0x00, 0x00, 0x2C, 0x00, 0x00, 0x00, 0xBD, 0x8C, 0x08, 0x00, 0x19, 0x31, 0x08, 0x00,
                0xD1, 0xAF, 0x08, 0x00, 0x69, 0x0F, 0x08, 0x00, 0xF4, 0xAF, 0x08, 0x00, 0x66, 0x94, 0x00, 0x00
            };
            arr2 = new byte[]
            { 0xAB, 0x0F, 0x08, 0x00, 0xD6, 0xAF, 0x08, 0x00, 0xC0, 0x82, 0x20, 0x00 };
            adler32.Reset();
            adler32.Update(arr1);
            adler32.Update(arr2);
            Debug.WriteLine(adler32.Checksum.ToString("X8"));
        }
Beispiel #6
0
        /// <summary>
        /// Sets the preset dictionary.  This should only be called, if
        /// needsDictionary() returns true and it should set the same
        /// dictionary, that was used for deflating.  The getAdler()
        /// function returns the checksum of the dictionary needed.
        /// </summary>
        /// <param name="buffer">
        /// The dictionary.
        /// </param>
        /// <param name="index">
        /// The index into buffer where the dictionary starts.
        /// </param>
        /// <param name="count">
        /// The number of bytes in the dictionary.
        /// </param>
        /// <exception cref="System.InvalidOperationException">
        /// No dictionary is needed.
        /// </exception>
        /// <exception cref="ApplicationException">
        /// The adler checksum for the buffer is invalid
        /// </exception>
        public void SetDictionary(byte[] buffer, int index, int count)
        {
            if (buffer == null)
            {
                throw new ArgumentNullException("buffer");
            }

            if (index < 0)
            {
                throw new ArgumentOutOfRangeException("index");
            }

            if (count < 0)
            {
                throw new ArgumentOutOfRangeException("count");
            }

            if (!IsNeedingDictionary)
            {
                throw new InvalidOperationException("Dictionary is not needed");
            }

            adler.Update(buffer, index, count);

            if ((int)adler.Value != readAdler)
            {
                throw new ApplicationException("Wrong adler checksum");
            }
            adler.Reset();
            outputWindow.CopyDict(buffer, index, count);
            mode = DECODE_BLOCKS;
        }
Beispiel #7
0
 public void SetDictionary(byte[] buffer, int index, int count)
 {
     //IL_0008: Unknown result type (might be due to invalid IL or missing references)
     //IL_0017: Unknown result type (might be due to invalid IL or missing references)
     //IL_0026: Unknown result type (might be due to invalid IL or missing references)
     //IL_0039: Unknown result type (might be due to invalid IL or missing references)
     if (buffer == null)
     {
         throw new ArgumentNullException("buffer");
     }
     if (index < 0)
     {
         throw new ArgumentOutOfRangeException("index");
     }
     if (count < 0)
     {
         throw new ArgumentOutOfRangeException("count");
     }
     if (!IsNeedingDictionary)
     {
         throw new InvalidOperationException("Dictionary is not needed");
     }
     adler.Update(buffer, index, count);
     if ((int)adler.Value != readAdler)
     {
         throw new SharpZipBaseException("Wrong adler checksum");
     }
     adler.Reset();
     outputWindow.CopyDict(buffer, index, count);
     mode = 2;
 }
Beispiel #8
0
		/// <summary>
		/// Sets the preset dictionary.  This should only be called, if
		/// needsDictionary() returns true and it should set the same
		/// dictionary, that was used for deflating.  The getAdler()
		/// function returns the checksum of the dictionary needed.
		/// </summary>
		/// <param name="buffer">
		/// The dictionary.
		/// </param>
		/// <param name="offset">
		/// The offset into buffer where the dictionary starts.
		/// </param>
		/// <param name="len">
		/// The length of the dictionary.
		/// </param>
		/// <exception cref="System.InvalidOperationException">
		/// No dictionary is needed.
		/// </exception>
		/// <exception cref="SharpZipBaseException">
		/// The adler checksum for the buffer is invalid
		/// </exception>
		public void SetDictionary(byte[] buffer, int offset, int len)
		{
			if (!IsNeedingDictionary) {
				throw new InvalidOperationException();
			}
			
			adler.Update(buffer, offset, len);
			if ((int)adler.Value != readAdler) {
				throw new SharpZipBaseException("Wrong adler checksum");
			}
			adler.Reset();
			outputWindow.CopyDict(buffer, offset, len);
			mode = DECODE_BLOCKS;
		}
Beispiel #9
0
        public int Inflate(byte[] buffer, int offset, int count)
        {
            if (buffer == null)
            {
                throw new ArgumentNullException("buffer");
            }
            if (count < 0)
            {
                throw new ArgumentOutOfRangeException("count", "count cannot be negative");
            }
            if (offset < 0)
            {
                throw new ArgumentOutOfRangeException("offset", "offset cannot be negative");
            }
            if ((offset + count) > buffer.Length)
            {
                throw new ArgumentException("count exceeds buffer bounds");
            }
            if (count == 0)
            {
                if (!IsFinished)
                {
                    Decode();
                }
                return(0);
            }
            int num = 0;

            do
            {
                if (mode != DECODE_CHKSUM)
                {
                    int num2 = outputWindow.CopyOutput(buffer, offset, count);
                    if (num2 > 0)
                    {
                        adler.Update(buffer, offset, num2);
                        offset   += num2;
                        num      += num2;
                        totalOut += num2;
                        count    -= num2;
                        if (count == 0)
                        {
                            return(num);
                        }
                    }
                }
            }while (Decode() || ((outputWindow.GetAvailable() > 0) && (mode != DECODE_CHKSUM)));
            return(num);
        }
        void UpdateHeader(BinaryWriter bw)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                BinaryWriter innerBw = new BinaryWriter(ms);
                innerBw.Write(keysOffsetsOffset);
                innerBw.Write(keysBlobOffset);
                innerBw.Write(stringsOffsetsOffset);
                innerBw.Write(stringsBlobOffset);
                innerBw.Write(streamsOffsetsOffset);
                innerBw.Write(streamsSizesOffset);
                innerBw.Write(streamsBlobOffset);
                innerBw.Write(rootOffset);
                innerBw.Flush();

                if (Version >= 3)
                {
                    Adler32 adler = new Adler32();
                    adler.Update(ms.ToArray());

                    if (Version >= 4)
                    {
                        using (MemoryStream secondMs = new MemoryStream())
                        {
                            BinaryWriter secondBw = new BinaryWriter(secondMs);
                            secondBw.Write(bStreamsOffsetsOffset);
                            secondBw.Write(bStreamsSizesOffset);
                            secondBw.Write(bStreamsBlobOffset);
                            secondBw.Flush();

                            adler.Update(secondMs.ToArray());

                            innerBw.Write((uint)adler.Value);
                            innerBw.Write(secondMs.ToArray());
                        }
                    }
                    else
                    {
                        innerBw.Write((uint)adler.Value);
                    }

                    ms.Flush();
                }

                bw.BaseStream.Seek(8, SeekOrigin.Begin);
                bw.Write(ms.ToArray());
            }
        }
Beispiel #11
0
        public MemoryStream ToShell(Stream stream, Dictionary <string, object> context = null)
        {
            bool fast = false;

            if (context != null && context.ContainsKey(FreeMount.PsbZlibFastCompress))
            {
                fast = (bool)context[FreeMount.PsbZlibFastCompress];
            }

            var          oriLen           = (int)stream.Length;
            var          pos              = stream.Position;
            var          compressedStream = ZlibCompress.CompressToStream(stream, fast);
            MemoryStream ms = new MemoryStream(16 + (int)compressedStream.Length);

            using (var bw = new BinaryWriter(ms, Encoding.UTF8, true))
            {
                stream.Position = pos;
                Adler32 checksumer = new Adler32();
                checksumer.Update(stream);
                var checksum = (uint)checksumer.Checksum;

                bw.Write(Signature);
                bw.Write((int)compressedStream.Length + 4);
                bw.Write(oriLen);
                bw.Write((int)0);
                compressedStream.CopyTo(ms);
                bw.WriteBE(checksum);
                compressedStream.Dispose();
            }

            ms.Position = 0;
            return(ms);
        }
Beispiel #12
0
        // Reads the body of a record from the PQDIF file.
        private RecordBody ReadRecordBody(int byteSize)
        {
            byte[]  bytes;
            Adler32 checksum;

            if (byteSize == 0)
            {
                return(null);
            }

            bytes = m_fileReader.ReadBytes(byteSize);

            checksum = new Adler32();
            checksum.Update(bytes);

            if (m_compressionAlgorithm == CompressionAlgorithm.Zlib && m_compressionStyle != CompressionStyle.None)
            {
                bytes = ZlibStream.UncompressBuffer(bytes);
            }

            using (MemoryStream stream = new MemoryStream(bytes))
                using (BinaryReader reader = new BinaryReader(stream))
                {
                    return(new RecordBody()
                    {
                        Collection = ReadCollection(reader),
                        Checksum = checksum.Value
                    });
                }
        }
Beispiel #13
0
        /// <summary>
        /// 获取指定数据的Adler32校验码
        /// </summary>
        /// <param name="buffer"></param>
        /// <param name="offset"></param>
        /// <param name="length"></param>
        /// <returns></returns>
        public static long Adler32CheckSum(this byte[] buffer, int offset, int length)
        {
            Adler32 adl = new Adler32();

            adl.Update(buffer, offset, length);
            return(adl.Checksum);
        }
Beispiel #14
0
        private void UnfilterRow(int nbytes)
        {
            int        ftn = rowbfilter[0];
            FilterType ft  = (FilterType)ftn;

            switch (ft)
            {
            case Hjg.Pngcs.FilterType.FILTER_NONE:
                UnfilterRowNone(nbytes);
                break;

            case Hjg.Pngcs.FilterType.FILTER_SUB:
                UnfilterRowSub(nbytes);
                break;

            case Hjg.Pngcs.FilterType.FILTER_UP:
                UnfilterRowUp(nbytes);
                break;

            case Hjg.Pngcs.FilterType.FILTER_AVERAGE:
                UnfilterRowAverage(nbytes);
                break;

            case Hjg.Pngcs.FilterType.FILTER_PAETH:
                UnfilterRowPaeth(nbytes);
                break;

            default:
                throw new PngjInputException("Filter type " + ftn + " not implemented");
            }
            if (crctest != null)
            {
                crctest.Update(rowb, 1, nbytes);
            }
        }
Beispiel #15
0
        /// <summary>
        /// Sets the preset dictionary.  This should only be called, if
        /// needsDictionary() returns true and it should set the same
        /// dictionary, that was used for deflating.  The getAdler()
        /// function returns the checksum of the dictionary needed.
        /// </summary>
        /// <param name="buffer">
        /// the dictionary.
        /// </param>
        /// <param name="off">
        /// the offset into buffer where the dictionary starts.
        /// </param>
        /// <param name="len">
        /// the length of the dictionary.
        /// </param>
        /// <exception cref="System.InvalidOperationException">
        /// if no dictionary is needed.
        /// </exception>
        /// <exception cref="System.ArgumentException">
        /// if the dictionary checksum is wrong.
        /// </exception>
        /// <exception cref="System.ArgumentOutOfRangeException">
        /// if the off and/or len are wrong.
        /// </exception>
        public void SetDictionary(byte[] buffer, int off, int len)
        {
            if (!NeedsDictionary())
            {
                throw new InvalidOperationException();
            }

            adler.Update(buffer, off, len);
            if ((int)adler.Value != readAdler)
            {
                throw new ArgumentException("Wrong adler checksum");
            }
            adler.Reset();
            outputWindow.CopyDict(buffer, off, len);
            mode = DECODE_BLOCKS;
        }
Beispiel #16
0
        public void UnfilterRow(int nbytes)
        {
            int num = rowbfilter[0];

            switch (num)
            {
            case 0:
                UnfilterRowNone(nbytes);
                break;

            case 1:
                UnfilterRowSub(nbytes);
                break;

            case 2:
                UnfilterRowUp(nbytes);
                break;

            case 3:
                UnfilterRowAverage(nbytes);
                break;

            case 4:
                UnfilterRowPaeth(nbytes);
                break;

            default:
                throw new PngjInputException("Filter type " + num.ToString() + " not implemented");
            }
            if (crctest != null)
            {
                crctest.Update(rowb, 1, nbytes);
            }
        }
Beispiel #17
0
        public static uint Adler32(byte[] buffer)
        {
            Adler32 adler32 = new Adler32();

            adler32.Update(buffer);
            return((uint)adler32.Value);
        }
        /// <summary>
        /// Compute
        /// </summary>
        /// <param name="bytesArray">Input data.</param>
        /// <param name="byteStart">The position to begin reading from.</param>
        /// <param name="bytesToRead">How many bytes in the bytesArray to read.</param>
        /// <returns></returns>
        public static uint Compute(byte[] bytesArray, int byteStart, int bytesToRead)
        {
            var adler32 = new Adler32();

            adler32.Update(bytesArray, byteStart, bytesToRead);
            return(adler32.Value);
        }
Beispiel #19
0
        /// <summary>Calculates the Adler-32 checksum on specified portion of a buffer.</summary>
        /// <param name="data">Data buffer to perform checksum on.</param>
        /// <param name="startIndex">Starts index in data buffer to begin checksum.</param>
        /// <param name="length">Total number of bytes from <paramref name="startIndex">startIndex</paramref> to
        /// perform checksum over.</param>
        /// <returns>Computed Adler-32 checksum over the specified portion of the buffer.</returns>
        public static uint Adler32Checksum(this byte[] data, int startIndex, int length)
        {
            Adler32 checksum = new Adler32();

            checksum.Update(data, startIndex, length);

            return(checksum.Value);
        }
        public void FillWindow()
        {
            while (lookahead < DeflaterConstants.MIN_LOOKAHEAD && inputOff < inputEnd)
            {
                int more = 2 * WSIZE - lookahead - strstart;

                /* If the window is almost full and there is insufficient lookahead,
                 * move the upper half to the lower one to make room in the upper half.
                 */
                if (strstart >= WSIZE + MAX_DIST)
                {
                    System.Array.Copy(window, WSIZE, window, 0, WSIZE);
                    matchStart -= WSIZE;
                    strstart   -= WSIZE;
                    blockStart -= WSIZE;

                    /* Slide the hash table (could be avoided with 32 bit values
                     * at the expense of memory usage).
                     */
                    for (int i = 0; i < HASH_SIZE; i++)
                    {
                        int m = head[i];
                        head[i] = m >= WSIZE ? (short)(m - WSIZE) : (short)0;
                    }
                    more += WSIZE;
                }

                if (more > inputEnd - inputOff)
                {
                    more = inputEnd - inputOff;
                }

                System.Array.Copy(inputBuf, inputOff,
                                  window, strstart + lookahead, more);
                adler.Update(inputBuf, inputOff, more);
                inputOff  += more;
                totalIn   += more;
                lookahead += more;

                if (lookahead >= MIN_MATCH)
                {
                    UpdateHash();
                }
            }
        }
Beispiel #21
0
    public static int Main(string[] args)
    {
        if (args.Length == 0)
        {
            ShowHelp();
            return(1);
        }

        var parser = new ArgumentParser(args);

        if (!File.Exists(file_))
        {
            Console.Error.WriteLine("Cannot find file {0}", file_);
            ShowHelp();
            return(1);
        }

        using (FileStream checksumStream = File.OpenRead(file_)) {
            byte[] buffer = new byte[4096];
            int    bytesRead;

            switch (parser.Command)
            {
            case Command.Help:
                ShowHelp();
                break;

            case Command.Crc32:
                var currentCrc = new Crc32();
                while ((bytesRead = checksumStream.Read(buffer, 0, buffer.Length)) > 0)
                {
                    currentCrc.Update(buffer, 0, bytesRead);
                }
                Console.WriteLine("CRC32 for {0} is 0x{1:X8}", args[0], currentCrc.Value);
                break;

            case Command.BZip2:
                var currentBZip2Crc = new BZip2Crc();
                while ((bytesRead = checksumStream.Read(buffer, 0, buffer.Length)) > 0)
                {
                    currentBZip2Crc.Update(buffer, 0, bytesRead);
                }
                Console.WriteLine("BZip2CRC32 for {0} is 0x{1:X8}", args[0], currentBZip2Crc.Value);
                break;

            case Command.Adler:
                var currentAdler = new Adler32();
                while ((bytesRead = checksumStream.Read(buffer, 0, buffer.Length)) > 0)
                {
                    currentAdler.Update(buffer, 0, bytesRead);
                }
                Console.WriteLine("Adler32 for {0} is 0x{1:X8}", args[0], currentAdler.Value);
                break;
            }
        }
        return(0);
    }
Beispiel #22
0
        public void UpdateByteTest()
        {
            Adler32 checksum = new Adler32();

            foreach (byte d in LicenseData)
            {
                checksum.Update(d);
            }

            Assert.AreEqual(LicenseChecksum, checksum.Value);
        }
Beispiel #23
0
        /// <summary>
        /// Save as pure MDF
        /// </summary>
        /// <param name="psb"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static byte[] SaveAsMdf(this PSB psb, uint?key = null)
        {
            psb.Merge();
            var     bytes    = psb.Build();
            Adler32 adler    = new Adler32();
            uint    checksum = 0;

            if (key == null)
            {
                adler.Update(bytes);
                checksum = (uint)adler.Checksum;
            }

            MemoryStream ms = new MemoryStream(bytes);

            using (MemoryStream fs = new MemoryStream())
            {
                if (key != null)
                {
                    MemoryStream nms = new MemoryStream((int)ms.Length);
                    PsbFile.Encode(key.Value, EncodeMode.Encrypt, EncodePosition.Auto, ms, nms);
                    ms.Dispose();
                    ms = nms;
                    var pos = ms.Position;
                    adler.Update(ms);
                    checksum    = (uint)adler.Checksum;
                    ms.Position = pos;
                }

                BinaryWriter bw = new BinaryWriter(fs);
                bw.WriteStringZeroTrim(MdfFile.Signature);
                bw.Write((uint)ms.Length);
                //bw.Write(ZlibCompress.Compress(ms));
                ZlibCompress.CompressToBinaryWriter(bw, ms);
                bw.WriteBE(checksum);
                ms.Dispose();
                bw.Flush();
                return(fs.ToArray());
            }
        }
        public void Adler_32()
        {
            var underTestAdler32 = new Adler32();
            Assert.AreEqual(0x00000001, underTestAdler32.Value);

            underTestAdler32.Update(check);
            Assert.AreEqual(0x091E01DE, underTestAdler32.Value);

            underTestAdler32.Reset();
            Assert.AreEqual(0x00000001, underTestAdler32.Value);

            exceptionTesting(underTestAdler32);
        }
Beispiel #25
0
 public void SetDictionary(byte[] buffer, int offset, int length)
 {
     adler.Update(buffer, offset, length);
     if (length >= 3)
     {
         if (length > 32506)
         {
             offset += length - 32506;
             length  = 32506;
         }
         global::System.Array.Copy((global::System.Array)buffer, offset, (global::System.Array)window, strstart, length);
         UpdateHash();
         length--;
         while (--length > 0)
         {
             InsertString();
             strstart++;
         }
         strstart  += 2;
         blockStart = strstart;
     }
 }
Beispiel #26
0
        /*
         * val= 3066839698
         * val= 0
         * val= 3799812176 t=14446
         */
        static public void testCRC32()
        {
            CRC32 crc1 = new CRC32();

            crc1.Update(new byte[] { 1, 2 });
            if (crc1.GetValue() != 3066839698)
            {
                throw new Exception("Bad CRC32!");
            }
            Console.WriteLine("Testing CRC32");
            Console.WriteLine("val= " + crc1.GetValue());
            crc1.Reset();
            Console.WriteLine("val= " + crc1.GetValue());
            if (crc1.GetValue() != 0)
            {
                throw new Exception("Bad CRC32!!");
            }
            Random r = new Random();

            byte[] all = new byte[2000 * 4];
            long   t0  = Environment.TickCount;

            for (int n = 0; n < 2000; n++)
            {
                byte[] b      = createBytes7(n < 50 ? n : n * n - 7);
                CRC32  crc    = new CRC32();
                int    offset = 0;
                while (offset < b.Length)
                {
                    int len = r.Next(b.Length - offset) + 1;
                    crc.Update(b, offset, len);
                    offset += len;
                }
                long x = crc.GetValue();
                all[n * 4]     = (byte)((x >> 24) & 0xff);
                all[n * 4 + 1] = (byte)((x >> 16) & 0xff);
                all[n * 4 + 2] = (byte)((x >> 8) & 0xff);
                all[n * 4 + 3] = (byte)((x) & 0xff);
            }
            long    t1 = Environment.TickCount;
            Adler32 a  = new Adler32();

            a.Update(all);
            long v = a.GetValue();

            Console.WriteLine("val= " + v + " t=" + (t1 - t0));
            if (v != 3799812176)
            {
                throw new Exception("Bad cRC32");                 // tested with Java CRC32
            }
        }
        byte[] VerifyHeader()
        {
            int headerLength = 8 * 4;

            if (Version >= 3)
            {
                headerLength += 4;
                if (Version >= 4)
                {
                    headerLength += 3 * 4;
                }
            }
            byte[] headerBytes = br.ReadBytes(headerLength);

            if (Version >= 3)
            {
                if (filter != null && (Flags & PsbFlags.HeaderFiltered) != 0)
                {
                    filter.Filter(headerBytes);
                }
                uint headerChecksum = BitConverter.ToUInt32(headerBytes, 0x20);

                // This is probably actually for checking that the header was decrypted successfully
                Adler32 adler = new Adler32();
                adler.Update(new ArraySegment <byte>(headerBytes, 0, 0x20));
                if (Version >= 4)
                {
                    adler.Update(new ArraySegment <byte>(headerBytes, 0x24, 0x0c));
                }
                if (adler.Value != headerChecksum)
                {
                    throw new InvalidDataException("Header checksum mismatch");
                }
            }

            return(headerBytes);
        }
Beispiel #28
0
        /// <summary>
        /// Save PSB as MDF file
        /// </summary>
        /// <param name="psb"></param>
        /// <param name="path"></param>
        /// <param name="key"></param>
        public static void SaveAsMdfFile(this PSB psb, string path, uint?key = null)
        {
            psb.Merge();
            var     bytes      = psb.Build();
            Adler32 checksumer = new Adler32();
            uint    checksum   = 0;

            if (key == null)
            {
                checksumer.Update(bytes);
                checksum = (uint)checksumer.Checksum;
            }
            MemoryStream ms = new MemoryStream(bytes);

            using (Stream fs = new FileStream(path, FileMode.Create))
            {
                if (key != null)
                {
                    MemoryStream nms = new MemoryStream((int)ms.Length);
                    PsbFile.Encode(key.Value, EncodeMode.Encrypt, EncodePosition.Auto, ms, nms);
                    ms.Dispose();
                    ms = nms;
                    var pos = ms.Position;
                    checksumer.Update(ms);
                    checksum    = (uint)checksumer.Checksum;
                    ms.Position = pos;
                }

                BinaryWriter bw = new BinaryWriter(fs);
                bw.WriteStringZeroTrim(MdfFile.Signature);
                bw.Write((uint)ms.Length);
                bw.Write(ZlibCompress.Compress(ms));
                bw.WriteBE(checksum);
                ms.Dispose();
                bw.Flush();
            }
        }
Beispiel #29
0
 public void FillWindow()
 {
     if (strstart >= 0xfefa)
     {
         SlideWindow();
     }
     while ((lookahead < 0x106) && (inputOff < inputEnd))
     {
         int length = (0x10000 - lookahead) - strstart;
         if (length > (inputEnd - inputOff))
         {
             length = inputEnd - inputOff;
         }
         Array.Copy(inputBuf, inputOff, window, strstart + lookahead, length);
         adler.Update(inputBuf, inputOff, length);
         inputOff  += length;
         totalIn   += length;
         lookahead += length;
     }
     if (lookahead >= 3)
     {
         UpdateHash();
     }
 }
Beispiel #30
0
        uint CheckedCopy(Stream src, Stream dst)
        {
            var checksum    = new Adler32();
            var read_buffer = new byte[81920];

            for (;;)
            {
                int read = src.Read(read_buffer, 0, read_buffer.Length);
                if (0 == read)
                {
                    break;
                }
                checksum.Update(read_buffer, 0, read);
                dst.Write(read_buffer, 0, read);
            }
            return(checksum.Value);
        }
Beispiel #31
-1
        /// <summary>Calculates the Adler32 check-sum on specified portion of a buffer.</summary>
        /// <param name="data">Data buffer to perform check-sum on.</param>
        /// <param name="startIndex">Starts index in data buffer to begin check-sum.</param>
        /// <param name="length">Total number of bytes from <paramref name="startIndex">startIndex</paramref> to
        /// perform check-sum over.</param>
        /// <remarks>
        /// <para>
        /// Computes Adler32 checksum for a stream of data. An Adler32 checksum is not as reliable as a CRC32
        /// checksum, but a lot faster to compute.
        /// </para>
        /// <para>
        /// The specification for Adler32 may be found in RFC 1950. ZLIB Compressed Data Format Specification
        /// version 3.3.
        /// </para>
        /// </remarks>
        /// <returns>Computed Adler32 checksum over the specified portion of the buffer.</returns>
        public static uint Adler32Checksum(this byte[] data, int startIndex, int length)
        {
            Adler32 checksum = new Adler32();

            checksum.Update(data, startIndex, length);

            return checksum.Value;
        }
Beispiel #32
-1
        public void UpdateByteTest()
        {
            Adler32 checksum = new Adler32();

            foreach (byte d in LicenseData)
                checksum.Update(d);

            Assert.AreEqual(LicenseChecksum, checksum.Value);
        }
Beispiel #33
-1
        public void MixedUpdateTest()
        {
            Adler32 checksum = new Adler32();
            int i = 0;

            checksum.Reset();

            while (i < LicenseData.Length / 4)
                checksum.Update(LicenseData[i++]);

            for (int j = 0; j < 2; j++)
            {
                checksum.Update(LicenseData, i, LicenseData.Length / 4);
                i += LicenseData.Length / 4;
            }

            while (i < LicenseData.Length)
                checksum.Update(LicenseData[i++]);

            Assert.AreEqual(LicenseChecksum, checksum.Value);
        }