示例#1
0
        /// <summary>
        /// calculate and return CRC-32 from given text
        /// </summary>
        /// <param name="text">input text</param>
        /// <returns>CRC-32 uint</returns>
        public static uint Crc32(string text)
        {
            Crc32Algorithm crc = new Crc32Algorithm();

            byte[] buffer = Encoding.ASCII.GetBytes(text);
            return(BitConverter.ToUInt32(crc.ComputeHash(buffer).Reverse().ToArray(), 0));
        }
示例#2
0
        private static string GetCRC32SumFromFile(string fileName)
        {
            var crc = new Crc32Algorithm();
            var sb  = new StringBuilder();

            try
            {
                using (FileStream fs = File.Open(fileName, FileMode.Open, FileAccess.Read))
                {
                    foreach (byte b in crc.ComputeHash(fs))
                    {
                        sb.Append(b.ToString("x2").ToLower());
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error(
                    ex,
                    "Error reading file {0} for CRC32 checksum generation",
                    fileName);
                throw;
            }

            return(sb.ToString());
        }
示例#3
0
        public static string Crc32Hash(string rawData)
        {
            Crc32Algorithm hasher = new Crc32Algorithm();
            var            ret    = string.Format("{0:X8}", BitConverter.ToUInt32(hasher.ComputeHash(Encoding.UTF8.GetBytes(rawData)).Reverse().ToArray()));

            return(ret);
        }
示例#4
0
        public void Benchmark()
        {
            var rnd = new Random();
            var fb  = new byte [1920 * 1080 * 4];

            rnd.NextBytes(fb);

            while (true)
            {
                // Initialized 1920x1080x4 framebuffer
                var start = DateTime.Now;
                // var crc32 = new Crc32CAlgorithm ();
                var crc32 = new Crc32Algorithm();
                for (int i = 0; i < 60; ++i)
                {
                    crc32.ComputeHash(fb);
                }

                long elapsedTicks = DateTime.Now.Ticks - start.Ticks;
                var  elapsedSpan  = new TimeSpan(elapsedTicks);

                Console.WriteLine("   {0:N0} nanoseconds", elapsedTicks * 100);
                Console.WriteLine("   {0:N0} ticks", elapsedTicks);
                Console.WriteLine("   {0:N3} seconds", elapsedSpan.TotalSeconds);
                Console.WriteLine("   {0:N2} minutes", elapsedSpan.TotalMinutes);
                Console.WriteLine("   {0:N0} days, {1} hours, {2} minutes, {3} seconds",
                                  elapsedSpan.Days, elapsedSpan.Hours,
                                  elapsedSpan.Minutes, elapsedSpan.Seconds);
            }
        }
示例#5
0
        public static uint ComputeCrc32(byte[] data)
        {
            var algorithm    = new Crc32Algorithm();
            var crc32AsBytes = algorithm.ComputeHash(data);

            return(BitConverter.ToUInt32(crc32AsBytes, 0));
        }
示例#6
0
        public static byte[] ComputeCRC32Bytes(FileInfo sourceFile)
        {
            using var source = sourceFile.OpenRead();

            var crc32     = new Crc32Algorithm();
            var hashBytes = crc32.ComputeHash(source);

            return(hashBytes);
        }
示例#7
0
        public static uint ComputeCRC32(FileInfo sourceFile)
        {
            using var source = sourceFile.OpenRead();

            var crc32     = new Crc32Algorithm();
            var hashBytes = crc32.ComputeHash(source);

            uint hash = hashBytes[0] + ((uint)hashBytes[1] << 8) + ((uint)hashBytes[2] << 16) + ((uint)hashBytes[3] << 24);

            return(hash);
        }
        public void FileCRCTest()
        {
            const string path = @"..\..\..\[CRC Sample]\VIDEO_TS [57FD7F1E].IFO";
            var          hash = new Crc32Algorithm();

            using (var file = File.OpenRead(path))
            {
                var crcByte = hash.ComputeHash(file);
                var calCRC  = (uint)crcByte[0] << 24 | (uint)crcByte[1] << 16 | (uint)crcByte[2] << 8 | crcByte[3];
                CRC32.FindCRC(path, out var fileCRC);
                Console.WriteLine($@"{fileCRC} {calCRC}");
                Assert.IsTrue(calCRC == fileCRC);
            }
        }
示例#9
0
        public static string GetHash(string path, Hash hashType, bool log = true, bool quick = true)
        {
            Benchmarker.Start();
            string hashStr = "";

            if (IsPathDirectory(path))
            {
                Logger.Log($"Path '{path}' is directory! Returning empty hash.", true);
                return(hashStr);
            }
            try
            {
                var stream = File.OpenRead(path);

                if (hashType == Hash.MD5)
                {
                    MD5 md5  = MD5.Create();
                    var hash = md5.ComputeHash(stream);
                    hashStr = BitConverter.ToString(hash).Replace("-", "").ToLowerInvariant();
                }

                if (hashType == Hash.CRC32)
                {
                    var crc        = new Crc32Algorithm();
                    var crc32bytes = crc.ComputeHash(stream);
                    hashStr = BitConverter.ToUInt32(crc32bytes, 0).ToString();
                }

                if (hashType == Hash.xxHash)
                {
                    ulong xxh64 = xxHash64.ComputeHash(stream, 8192, (ulong)GetFilesize(path));
                    hashStr = xxh64.ToString();
                }

                stream.Close();
            }
            catch (Exception e)
            {
                Logger.Log($"Error getting file hash for {Path.GetFileName(path)}: {e.Message}", true);
                return("");
            }
            if (log)
            {
                Logger.Log($"Computed {hashType} for '{Path.GetFileNameWithoutExtension(path).Trunc(40) + Path.GetExtension(path)}' ({GetFilesizeStr(path)}) in {Benchmarker.GetTimeStr(true)}: {hashStr}", true);
            }
            return(hashStr);
        }
示例#10
0
        public static uint GetCrc32FromBytes(byte[] bytes)
        {
            if (bytes == null || bytes.Length <= 0)
            {
                throw new ArgumentException(@"Is Null Or Empty!", nameof(bytes));
            }

            uint retVal;

            using (var crc32Algo = new Crc32Algorithm())
            {
                var result = crc32Algo.ComputeHash(bytes);
                Array.Reverse(result);
                retVal = BitConverter.ToUInt32(result, 0);
            }
            return(retVal);
        }
示例#11
0
        public byte[] GetSatoshiUploadedBytes()
        {
            var data = new List <byte>();

            foreach (var txOut in Outs)
            {
                data.AddRange(txOut.Script.Inner);
            }

            if (data.Count < 8)
            {
                return(null);
            }

            var header = data.GetRange(0, 8).ToArray();

            // Now check headers

            var length = header.ToInt32(0);

            if (length <= 0 || length > data.Count - 8)
            {
                return(null);
            }

            var section = data.GetRange(8, length);

            var crc  = new Crc32Algorithm();
            var hash = crc.ComputeHash(section.ToArray());

            // Weird comparison is an Endian problem

            if (hash[0] != header[7] || hash[1] != header[6] || hash[2] != header[5] || hash[3] != header[4])
            {
                return(null);
            }

            return(data.GetRange(8, length).ToArray());
        }
示例#12
0
        public static uint GetCrc32File(string fileName)
        {
            if (!File.Exists(fileName))
            {
                throw new FileNotFoundException($"File '{fileName}' not found!", fileName);
            }

            uint retVal;

            using (var fs = File.Open(fileName, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                using (var crc32Algo = new Crc32Algorithm())
                {
                    var result = crc32Algo.ComputeHash(fs);
                    Array.Reverse(result);

                    retVal = BitConverter.ToUInt32(result, 0);
                }
            }

            return(retVal);
        }
示例#13
0
        internal static SumResult CalculateSums(string file)
        {
            SumResult result = new SumResult();

            try
            {
                if (File.Exists(file))
                {
                    result.File = file;

                    if (Options.CurrentOptions.HashOptions.MD5)
                    {
                        using (FileStream fs = File.OpenRead(file))
                        {
                            using (var md5 = new MD5CryptoServiceProvider())
                            {
                                result.MD5 = BitConverter.ToString(md5.ComputeHash(fs)).Replace("-", string.Empty);
                            }
                        }
                    }

                    if (Options.CurrentOptions.HashOptions.SHA1)
                    {
                        using (FileStream fs = File.OpenRead(file))
                        {
                            using (var sha1 = new SHA1CryptoServiceProvider())
                            {
                                result.SHA1 = BitConverter.ToString(sha1.ComputeHash(fs)).Replace("-", string.Empty);
                            }
                        }
                    }

                    if (Options.CurrentOptions.HashOptions.SHA256)
                    {
                        using (FileStream fs = File.OpenRead(file))
                        {
                            using (var sha256 = new SHA256CryptoServiceProvider())
                            {
                                result.SHA256 = BitConverter.ToString(sha256.ComputeHash(fs)).Replace("-", string.Empty);
                            }
                        }
                    }

                    if (Options.CurrentOptions.HashOptions.SHA384)
                    {
                        using (FileStream fs = File.OpenRead(file))
                        {
                            using (var sha384 = new SHA384CryptoServiceProvider())
                            {
                                result.SHA384 = BitConverter.ToString(sha384.ComputeHash(fs)).Replace("-", string.Empty);
                            }
                        }
                    }

                    if (Options.CurrentOptions.HashOptions.SHA512)
                    {
                        using (FileStream fs = File.OpenRead(file))
                        {
                            using (var sha512 = new SHA512CryptoServiceProvider())
                            {
                                result.SHA512 = BitConverter.ToString(sha512.ComputeHash(fs)).Replace("-", string.Empty);
                            }
                        }
                    }

                    if (Options.CurrentOptions.HashOptions.CRC32)
                    {
                        using (FileStream fs = File.OpenRead(file))
                        {
                            using (var crc32 = new Crc32Algorithm())
                            {
                                result.CRC32 = BitConverter.ToString(crc32.ComputeHash(fs)).Replace("-", string.Empty);

                                if (Options.CurrentOptions.CRC32Decimal)
                                {
                                    result.CRC32 = Convert.ToInt64(result.CRC32, 16).ToString();
                                }
                            }
                        }
                    }

                    if (Options.CurrentOptions.HashOptions.RIPEMD160)
                    {
                        using (FileStream fs = File.OpenRead(file))
                        {
                            using (var ripemd160 = RIPEMD160.Create())
                            {
                                result.RIPEMD160 = BitConverter.ToString(ripemd160.ComputeHash(fs)).Replace("-", string.Empty);
                            }
                        }
                    }

                    if (Options.CurrentOptions.HashOptions.SHA3_256)
                    {
                        using (FileStream fs = File.OpenRead(file))
                        {
                            using (var h = Sha3.Sha3256())
                            {
                                result.SHA3_256 = BitConverter.ToString(h.ComputeHash(fs)).Replace("-", string.Empty);
                            }
                        }
                    }

                    if (Options.CurrentOptions.HashOptions.SHA3_384)
                    {
                        using (FileStream fs = File.OpenRead(file))
                        {
                            using (var h = Sha3.Sha3384())
                            {
                                result.SHA3_384 = BitConverter.ToString(h.ComputeHash(fs)).Replace("-", string.Empty);
                            }
                        }
                    }

                    if (Options.CurrentOptions.HashOptions.SHA3_512)
                    {
                        using (FileStream fs = File.OpenRead(file))
                        {
                            using (var h = Sha3.Sha3512())
                            {
                                result.SHA3_512 = BitConverter.ToString(h.ComputeHash(fs)).Replace("-", string.Empty);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                result = null;
                MessageBox.Show(ex.Message, "Hash Error", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }

            if (Options.CurrentOptions.LowerCasing)
            {
                result.ConvertToLowerCasing();
            }
            else
            {
                result.ConvertToUpperCasing();
            }

            return(result);
        }
示例#14
0
 public override string GenerateHash(string value)
 {
     return(HashBytesToString(_hasher.ComputeHash(Encoding.GetBytes(value))));
 }
示例#15
0
        public static List <Frame> DecodeFrameBuffer(byte[] buffer, int offset, int available, out int newOffset, out int newAvailable)
        {
            if (buffer == null)
            {
                throw new ArgumentNullException();
            }

            var frames = new List <Frame>();

            newOffset    = offset;
            newAvailable = available;

            // do we have the minimum - empty payload no extended
            var minBytes = BREADCRUMB_BYTES + LENGTH_BYTES + TYPE_BYTES + POFF_BYTES + CRC_BYTES;

            if (available < minBytes)
            {
                return(frames);
            }

            // while there's still data available in the buffer
            while (available > 0)
            {
                // breadcrumb
                if (buffer[offset] != (byte)'I' ||
                    buffer[offset + 1] != (byte)'N' ||
                    buffer[offset + 2] != (byte)'T' ||
                    buffer[offset + 3] != (byte)'E' ||
                    buffer[offset + 4] != (byte)'R' ||
                    buffer[offset + 5] != (byte)'C')
                {
                    available--;
                    offset++;
                    continue;
                }

                // length
                var length = BitConverter.ToUInt32(buffer, offset + BREADCRUMB_BYTES);
                if (available < length)
                {
                    // exit
                    break;
                }

                // CRC (end) - validate data not corrupt FIRST
                var frameCrc = new byte[CRC_BYTES];
                Array.Copy(buffer, offset + length - 4, frameCrc, 0, frameCrc.Length);
                var calculatedCrc = _crc32.ComputeHash(buffer, offset, (int)length - CRC_BYTES);
                if (!frameCrc.SequenceEqual(calculatedCrc))
                {
                    // going to re-search for next packet - if corrupt don't know how/where it's been corrupted (nor can we trust length)
                    available--;
                    offset++;
                    continue;
                }

                // type
                var type = (FrameType)buffer[offset + BREADCRUMB_BYTES + LENGTH_BYTES];

                // POFF
                var  extheaderLength = buffer[offset + BREADCRUMB_BYTES + LENGTH_BYTES + TYPE_BYTES] * 4;
                uint sessionId       = 0;
                uint messageId       = 0;

                if (extheaderLength > 0)
                {
                    // sessionId
                    sessionId = BitConverter.ToUInt32(buffer, offset + BREADCRUMB_BYTES + LENGTH_BYTES + TYPE_BYTES + POFF_BYTES);

                    // messageId
                    messageId = BitConverter.ToUInt32(buffer, offset + BREADCRUMB_BYTES + LENGTH_BYTES + TYPE_BYTES + POFF_BYTES + SESSION_ID_BYTES);
                }

                // payload
                var payloadLength = length - (BREADCRUMB_BYTES + LENGTH_BYTES + TYPE_BYTES + POFF_BYTES + extheaderLength + CRC_BYTES);
                var payloadBytes  = new byte[payloadLength];
                Array.Copy(buffer, offset + BREADCRUMB_BYTES + LENGTH_BYTES + TYPE_BYTES + POFF_BYTES + extheaderLength, payloadBytes, 0, payloadLength);

                // create and add the frame
                var frame = new Frame
                {
                    Length    = length,
                    Type      = type,
                    SessionID = sessionId,
                    MessageID = messageId,
                    Payload   = payloadBytes
                };

                frames.Add(frame);

                // move pointers
                available -= (int)length;
                offset    += (int)length;
            }

            if (available == 0)
            {
                // move pointer to beginning of buffer
                offset = 0;
            }

            newOffset    = offset;
            newAvailable = available;

            return(frames);
        }
示例#16
0
        static void Main(string[] args)
        {
            Console.Write("Version actuelle : ");
            var currentVersion = Console.ReadLine();

            Console.Write("Nouvelle version : ");
            var nextVersion = Console.ReadLine();

            var patchFileName = "dofus_" + currentVersion + "_to_" + nextVersion + ".zip";

            using (var stream = new FileStream("./input/games.xml", FileMode.Create))
            {
                var serializer = new XmlSerializer(typeof(GamesConfigurations));
                serializer.Serialize(stream, new GamesConfigurations()
                {
                    dofus = new dofus()
                    {
                        version = nextVersion
                    }
                });
            }

            var fullPath = new Uri(Path.GetFullPath("./input/"));
            var files    = new List <file>();

            foreach (var file in Directory.GetFiles("./input", "*.*", SearchOption.AllDirectories))
            {
                Console.WriteLine("#########");
                var            infos = new FileInfo(file);
                Crc32Algorithm crc32 = new Crc32Algorithm();
                StringBuilder  hash  = new StringBuilder();

                using (FileStream fs = File.Open(file, FileMode.Open))
                    foreach (byte b in crc32.ComputeHash(fs))
                    {
                        hash.Append(b.ToString("x2").ToLower());
                    }

                var fileUri = new Uri(infos.FullName);

                files.Add(new file()
                {
                    nameTo   = "./" + fullPath.MakeRelativeUri(fileUri).ToString(),
                    nameFrom = fullPath.MakeRelativeUri(fileUri).ToString(),
                    action   = "add",
                    crc      = hash.ToString().ToUpper()
                });
            }

            using (var stream = new FileStream("./output/manifest.xml", FileMode.Create))
            {
                var serializer = new XmlSerializer(typeof(Modifications));
                serializer.Serialize(stream, new Modifications()
                {
                    files = files.ToArray()
                });
            }

            if (File.Exists("./output/" + patchFileName))
            {
                File.Delete("./output/" + patchFileName);
            }
            using (ZipArchive patchFile = ZipFile.Open("./output/" + patchFileName, ZipArchiveMode.Create))
            {
                patchFile.CreateEntryFromFile("./output/manifest.xml", "manifest.xml");
                foreach (var file in Directory.GetFiles("./input", "*.*", SearchOption.AllDirectories))
                {
                    var infos    = new FileInfo(file);
                    var fileUri  = new Uri(infos.FullName);
                    var relative = fullPath.MakeRelativeUri(fileUri).ToString();
                    patchFile.CreateEntryFromFile(file, relative);
                }
            }

            {
                Crc32Algorithm crc32 = new Crc32Algorithm();
                StringBuilder  hash  = new StringBuilder();
                using (FileStream fs = File.Open("./output/" + patchFileName, FileMode.Open))
                    foreach (byte b in crc32.ComputeHash(fs))
                    {
                        hash.Append(b.ToString("x2").ToLower());
                    }

                using (var stream = new FileStream("./output/dofus_" + currentVersion + ".xml", FileMode.Create))
                {
                    var serializer = new XmlSerializer(typeof(Uplauncher));
                    serializer.Serialize(stream, new Uplauncher()
                    {
                        version = nextVersion, patchs = new patch[] { new patch()
                                                                      {
                                                                          path = new path()
                                                                          {
                                                                              crc = hash.ToString().ToUpper(), url = "http://staticdata.earthscape.fr/client/" + patchFileName
                                                                          }
                                                                      } }
                    });
                }
            }

            Console.ReadLine();
        }