예제 #1
0
        private void EncryptStream(AesManaged EncEngine, TEncryptionKey DataKey, byte[] WorkLen)
        {
            WorkingStream.Position = 0;
            WorkingStream.Write(WorkLen, 0, WorkLen.Length);
            int read;

            byte[] CurrentSegment = new byte[TEncryptionUtils.AgileSegmentSize];
            int    SegmentNumber  = 0;

            while ((read = WorkingStream.Read(CurrentSegment, 0, CurrentSegment.Length)) > 0)
            {
                DataKey.CalcDataIV(SegmentNumber);
                SegmentNumber++;

                using (ICryptoTransform Encryptor = EncEngine.CreateEncryptor(DataKey.Key, DataKey.IV))
                {
                    using (MemoryStream outms = new MemoryStream()) //will be closed by Cryptostream
                    {
                        using (CryptoStream cs = new CryptoStream(outms, Encryptor, CryptoStreamMode.Write))
                        {
                            cs.Write(CurrentSegment, 0, read);
                        }

                        WorkingStream.Position -= read;
                        byte[] outArr = outms.ToArray(); //ToArray works with stream closed, and cs will close the stream.
                        WorkingStream.Write(outArr, 0, outArr.Length);
                    }
                }
            }
        }
예제 #2
0
        private void ReadSegment(long SegmentNumber)
        {
            if (SegmentNumber == CurrentSegmentNo)
            {
                return;
            }
            DataStream.Position = DataStreamStart + SegmentNumber * SegmentSize;

            byte[] CurrentSegmentEnc = new byte[Math.Min(SegmentSize, DataStream.Length - DataStream.Position)];
            DataStream.Read(CurrentSegmentEnc, CurrentSegmentEnc.Length);

            using (MemoryStream msDecrypt = new MemoryStream(CurrentSegmentEnc))
            {
                ICryptoTransform RealDecryptor = Decryptor;
                try
                {
                    if (RealDecryptor == null)
                    {
                        Key.CalcDataIV(SegmentNumber);
                        RealDecryptor = EncEngine.CreateDecryptor(Key.Key, Key.IV);
                    }
                    using (CryptoStream cs = new CryptoStream(msDecrypt, RealDecryptor, CryptoStreamMode.Read))
                    {
                        cs.Read(CurrentSegment, 0, CurrentSegmentEnc.Length);
                    }
                }
                finally
                {
                    if (RealDecryptor != Decryptor)
                    {
                        RealDecryptor.Dispose();
                    }
                }
            }

            CurrentSegmentNo = SegmentNumber;
        }