Example #1
0
 /// <summary>
 /// Calculates the CRC32 polynomial of an object.
 /// </summary>
 /// <param name="value">The object to check.</param>
 /// <returns>A checksum of <paramref name="value"/> as an integer.</returns>
 public static long CRC32(object value)
 {
     var raw = ToByteArray(value);
     var alg = new CRC32();
     alg.ComputeHash(raw);
     return alg.Value;
 }
 /// <summary>
 /// Метод возвращает строку, которая представляет хеш-сумму файла по указанному пути для алгоритма CRC-32.
 /// </summary>
 /// <returns></returns>
 public string GetCRCHash()
 {
     CRC32 crc32 = new CRC32();
     String hash = String.Empty;
     try
     {
         using (FileStream fs = File.Open(filePath, FileMode.Open))
             foreach (byte b in crc32.ComputeHash(fs))
                 hash += b.ToString("x2").ToLower();
     }
     catch (Exception e)
     {
         System.Windows.MessageBox.Show(e.Message);
     }
     return hash;
 }
 private byte[] getCrc32(byte[] data, long dataLength) {
     CRC32 crc32 = new CRC32();
     crc32.Initialize();
     byte[] hash = crc32.ComputeHash(data, 0, (int)dataLength);
     Array.Reverse(hash);
     return hash;
 }
Example #4
0
        private void NetworkLoop()
        {
            while (!Cancellator.IsCancellationRequested)
            {
                try
                {
                    if (!Socket.Poll(100000, SelectMode.SelectRead))
                    {
                        continue;
                    }
                }
                catch (SocketException) { break; }
                byte[] Data;
                try
                {
                    byte[] Buffer = new byte[8];
                    Stream.Read(Buffer, 0, 8);
                    int PacketLength = ToInt32(Buffer, 0);
                    if (ToUInt32(Buffer, 4) != 0x31305456U)
                    {
                        break;
                    }
                    Data = new byte[PacketLength];
                    int Offset = 0;
                    do
                    {
                        int BytesRead = Stream.Read(Data, Offset, PacketLength);
                        if (BytesRead == 0)
                        {
                            break;
                        }
                        Offset       += BytesRead;
                        PacketLength -= BytesRead;
                    } while (PacketLength > 0);
                    if (PacketLength != 0)
                    {
                        break;
                    }
                }
                catch (IOException) { break; }
                try
                {
                    if (State == EncryptionState.Encrypted)
                    {
                        MessageReceived(Encryptor.Decrypt(Data));
                    }
                    else
                    {
                        MessageType Type = MessageType.Invalid;
                        if (Data.Length > 3)
                        {
                            Type = (MessageType)(ToUInt32(Data, 0) & ~0x80000000U);
                        }
                        if (State == EncryptionState.Connected && Type == MessageType.ChannelEncrypt)
                        {
                            RawMessage <ChannelEncrypt> Message = new RawMessage <ChannelEncrypt>(Data);
                            if (Message.Payload.Length >= 16)
                            {
                                RawMessage <ChannelEncrypt> Response = new RawMessage <ChannelEncrypt>(MessageType.ChannelEncryptResponse);
                                byte[] Challenge = Message.Payload, EncryptedBlob, SessionKey = new byte[32];
                                using (RandomNumberGenerator RNG = RandomNumberGenerator.Create())
                                    RNG.GetBytes(SessionKey);
                                using (RSA RSA = RSA.Create())
                                {
                                    RSA.ImportParameters(Parameters);
                                    byte[] BlobToEncrypt = new byte[32 + Challenge.Length];
                                    Copy(SessionKey, BlobToEncrypt, 32);
                                    Copy(Challenge, 0, BlobToEncrypt, 32, Challenge.Length);
                                    EncryptedBlob = RSA.Encrypt(BlobToEncrypt, RSAEncryptionPadding.OaepSHA1);
                                }
                                byte[] CRCHash;
                                using (CRC32 CRC = new CRC32())
                                    CRCHash = CRC.ComputeHash(EncryptedBlob);
                                int Length = EncryptedBlob.Length;
                                Response.Payload = new byte[Length + 8];
                                Copy(EncryptedBlob, Response.Payload, Length);
                                Copy(CRCHash, 0, Response.Payload, Length, 4);
                                Encryptor = new EncryptionFilter(SessionKey);
                                State     = EncryptionState.Challenged;
                                Send(Response.Serialize());
                            }
                            else
                            {
                                Disconnect(false);
                            }
                        }
                        else if (State == EncryptionState.Challenged && Type == MessageType.ChannelEncryptResult)
                        {
                            if (new RawMessage <ChannelEncryptResult>(Data).Body.Success)
                            {
                                State = EncryptionState.Encrypted;
                                Log($"Established encrypted TCP connection to {EndpointAddress}");
                                Connected?.Invoke();
                            }
                            else
                            {
                                Disconnect(false);
                            }
                        }
                        else
                        {
                            Disconnect(false);
                        }
                    }
                }
                catch { }
            }
            bool UserInitiated = Cancellator.IsCancellationRequested;

            if (UserInitiated)
            {
                Shutdown();
            }
            Release(UserInitiated);
        }
        /// <summary>
        /// The sender then sends a ZFILE header with ZMODEM Conversion, Management, and Transport options[3]
        /// followed by a ZCRCW data subpacket containing the file name, file length,
        /// modification date, and other information identical to that used by YMODEM Batch.
        /// </summary>
        /// <param name="fileInfo"></param>
        /// <param name="crcCalculator"></param>
        private bool SendZFILEHeaderCommand(string filename, int length, DateTimeOffset lastWriteTimeUtc, CRC32 crcCalculator)
        {
            var result = default(bool);

            var isExtended = true;

            var zFileHeader = Utils.Build32BitBinHeader(
                HeaderType.ZFILE,
                ZFILEConversionOption.ZCBIN,
                ZFILEManagementOption.ZMNEWL,
                ZFILETransportOption.None,
                ZFILEExtendedOptions.None,
                crcCalculator
                );

            var zFileHeaderQueue = new Queue <byte>();

            foreach (var c in zFileHeader)
            {
                zFileHeaderQueue.Enqueue((byte)c);
            }

            // Send ZFILE header first - No response
            SendCommand(zFileHeaderQueue.ToArray());

            var dataQueue = new Queue <byte>();

            foreach (char c in filename)
            {
                dataQueue.Enqueue((byte)c);
            }

            if (isExtended)
            {
                dataQueue.Enqueue(0);

                // File length as decimal string
                var fileLength = length.ToString();

                foreach (var c in fileLength)
                {
                    dataQueue.Enqueue((byte)c);
                }

                // Space
                dataQueue.Enqueue(0x20);

                var utcTime     = lastWriteTimeUtc.ToUnixTimeSeconds();
                var octalString = Convert.ToString(utcTime, 8);

                // Modification date
                foreach (var c in octalString)
                {
                    dataQueue.Enqueue((byte)c);
                }
            }
            else
            {
                // The file information is terminated by a null.
                // If only the pathname is sent, the pathname is terminated with two nulls.
                dataQueue.Enqueue(0);
                dataQueue.Enqueue(0);
            }

            byte[] data = dataQueue.Concat(new byte[] { (byte)ZDLESequence.ZCRCW }).ToArray();
            dataQueue.Enqueue((byte)ControlBytes.ZDLE);
            dataQueue.Enqueue((byte)ZDLESequence.ZCRCW);

            var crc = crcCalculator.ComputeHash(data);

            var encodedCRC = dataQueue
                             .Concat(ZDLEEncoder.EscapeControlCharacters(crc))
                             .ToArray();

            var response = SendCommand(encodedCRC, true, HeaderType.ZRPOS);

            // We expect ZRPOS
            if (response?.ZHeader == HeaderType.ZRPOS)
            {
                result = true;
            }

            /*
             * The receiver may respond with a ZSKIP header, which makes the sender
             * proceed to the next file (if any) in the batch.
             *
             * A ZRPOS header from the receiver initiates transmission of the file
             * data starting at the offset in the file specified in the ZRPOS header.
             * Normally the receiver specifies the data transfer to begin begin at
             * offset 0 in the file.
             */

            if (response?.ZHeader == HeaderType.ZSKIP ||
                response?.ZHeader == HeaderType.ZRPOS ||
                response?.ZHeader == HeaderType.ZCRC)
            {
                /*
                 * The receiver has a file with the same name and length, may
                 * respond with a ZCRC header with a byte count, which
                 * requires the sender to perform a 32 bit CRC on the
                 * specified number of bytes in the file and transmit the
                 * complement of the CRC in an answering ZCRC header.the crc is
                 * initialised to 0xfffffff; a byte count of 0 implies the entire
                 * file the receiver uses this information to determine whether to
                 * accept the file or skip it.  This sequence may be triggered
                 * by the ZMCRC Management Option.
                 */
            }

            return(result);
        }
        public void SampleEncode()
        {
            FileStream fs = File.OpenRead(@"..\..\Samples\TestFile.bin");

            try
            {
                byte[] original = new byte[4096];
                int originalBytes = fs.Read(original, 0, 4096);
                Assert.AreEqual(584, originalBytes, "Unexpected amount of bytes read.");

                //test file encodes period(46) and tab(9), and follows with CRLF
                YEncEncoder encoder = new YEncEncoder(128, new byte[] {46,9}, true);
                byte[] encoded = new byte[4096];

                int encodedBytes = encoder.GetBytes(original, 0, originalBytes, encoded, 0, true);

                Assert.AreEqual(606, encodedBytes, "Test file supplied encodes to 606");
                FileStream fs2 = File.OpenRead(@"..\..\Samples\Encoded.bin");

                try
                {
                    byte[] check = new byte[4096];
                    int checkBytes = fs2.Read(check, 0, 4096);

                    Assert.AreEqual(606, checkBytes, "We expect 606 bytes");

                    for(int i=0; i<checkBytes; i++)
                    {
                        Assert.AreEqual(check[i], encoded[i], "Checked against sample encoded failed on byte " + i.ToString());
                    }

                    CRC32 extraCheck = new CRC32();
                    extraCheck.ComputeHash(original, 0, originalBytes);
                    byte[] extraCheckCRC = extraCheck.Hash;
                    byte[] actualCRC = encoder.CRCHash;
                    byte[] expectedCRC = new byte[] {0xde,0xd2,0x9f,0x4f};

                    Assert.AreEqual(BitConverter.ToString(expectedCRC), BitConverter.ToString(extraCheckCRC), "CRC mismatch, due to CRC algorithm failure?");
                    Assert.AreEqual(BitConverter.ToString(expectedCRC), BitConverter.ToString(actualCRC), "CRC mismatch");
                }
                finally
                {
                    fs2.Close();
                }
            }
            finally
            {
                fs.Close();
            }
        }
        public override unsafe void CodeImage(Bitmap bitmap, Stream outStream)
        {
            lock (ImageProcessLock)
            {
                if (!outStream.CanWrite)
                {
                    throw new Exception("Must have access to Write in the Stream");
                }

                if (LastFrame == null)
                {
                    byte[] temp = base.jpgCompression.Compress(bitmap);
                    outStream.Write(BitConverter.GetBytes(temp.Length), 0, 4);
                    outStream.Write(temp, 0, temp.Length);
                    SetLastFrame(ref bitmap);
                    return;
                }

                long oldPos = outStream.Position;
                outStream.Write(new byte[4], 0, 4);
                int TotalDataLength = 0;

                List <byte[]> updates = new List <byte[]>();
                SimpleBitmap  sbBmp   = new SimpleBitmap(bitmap);
                MemoryStream  ms      = new MemoryStream();
                byte[]        buffer  = null;

                if (!LastFrame.Locked)
                {
                    LastFrame.Lock();
                }

                sbBmp.Lock();

                if (sbBmp.Info.PixelSize != LastFrame.Info.PixelSize)
                {
                    throw new Exception("PixelFormat is not equal to previous Bitmap");
                }

                if (LastFrame.Info.Width != sbBmp.Info.Width || LastFrame.Info.Height != sbBmp.Info.Height)
                {
                    sbBmp.Unlock();
                    throw new Exception("Bitmap width/height are not equal to previous bitmap");
                }

                List <Rectangle> Blocks = new List <Rectangle>();
                int index = 0;

                int y = 0;
                int x = 0;

                Size s        = new Size(bitmap.Width, CheckBlock.Height);
                Size lastSize = new Size(bitmap.Width % CheckBlock.Width, bitmap.Height % CheckBlock.Height);

                int lasty = bitmap.Height - lastSize.Height;
                int lastx = bitmap.Width - lastSize.Width;

                Rectangle cBlock = new Rectangle();

                s = new Size(bitmap.Width, s.Height);
                while (y != bitmap.Height)
                {
                    if (y == lasty)
                    {
                        s = new Size(bitmap.Width, lastSize.Height);
                    }

                    cBlock = new Rectangle(0, y, bitmap.Width, s.Height);

                    if (onCodeDebugScan != null)
                    {
                        onCodeDebugScan(cBlock);
                    }

                    if (!SimpleBitmap.Compare(cBlock, LastFrame.Scan0_int, sbBmp.Scan0_int, sbBmp.Info))
                    //if (!SimpleBitmap.Compare(y, s.Height, LastFrame.Scan0_int, sbBmp.Scan0_int, sbBmp.Info))
                    {
                        index = Blocks.Count - 1;
                        if (Blocks.Count != 0 && (Blocks[index].Y + Blocks[index].Height) == cBlock.Y)
                        {
                            cBlock        = new Rectangle(Blocks[index].X, Blocks[index].Y, Blocks[index].Width, Blocks[index].Height + cBlock.Height);
                            Blocks[index] = cBlock;
                        }
                        else
                        {
                            Blocks.Add(cBlock);
                        }
                    }
                    y += s.Height;
                }

                List <CacheInfo> finalUpdates = new List <CacheInfo>();
                const int        CheckHeight  = 50;
                for (int i = 0; i < Blocks.Count; i++)
                {
                    s     = new Size(CheckBlock.Width, Blocks[i].Height);
                    y     = Blocks[i].Y;
                    lasty = (Blocks[i].Y + Blocks[i].Height);

                    while (y != lasty)
                    {
                        int ScanHeight = y + CheckHeight > lasty ? lasty - y : CheckHeight;
                        x = 0;
                        while (x != bitmap.Width)
                        {
                            if (x == lastx)
                            {
                                s = new Size(lastSize.Width, Blocks[i].Height);
                            }
                            cBlock = new Rectangle(x, y, s.Width, ScanHeight);

                            if (onCodeDebugScan != null)
                            {
                                onCodeDebugScan(cBlock);
                            }

                            if (!SimpleBitmap.Compare(cBlock, sbBmp.Scan0_int, LastFrame.Scan0_int, sbBmp.Info))
                            {
                                /*byte[] tempData = new byte[0];
                                 * LastFrame.CopyBlock(cBlock, ref tempData);
                                 * finalUpdates.Add(new CacheInfo(0, false, tempData, cBlock));*/

                                //hash it and see if exists in cache
                                hasher = new CRC32(); //re-initialize for seed
                                byte[] tempData = new byte[0];
                                LastFrame.CopyBlock(cBlock, ref tempData);
                                int hash = BitConverter.ToInt32(hasher.ComputeHash(tempData), 0);

                                if (codeCached.Count >= MaxBuffers)
                                {
                                    codeCached.RemoveAt(0);
                                }

                                if (codeCached.ContainsKey(hash))
                                {
                                    CachedSize += (ulong)tempData.Length;
                                    finalUpdates.Add(new CacheInfo(hash, true, new byte[0], cBlock));
                                }
                                else
                                {
                                    //nothing found in cache let's use the normal way
                                    codeCached.Add(hash, tempData);
                                    finalUpdates.Add(new CacheInfo(hash, false, tempData, cBlock));
                                }
                            }
                            x += s.Width;
                        }
                        y += ScanHeight;
                    }
                }

                for (int i = 0; i < finalUpdates.Count; i++)
                {
                    buffer = new byte[0];
                    Rectangle rect = finalUpdates[i].Rect;

                    if (!finalUpdates[i].isCached)
                    {
                        fixed(byte *ptr = finalUpdates[i].Data)
                        {
                            using (Bitmap TmpBmp = new Bitmap(rect.Width, rect.Height, rect.Width * LastFrame.Info.PixelSize, LastFrame.bitmapData.PixelFormat, new IntPtr(ptr)))
                            {
                                buffer = base.jpgCompression.Compress(TmpBmp);
                            }
                        }
                    }

                    outStream.WriteByte(finalUpdates[i].isCached ? (byte)1 : (byte)0);
                    outStream.Write(BitConverter.GetBytes(finalUpdates[i].Rect.X), 0, 4);
                    outStream.Write(BitConverter.GetBytes(finalUpdates[i].Rect.Y), 0, 4);
                    outStream.Write(BitConverter.GetBytes(finalUpdates[i].Rect.Width), 0, 4);
                    outStream.Write(BitConverter.GetBytes(finalUpdates[i].Rect.Height), 0, 4);
                    outStream.Write(BitConverter.GetBytes(finalUpdates[i].Hash), 0, 4);
                    outStream.Write(BitConverter.GetBytes(buffer.Length), 0, 4);
                    outStream.Write(buffer, 0, buffer.Length);
                    TotalDataLength += buffer.Length + (4 * 6) + 1;
                }

                outStream.Position = oldPos;
                outStream.Write(BitConverter.GetBytes(TotalDataLength), 0, 4);

                Blocks.Clear();
                SetLastFrame(sbBmp);
                ms.Close();
                ms.Dispose();
            }
        }
Example #8
0
 /// <see cref="IHeap.ComputeHash"/>
 public byte[] ComputeHash()
 {
     return(CRC32.ComputeHash(this.GetByteSquence()));
 }
Example #9
0
 public static string CalcCRC32(string password)
 {
     return(BitConverter.ToInt32(crc32.ComputeHash(Encoding.UTF8.GetBytes(password)), 0).ToString());
 }
Example #10
0
 public static uint GetCRC32(Stream input)
 {
     byte[] data = crc32.ComputeHash(input);
     return(GetCRC32(data));
 }
Example #11
0
        private static string getUniqueIdentifier(byte[] replayDataBuffer)
        {
            CRC32 crc = new CRC32();

            byte[] tailInBytes = crc.ComputeHash(replayDataBuffer);

            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < tailInBytes.Length; i++)
            {
                sb.Append(tailInBytes[i].ToString("x2"));
            }
            string tail = sb.ToString();
            return tail;
        }
        public override unsafe void CodeImage(Bitmap bitmap, Stream outStream)
        {
            if (!outStream.CanWrite)
            {
                throw new Exception("Must have access to Write in the Stream");
            }

            if (CodeTempBitmap != null)
            {
                if (CodeTempBitmap.Width != bitmap.Width || CodeTempBitmap.Height != bitmap.Height)
                {
                    throw new Exception("Bitmap width/height are not equal to previous bitmap");
                }
                if (bitmap.PixelFormat != CodeTempBitmap.PixelFormat)
                {
                    throw new Exception("PixelFormat is not equal to previous Bitmap");
                }
            }

            if (CodeTempBitmap == null)
            {
                byte[] temp = base.jpgCompression.Compress(bitmap);
                outStream.Write(BitConverter.GetBytes(temp.Length), 0, 4);
                outStream.Write(temp, 0, temp.Length);
                CodeTempBitmap = bitmap;
                return;
            }

            BitmapData bmpData     = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadWrite, bitmap.PixelFormat);
            BitmapData CodeBmpData = CodeTempBitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadWrite, bitmap.PixelFormat);
            int        Stride      = Math.Abs(bmpData.Stride);

            List <Rectangle> Blocks = new List <Rectangle>();

            for (int y = 0, i = 0; y < bitmap.Height; y++, i += Stride)
            {
                if (onCodeDebugScan != null)
                {
                    onCodeDebugScan(new Rectangle(0, y, bitmap.Width, 1));
                }

                Rectangle ScanBlock = new Rectangle(0, y, bitmap.Width, 1);
                if (NativeMethods.memcmp(new IntPtr(bmpData.Scan0.ToInt32() + i), new IntPtr(CodeBmpData.Scan0.ToInt32() + i), (uint)Stride) != 0)
                {
                    byte[] temp = new byte[Stride];
                    fixed(byte *ptr = temp)
                    {
                        NativeMethods.memcpy(ptr, (void *)(bmpData.Scan0.ToInt32() + i), (uint)temp.Length);
                    }

                    CRC32 hasher = new CRC32();
                    int   hash   = BitConverter.ToInt32(hasher.ComputeHash(temp), 0);

                    if (EncodeCache.Count >= MaxBuffers)
                    {
                        EncodeCache.RemoveAt(0);
                    }

                    if (EncodeCache.ContainsKey(hash))
                    {
                        outStream.WriteByte(1);
                        outStream.Write(new byte[4], 0, 4);
                        outStream.Write(BitConverter.GetBytes(hash), 0, 4);
                        outStream.Write(BitConverter.GetBytes((ushort)y), 0, 2);
                    }
                    else
                    {
                        outStream.WriteByte(0);
                        outStream.Write(BitConverter.GetBytes(temp.Length), 0, 4);
                        outStream.Write(BitConverter.GetBytes(hash), 0, 4);
                        outStream.Write(BitConverter.GetBytes((ushort)y), 0, 2);
                        outStream.Write(temp, 0, temp.Length);
                        EncodeCache.Add(hash, temp);
                    }
                    Blocks.Add(ScanBlock);
                }
            }

            for (int i = 0; i < Blocks.Count; i++)
            {
                Bitmap cloned = (Bitmap)bitmap.Clone(Blocks[i], bitmap.PixelFormat);
                byte[] temp   = base.jpgCompression.Compress(cloned);

                cloned.Dispose();
            }

            bitmap.UnlockBits(bmpData);
            CodeTempBitmap.UnlockBits(CodeBmpData);

            if (onVideoStreamCoding != null)
            {
                onVideoStreamCoding(outStream, Blocks.ToArray());
            }

            if (CodeTempBitmap != null)
            {
                CodeTempBitmap.Dispose();
            }
            this.CodeTempBitmap = bitmap;
        }