Exemple #1
0
        private void ParallelCTR(ICipherMode Cipher, byte[] Input, int InOffset, byte[] Output, int OutOffset)
        {
            int  blkSize = Cipher.ParallelBlockSize;
            long inpSize = (Input.Length - InOffset);
            long alnSize = (inpSize / blkSize) * blkSize;
            long count   = 0;

            Cipher.IsParallel        = true;
            Cipher.ParallelBlockSize = blkSize;

            // parallel blocks
            while (count != alnSize)
            {
                Cipher.Transform(Input, InOffset, Output, OutOffset);
                InOffset  += blkSize;
                OutOffset += blkSize;
                count     += blkSize;
            }

            if (alnSize != inpSize)
            {
                int    cnkSize   = (int)(inpSize - alnSize);
                byte[] inpBuffer = new byte[cnkSize];
                Buffer.BlockCopy(Input, InOffset, inpBuffer, 0, cnkSize);
                byte[] outBuffer = new byte[cnkSize];
                Cipher.Transform(inpBuffer, outBuffer);
                Buffer.BlockCopy(outBuffer, 0, Output, OutOffset, cnkSize);
                count += cnkSize;
            }
        }
Exemple #2
0
        private void BlockEncrypt(ICipherMode Cipher, IPadding Padding, byte[] Input, int InOffset, ref byte[] Output, int OutOffset)
        {
            int  blkSize = Cipher.BlockSize;
            long inpSize = (Input.Length - InOffset);
            long alnSize = inpSize - (inpSize % blkSize);
            long count   = 0;

            Cipher.IsParallel = false;

            while (count != alnSize)
            {
                Cipher.Transform(Input, InOffset, Output, OutOffset);
                InOffset  += blkSize;
                OutOffset += blkSize;
                count     += blkSize;
            }

            // partial
            if (alnSize != inpSize)
            {
                int    fnlSize   = (int)(inpSize - alnSize);
                byte[] inpBuffer = new byte[blkSize];
                Buffer.BlockCopy(Input, InOffset, inpBuffer, 0, fnlSize);
                Padding.AddPadding(inpBuffer, fnlSize);
                byte[] outBuffer = new byte[blkSize];
                Cipher.Transform(inpBuffer, 0, outBuffer, 0);
                if (Output.Length != OutOffset + blkSize)
                {
                    Array.Resize(ref Output, OutOffset + blkSize);
                }
                Buffer.BlockCopy(outBuffer, 0, Output, OutOffset, blkSize);
                count += blkSize;
            }
        }
Exemple #3
0
        private void BlockDecrypt(ICipherMode Cipher, IPadding Padding, byte[] Input, int InOffset, ref byte[] Output, int OutOffset)
        {
            int  blkSize = Cipher.BlockSize;
            long inpSize = (Input.Length - InOffset);
            long alnSize = inpSize - blkSize;
            long count   = 0;

            Cipher.IsParallel = false;

            while (count != alnSize)
            {
                Cipher.Transform(Input, InOffset, Output, OutOffset);
                InOffset  += blkSize;
                OutOffset += blkSize;
                count     += blkSize;
            }

            // last block
            byte[] inpBuffer = new byte[blkSize];
            Buffer.BlockCopy(Input, InOffset, inpBuffer, 0, blkSize);
            byte[] outBuffer = new byte[blkSize];
            Cipher.Transform(inpBuffer, 0, outBuffer, 0);
            int fnlSize = blkSize - Padding.GetPaddingLength(outBuffer, 0);

            Buffer.BlockCopy(outBuffer, 0, Output, OutOffset, fnlSize);
            OutOffset += fnlSize;

            if (Output.Length != OutOffset)
            {
                Array.Resize(ref Output, OutOffset);
            }
        }
Exemple #4
0
        private void BlockCTR(ICipherMode Cipher, byte[] Input, int InOffset, byte[] Output, int OutOffset)
        {
            int  blkSize = Cipher.BlockSize;
            long inpSize = (Input.Length - InOffset);
            long alnSize = inpSize - (inpSize % blkSize);
            long count   = 0;

            Cipher.IsParallel = false;

            while (count != alnSize)
            {
                Cipher.Transform(Input, InOffset, Output, OutOffset);
                InOffset  += blkSize;
                OutOffset += blkSize;
                count     += blkSize;
            }

            // partial
            if (alnSize != inpSize)
            {
                int    cnkSize   = (int)(inpSize - alnSize);
                byte[] inpBuffer = new byte[blkSize];
                Buffer.BlockCopy(Input, InOffset, inpBuffer, 0, cnkSize);
                byte[] outBuffer = new byte[blkSize];
                Cipher.Transform(inpBuffer, 0, outBuffer, 0);
                Buffer.BlockCopy(outBuffer, 0, Output, OutOffset, cnkSize);
                count += cnkSize;
            }
        }
Exemple #5
0
        private void ParallelDecrypt(ICipherMode Cipher, IPadding Padding, byte[] Input, int InOffset, byte[] Output, int OutOffset)
        {
            int  blkSize = Cipher.ParallelBlockSize;
            long inpSize = (Input.Length - InOffset);
            long alnSize = (inpSize / blkSize) * blkSize;
            long count   = 0;

            Cipher.IsParallel        = true;
            Cipher.ParallelBlockSize = blkSize;

            // parallel
            while (count != alnSize)
            {
                Cipher.Transform(Input, InOffset, Output, OutOffset);
                InOffset  += blkSize;
                OutOffset += blkSize;
                count     += blkSize;
            }

            if (alnSize != inpSize)
            {
                int cnkSize = (int)(inpSize - alnSize);
                BlockDecrypt(Cipher, Padding, Input, InOffset, ref Output, OutOffset);
            }
        }
Exemple #6
0
        /// <summary>
        /// Initialize the class with a Block <see cref="VTDev.Libraries.CEXEngine.Crypto.Digest.IDigest">Cipher</see> and optional <see cref="VTDev.Libraries.CEXEngine.Crypto.Cipher.Symmetric.Block.Padding.IPadding">Padding</see> instances.
        /// <para>This constructor requires a fully initialized <see cref="VTDev.Libraries.CEXEngine.Crypto.Enumeration.CipherModes">CipherMode</see> instance.
        /// If the <see cref="VTDev.Libraries.CEXEngine.Crypto.Enumeration.PaddingModes">PaddingMode</see> parameter is null, X9.23 padding will be used if required.</para>
        /// </summary>
        ///
        /// <param name="Cipher">The <see cref="VTDev.Libraries.CEXEngine.Crypto.Enumeration.SymmetricEngines">Block Cipher</see> wrapped in a Cipher mode</param>
        /// <param name="Padding">The Padding instance</param>
        /// <param name="DisposeEngine">Dispose of cipher engine when <see cref="Dispose()"/> on this class is called</param>
        ///
        /// <exception cref="CryptoProcessingException">Thrown if a null or uninitialized Cipher is used</exception>
        public PacketCipher(ICipherMode Cipher, IPadding Padding = null, bool DisposeEngine = false)
        {
            if (Cipher == null)
            {
                throw new CryptoProcessingException("PacketCipher:CTor", "The Cipher can not be null!", new ArgumentNullException());
            }
            if (!Cipher.IsInitialized)
            {
                throw new CryptoProcessingException("PacketCipher:CTor", "The Cipher has not been initialized!", new ArgumentException());
            }

            m_disposeEngine  = DisposeEngine;
            m_cipherEngine   = Cipher;
            m_isStreamCipher = false;
            m_blockSize      = m_cipherEngine.BlockSize;
            m_isEncryption   = m_cipherEngine.IsEncryption;
            m_isParallel     = false;

            if (m_isCounterMode = m_cipherEngine.GetType().Equals(typeof(CTR)))
            {
                if (m_isParallel = ((CTR)m_cipherEngine).IsParallel)
                {
                    m_blockSize = ((CTR)m_cipherEngine).ParallelBlockSize;
                }
            }
            else
            {
                if (m_cipherEngine.GetType().Equals(typeof(CBC)))
                {
                    m_isParallel = ((CBC)m_cipherEngine).IsParallel && !((CBC)m_cipherEngine).IsEncryption;
                }
            }
        }
 /// <summary>
 /// The DTM Established event arguments constructor
 /// </summary>
 /// 
 /// <param name="Client">The client socket instance</param>
 /// <param name="ForwardSession">The initialized Forward session encryption cipher; used to encrypt data sent to the remote host</param>
 /// <param name="ReturnSession">The initialized Return session encryption cipher; used to decrypt data sent from the remote host</param>
 /// <param name="Flag">An option flag that can contain additional information about the exchange</param>
 public DtmEstablishedEventArgs(Socket Client, ICipherMode ForwardSession, ICipherMode ReturnSession, long Flag)
 {
     this.Client = Client;
     this.ForwardSession = ForwardSession;
     this.ReturnSession = ReturnSession;
     this.OptionFlag = Flag;
 }
 /// <summary>
 /// The DTM Established event arguments constructor
 /// </summary>
 ///
 /// <param name="Client">The established client socket instance</param>
 /// <param name="ForwardSession">The initialized Forward session encryption cipher; used to encrypt data sent to the remote host</param>
 /// <param name="ReturnSession">The initialized Return session encryption cipher; used to decrypt data sent from the remote host</param>
 /// <param name="Flag">An option flag that can contain additional information about the exchange</param>
 public DtmEstablishedArgs(Socket Client, ICipherMode ForwardSession, ICipherMode ReturnSession, long Flag)
 {
     this.Client         = Client;
     this.ForwardSession = ForwardSession;
     this.ReturnSession  = ReturnSession;
     this.OptionFlag     = Flag;
 }
Exemple #9
0
        private byte[] SymmetricTransform(ICipherMode Cipher, byte[] Data)
        {
            byte[] ptext = new byte[Data.Length];
            Cipher.Transform(Data, ptext);

            return(ptext);
        }
Exemple #10
0
 private void Dispose(bool Disposing)
 {
     if (!m_isDisposed && Disposing)
     {
         try
         {
             if (m_disposeEngine)
             {
                 if (m_cipherEngine != null)
                 {
                     m_cipherEngine.Dispose();
                     m_cipherEngine = null;
                 }
                 if (m_streamCipher != null)
                 {
                     m_streamCipher.Dispose();
                     m_streamCipher = null;
                 }
             }
         }
         finally
         {
             m_isDisposed = true;
         }
     }
 }
Exemple #11
0
 public DtmFileTransfer(ICipherMode Cipher, long FileId = 0, int BufferCount = 1024, int BufferSize = 262144)
 {
     _fileSymProcessor = Cipher;
     _fileId           = FileId;
     _rcvBuffer        = new PacketBuffer(BufferCount);
     _sndBuffer        = new PacketBuffer(BufferCount);
     m_bufferSize      = BufferSize;
     _bufferCount      = BufferCount;
 }
Exemple #12
0
        private string _tempPath = ""; // temp file path

        #endregion Fields

        #region Constructors

        public DtmFileTransfer(ICipherMode Cipher, long FileId = 0, int BufferCount = 1024, int BufferSize = 262144)
        {
            _fileSymProcessor = Cipher;
            _fileId = FileId;
            _rcvBuffer = new PacketBuffer(BufferCount);
            _sndBuffer = new PacketBuffer(BufferCount);
            _bufferSize = BufferSize;
            _bufferCount = BufferCount;
        }
Exemple #13
0
        private string MonteCarloTest(ICipherMode Engine)
        {
            byte[] outBytes = new byte[Engine.BlockSize];
            byte[] inBytes  = new byte[Engine.BlockSize];

            for (int i = 0; i < 100; i++)
            {
                Engine.Transform(inBytes, outBytes);
                inBytes = (byte[])outBytes.Clone();
            }

            return(HexConverter.ToString(outBytes));
        }
Exemple #14
0
        /// <summary>
        /// Initialize this class with a block cipher instance
        /// </summary>
        /// <param name="Cipher">Instance of the block cipher</param>
        /// <param name="DisposeEngine">Dispose of digest engine when <see cref="Dispose()"/> on this class is called</param>
        ///
        /// <exception cref="CryptoMacException">Thrown if an invalid block size is used</exception>
        public CMAC(IBlockCipher Cipher, bool DisposeEngine = true)
        {
            if (Cipher.BlockSize != 16 && Cipher.BlockSize != 32)
            {
                throw new CryptoMacException("CMAC:Ctor", "Block size must be 128 or 256 bits!", new ArgumentException());
            }

            m_disposeEngine = DisposeEngine;
            m_cipherMode    = new CBC(Cipher);
            m_blockSize     = m_cipherMode.BlockSize;
            m_macSize       = Cipher.BlockSize;
            m_msgCode       = new byte[m_blockSize];
            m_wrkBuffer     = new byte[m_blockSize];
            m_wrkOffset     = 0;
        }
Exemple #15
0
 private void Dispose(bool Disposing)
 {
     if (!_isDisposed && Disposing)
     {
         try
         {
             if (_cipherType != null && _disposeEngine)
             {
                 _cipherType.Dispose();
                 _cipherType = null;
             }
             if (_msgCode != null)
             {
                 Array.Clear(_msgCode, 0, _msgCode.Length);
                 _msgCode = null;
             }
             if (_tmpZeroes != null)
             {
                 Array.Clear(_tmpZeroes, 0, _tmpZeroes.Length);
                 _tmpZeroes = null;
             }
             if (_wrkBuffer != null)
             {
                 Array.Clear(_wrkBuffer, 0, _wrkBuffer.Length);
                 _wrkBuffer = null;
             }
             if (_L != null)
             {
                 Array.Clear(_L, 0, _L.Length);
                 _L = null;
             }
             if (_LU != null)
             {
                 Array.Clear(_LU, 0, _LU.Length);
                 _LU = null;
             }
             if (_LU2 != null)
             {
                 Array.Clear(_LU2, 0, _LU2.Length);
                 _LU2 = null;
             }
         }
         finally
         {
             _isDisposed = true;
         }
     }
 }
Exemple #16
0
        /// <summary>
        /// Initialize the class as a Block Cipher
        /// </summary>
        /// <param name="Cipher">Block Cipher instance</param>
        /// <param name="KeyParam">Key and vector material</param>
        /// <param name="Mode">Cipher mode</param>
        /// <param name="Padding">Padding type</param>
        public Transform(IBlockCipher Cipher, KeyParams KeyParam, CipherModes Mode = CipherModes.CTR, PaddingModes Padding = PaddingModes.X923)
        {
            this.KeyParam = KeyParam;

            if (Mode == CipherModes.CBC)
                this.CipherMode = new CBC(Cipher);
            else
                this.CipherMode = new CTR(Cipher);

            if (Padding == PaddingModes.PKCS7)
                this.Padding = new PKCS7();
            else if (Padding == PaddingModes.X923)
                this.Padding = new X923();

            this.IsStream = false;
        }
Exemple #17
0
        /// <summary>
        /// Initialize the class with the block cipher enumeration name
        /// </summary>
        /// <param name="EngineType">The block cipher enumeration name</param>
        ///
        /// <exception cref="CryptoMacException">Thrown if an invalid block size is used</exception>
        public CMAC(BlockCiphers EngineType)
        {
            IBlockCipher cipher = Helper.BlockCipherFromName.GetInstance(EngineType);

            if (cipher.BlockSize != 16 && cipher.BlockSize != 32)
            {
                throw new CryptoMacException("CMAC:Ctor", "Block size must be 128 or 256 bits!", new ArgumentException());
            }

            m_disposeEngine = true;
            m_cipherMode    = new CBC(cipher);
            m_blockSize     = m_cipherMode.BlockSize;
            m_macSize       = cipher.BlockSize;
            m_msgCode       = new byte[m_blockSize];
            m_wrkBuffer     = new byte[m_blockSize];
            m_wrkOffset     = 0;
        }
Exemple #18
0
        void StreamModesTest(ICipherMode Cipher, IPadding Padding)
        {
            if (Cipher.Engine.LegalKeySizes[0] > 32)
            {
                AllocateRandom(ref _key, 192);
            }
            else
            {
                AllocateRandom(ref _key, 32);
            }

            AllocateRandom(ref _iv, 16);
            // we are testing padding modes, make sure input size is random, but -not- block aligned..
            AllocateRandom(ref _plnText, 0, Cipher.BlockSize);

            KeyParams    kp   = new KeyParams(_key, _iv);
            MemoryStream mIn  = new MemoryStream(_plnText);
            MemoryStream mOut = new MemoryStream();
            MemoryStream mRes = new MemoryStream();

            CipherStream cs = new CipherStream(Cipher, Padding);

            cs.Initialize(true, kp);
            cs.Write(mIn, mOut);

            cs.Initialize(false, kp);
            mOut.Seek(0, SeekOrigin.Begin);
            cs.Write(mOut, mRes);

            int pos = (int)mRes.Position;

            byte[] res = new byte[_plnText.Length];
            Buffer.BlockCopy(mRes.ToArray(), 0, res, 0, pos);

            if (!Evaluate.AreEqual(res, _plnText))
            {
                throw new Exception("CipherStreamTest: Encrypted arrays are not equal!");
            }

            Cipher.Dispose();
        }
Exemple #19
0
 private void Dispose(bool Disposing)
 {
     if (!m_isDisposed && Disposing)
     {
         try
         {
             if (m_cipherMode != null && m_disposeEngine)
             {
                 m_cipherMode.Dispose();
                 m_cipherMode = null;
             }
             if (m_msgCode != null)
             {
                 Array.Clear(m_msgCode, 0, m_msgCode.Length);
                 m_msgCode = null;
             }
             if (m_wrkBuffer != null)
             {
                 Array.Clear(m_wrkBuffer, 0, m_wrkBuffer.Length);
                 m_wrkBuffer = null;
             }
             if (m_K1 != null)
             {
                 Array.Clear(m_K1, 0, m_K1.Length);
                 m_K1 = null;
             }
             if (m_K2 != null)
             {
                 Array.Clear(m_K2, 0, m_K2.Length);
                 m_K2 = null;
             }
         }
         finally
         {
             m_isDisposed = true;
         }
     }
 }
Exemple #20
0
        /// <summary>
        /// Uses Transform(in_data, out_data) method
        /// </summary>
        private byte[] Transform2(ICipherMode Cipher, byte[] Input, int BlockSize)
        {
            // slower, mem copy can be expensive on large data..
            int blocks = Input.Length / BlockSize;

            byte[] outData  = new byte[Input.Length];
            byte[] inBlock  = new byte[BlockSize];
            byte[] outBlock = new byte[BlockSize];

            for (int i = 0; i < blocks; i++)
            {
                Buffer.BlockCopy(Input, i * BlockSize, inBlock, 0, BlockSize);
                Cipher.Transform(inBlock, outBlock);
                Buffer.BlockCopy(outBlock, 0, outData, i * BlockSize, BlockSize);
            }

            if (blocks * BlockSize < Input.Length)
            {
                Cipher.Transform(Input, blocks * BlockSize, outData, blocks * BlockSize);
            }

            return(outData);
        }
Exemple #21
0
        /// <summary>
        /// Initialize the class
        /// </summary>
        /// <param name="Cipher">Instance of the block cipher</param>
        /// <param name="MacBits">Expected MAC return size in Bits; must be less or equal to Cipher Block size in bits</param>
        /// <param name="DisposeEngine">Dispose of digest engine when <see cref="Dispose()"/> on this class is called</param>
        ///
        /// <exception cref="CryptoMacException">Thrown if an invalid Mac or block size is used</exception>
        public CMAC(IBlockCipher Cipher, int MacBits, bool DisposeEngine = true)
        {
            if ((MacBits % 8) != 0)
            {
                throw new CryptoMacException("CMAC:Ctor", "MAC size must be multiple of 8!", new ArgumentOutOfRangeException());
            }
            if (MacBits > (Cipher.BlockSize * 8))
            {
                throw new CryptoMacException("CMAC:Ctor", String.Format("MAC size must be less or equal to {0}!", Cipher.BlockSize * 8), new ArgumentOutOfRangeException());
            }
            if (Cipher.BlockSize != 8 && Cipher.BlockSize != 16)
            {
                throw new CryptoMacException("CMAC:Ctor", "Block size must be either 64 or 128 bits!", new ArgumentException());
            }

            _disposeEngine = DisposeEngine;
            _cipherType    = new CBC(Cipher);
            _blockSize     = _cipherType.BlockSize;
            _digestSize    = MacBits / 8;
            _msgCode       = new byte[_blockSize];
            _wrkBuffer     = new byte[_blockSize];
            _tmpZeroes     = new byte[_blockSize];
            _wrkOffset     = 0;
        }
Exemple #22
0
        /// <summary>
        /// Uses Transform(in_data, in_offset, out_data, out_offset) method
        /// </summary>
        private byte[] Transform1(ICipherMode Cipher, byte[] Input, int BlockSize)
        {
            byte[] outData = new byte[Input.Length];
            int    blocks  = Input.Length / BlockSize;

            for (int i = 0; i < blocks; i++)
            {
                Cipher.Transform(Input, i * BlockSize, outData, i * BlockSize);
            }

            if (blocks * BlockSize < Input.Length)
            {
                // ctr tests only
                int    diff      = Input.Length - (blocks * BlockSize);
                byte[] inpBuffer = new byte[diff];
                int    offset    = Input.Length - diff;
                Buffer.BlockCopy(Input, offset, inpBuffer, 0, diff);
                byte[] outBuffer = new byte[diff];
                Cipher.Transform(inpBuffer, outBuffer);
                Buffer.BlockCopy(outBuffer, 0, outData, offset, diff);
            }

            return(outData);
        }
Exemple #23
0
        internal Transform(string KeyPath)
        {
            if (!File.Exists(KeyPath)) return;
            // get key and algorithm
            this.ProgressInterval = PRG_INTV;
            this.KeyPath = KeyPath;
            this.Engine = KeyHeader.GetEngineType(KeyPath);
            this.Key = GetKey(KeyPath);
            int rounds = GetRoundsSize(KeyPath);

            // stream ciphers
            if (this.Engine == Engines.ChaCha)
                StreamCipher = new ChaCha(rounds);
            else if (this.Engine == Engines.DCS)
                StreamCipher = new DCS();
            if (this.Engine == Engines.Salsa)
                StreamCipher = new Salsa20(rounds);
            if (this.Engine == Engines.Fusion)
                StreamCipher = new Fusion(rounds);

            this.BlockSize = 64;

            // get iv
            if (this.Engine != Engines.DCS )
                this.IV = GetIV(KeyPath);
            else
                this.BlockSize = (DCS_BLOCK * 4);

            // dcs, chacha and salsa are stream ciphers
            if (this.Engine == Engines.DCS || this.Engine == Engines.ChaCha || this.Engine == Engines.Salsa || this.Engine == Engines.Fusion)
                return;

            this.IsParallel = Environment.ProcessorCount > 1;

            // set params from key data
            this.BlockSize = KeyHeader.GetBlockSize(KeyPath) == BlockSizes.B128 ? 16 : 32;
            this.CipherMode = KeyHeader.GetCipherType(KeyPath);
            this.PaddingMode = KeyHeader.GetPaddingType(KeyPath);

            // block size
            if (this.IV != null && this.IV.Length > 0)
                this.BlockSize = this.IV.Length;
            else
                this.CipherMode = CipherModes.ECB;

            // padding selection
            if (this.PaddingMode == PaddingModes.PKCS7)
                Padding = new PKCS7();
            else if (this.PaddingMode == PaddingModes.X923)
                Padding = new X923();
            else if (this.PaddingMode == PaddingModes.Zeros)
                Padding = new ZeroPad();

            // create engine
            if (this.Engine == Engines.RDX)
                this.BlockCipher = new RDX(this.BlockSize);
            else if (this.Engine == Engines.RSM)
                this.BlockCipher = new RSM(rounds, this.BlockSize);
            else if (this.Engine == Engines.RSX)
                this.BlockCipher = new RSX(this.BlockSize);
            else if (this.Engine == Engines.RHX)
                this.BlockCipher = new RHX(rounds, this.BlockSize);
            else if (this.Engine == Engines.SPX)
                this.BlockCipher = new SPX(rounds);
            else if (this.Engine == Engines.SHX)
                this.BlockCipher = new SHX(rounds);
            else if (this.Engine == Engines.TFX)
                this.BlockCipher = new TFX(rounds);
            else if (this.Engine == Engines.THX)
                this.BlockCipher = new THX(rounds);
            else if (this.Engine == Engines.TSM)
                this.BlockCipher = new TSM(rounds);

            // create cipher
            if (this.CipherMode == CipherModes.CBC)
                this.Mode = new CBC(this.BlockCipher);
            else if (this.CipherMode == CipherModes.CTR)
                this.Mode = new CTR(this.BlockCipher);
            else if (this.CipherMode == CipherModes.ECB)
                this.Mode = new ECB(this.BlockCipher);
        }
Exemple #24
0
        public EngineSpeedTest(SymmetricEngines Engine, CipherModes Mode, int DataSize, int KeySize, int Rounds, bool Encryption, bool Parallel, TestTypes TestType = TestTypes.FileIO)
        {
            _cipherType = Mode;
            _dataSize = DataSize;
            _roundCount = Rounds;
            _engineType = Engine;
            _isEncryption = Encryption;
            _isParallel = Parallel;
            _keySize = KeySize;
            _keyParam = GetKeyParams();
            _testType = TestType;

            if (IsStreamCipher())
            {
                _streamCipher = GetStreamEngine();
                _streamCipher.Initialize(_keyParam);

                if (_isParallel && _engineType == SymmetricEngines.Fusion || _engineType == SymmetricEngines.Salsa)
                {
                    if (_dataSize > MB100)
                        _blockSize = MB100;
                    else if (DataSize > MB10)
                        _blockSize = MB10;
                    else if (DataSize > MB1)
                        _blockSize = MB1;
                    else
                        _blockSize = 1024;
                }
                else
                {
                    _blockSize = 64000;
                }
            }
            else
            {
                _cipherEngine = GetCipher();
                _cipherEngine.Initialize(_isEncryption, _keyParam);

                // set parallel
                if (_cipherEngine.GetType().Equals(typeof(CTR)))
                    ((CTR)_cipherEngine).IsParallel = _isParallel;
                else if (_cipherEngine.GetType().Equals(typeof(CBC)))
                    ((CBC)_cipherEngine).IsParallel = _isParallel;
                else if (_cipherEngine.GetType().Equals(typeof(CFB)))
                    ((CFB)_cipherEngine).IsParallel = _isParallel;

                // set block
                if (_isParallel && (_cipherType.Equals(CipherModes.CTR) ||
                    _cipherType.Equals(CipherModes.CBC) && !_isEncryption ||
                    _cipherType.Equals(CipherModes.CFB) && !_isEncryption))
                {
                    if (_dataSize > MB100)
                        _blockSize = MB100;
                    else if (DataSize > MB10)
                        _blockSize = MB10;
                    else if (DataSize > MB1)
                        _blockSize = MB1;
                    else
                        _blockSize = 1024;

                    if (_cipherEngine.GetType().Equals(typeof(CTR)))
                        ((CTR)_cipherEngine).ParallelBlockSize = _blockSize;
                    else if (_cipherEngine.GetType().Equals(typeof(CBC)))
                        ((CBC)_cipherEngine).ParallelBlockSize = _blockSize;
                    else if (_cipherEngine.GetType().Equals(typeof(CFB)))
                        ((CFB)_cipherEngine).ParallelBlockSize = _blockSize;
                }
                else
                {
                    _blockSize = _cipherEngine.BlockSize;
                }
            }

            _inputBuffer = new byte[_blockSize];
            _outputBuffer = new byte[_blockSize];
        }
Exemple #25
0
        internal Transform(string KeyPath)
        {
            if (!File.Exists(KeyPath))
            {
                return;
            }
            // get key and algorithm
            this.ProgressInterval = PRG_INTV;
            this.KeyPath          = KeyPath;
            this.Engine           = KeyHeader.GetEngineType(KeyPath);
            this.Key = GetKey(KeyPath);
            int rounds = GetRoundsSize(KeyPath);

            // stream ciphers
            if (this.Engine == Engines.ChaCha)
            {
                StreamCipher = new ChaCha(rounds);
            }
            else if (this.Engine == Engines.DCS)
            {
                StreamCipher = new DCS();
            }
            if (this.Engine == Engines.Salsa)
            {
                StreamCipher = new Salsa20(rounds);
            }
            if (this.Engine == Engines.Fusion)
            {
                StreamCipher = new Fusion(rounds);
            }

            this.BlockSize = 64;

            // get iv
            if (this.Engine != Engines.DCS)
            {
                this.IV = GetIV(KeyPath);
            }
            else
            {
                this.BlockSize = (DCS_BLOCK * 4);
            }

            // dcs, chacha and salsa are stream ciphers
            if (this.Engine == Engines.DCS || this.Engine == Engines.ChaCha || this.Engine == Engines.Salsa || this.Engine == Engines.Fusion)
            {
                return;
            }

            this.IsParallel = Environment.ProcessorCount > 1;

            // set params from key data
            this.BlockSize   = KeyHeader.GetBlockSize(KeyPath) == BlockSizes.B128 ? 16 : 32;
            this.CipherMode  = KeyHeader.GetCipherType(KeyPath);
            this.PaddingMode = KeyHeader.GetPaddingType(KeyPath);

            // block size
            if (this.IV != null && this.IV.Length > 0)
            {
                this.BlockSize = this.IV.Length;
            }
            else
            {
                this.CipherMode = CipherModes.ECB;
            }

            // padding selection
            if (this.PaddingMode == PaddingModes.PKCS7)
            {
                Padding = new PKCS7();
            }
            else if (this.PaddingMode == PaddingModes.X923)
            {
                Padding = new X923();
            }
            else if (this.PaddingMode == PaddingModes.Zeros)
            {
                Padding = new ZeroPad();
            }

            // create engine
            if (this.Engine == Engines.RDX)
            {
                this.BlockCipher = new RDX(this.BlockSize);
            }
            else if (this.Engine == Engines.RSM)
            {
                this.BlockCipher = new RSM(rounds, this.BlockSize);
            }
            else if (this.Engine == Engines.RSX)
            {
                this.BlockCipher = new RSX(this.BlockSize);
            }
            else if (this.Engine == Engines.RHX)
            {
                this.BlockCipher = new RHX(rounds, this.BlockSize);
            }
            else if (this.Engine == Engines.SPX)
            {
                this.BlockCipher = new SPX(rounds);
            }
            else if (this.Engine == Engines.SHX)
            {
                this.BlockCipher = new SHX(rounds);
            }
            else if (this.Engine == Engines.TFX)
            {
                this.BlockCipher = new TFX(rounds);
            }
            else if (this.Engine == Engines.THX)
            {
                this.BlockCipher = new THX(rounds);
            }
            else if (this.Engine == Engines.TSM)
            {
                this.BlockCipher = new TSM(rounds);
            }

            // create cipher
            if (this.CipherMode == CipherModes.CBC)
            {
                this.Mode = new CBC(this.BlockCipher);
            }
            else if (this.CipherMode == CipherModes.CTR)
            {
                this.Mode = new CTR(this.BlockCipher);
            }
            else if (this.CipherMode == CipherModes.ECB)
            {
                this.Mode = new ECB(this.BlockCipher);
            }
        }
Exemple #26
0
        /// <summary>
        /// Initialize the class with a CipherDescription Structure; containing the cipher implementation details, and a <see cref="KeyParams"/> class containing the Key material.
        /// <para>This constructor creates and configures cryptographic instances based on the cipher description contained in a CipherDescription. 
        /// Cipher modes, padding, and engines are destroyed automatically through this classes Dispose() method.</para>
        /// </summary>
        /// 
        /// <param name="Encryption">Cipher is an encryptor</param>
        /// <param name="KeyStream">A stream containing a <see cref="VolumeKey"/> and the keying material</param>
        /// 
        /// <exception cref="CryptoProcessingException">Thrown if an invalid <see cref="VolumeKey"/> is used</exception>
        public VolumeCipher(bool Encryption, Stream KeyStream)
        {
            _keyStream = KeyStream;
            _volumeKey = new VolumeKey(KeyStream);

            if (!CipherDescription.IsValid(_volumeKey.Description))
                throw new CryptoProcessingException("VolumeCipher:CTor", "The key Header is invalid!", new ArgumentException());

            _disposeEngine = true;
            _isEncryption = Encryption;
            _blockSize = _volumeKey.Description.BlockSize;
            _isParallel = false;
            CipherDescription desc = _volumeKey.Description;

            if (_isStreamCipher = IsStreamCipher((SymmetricEngines)desc.EngineType))
            {
                _streamCipher = GetStreamEngine((SymmetricEngines)desc.EngineType, desc.RoundCount, (Digests)desc.KdfEngine);

                if (_streamCipher.GetType().Equals(typeof(Fusion)))
                {
                    if (_isParallel = ((Fusion)_streamCipher).IsParallel)
                        _blockSize = ((Fusion)_streamCipher).ParallelBlockSize;
                }
            }
            else
            {
                _cipherEngine = GetCipher((CipherModes)desc.CipherType, (SymmetricEngines)desc.EngineType, desc.RoundCount, desc.BlockSize, (Digests)desc.KdfEngine);

                if (_isCounterMode = _cipherEngine.GetType().Equals(typeof(CTR)))
                {
                    if (_isParallel = ((CTR)_cipherEngine).IsParallel)
                        _blockSize = ((CTR)_cipherEngine).ParallelBlockSize;
                }
                else
                {
                    if (_cipherEngine.GetType().Equals(typeof(CBC)))
                    {
                        if (_isParallel = ((CBC)_cipherEngine).IsParallel && !((CBC)_cipherEngine).IsEncryption)
                            _blockSize = ((CBC)_cipherEngine).ParallelBlockSize;
                    }
                    else if (_cipherEngine.GetType().Equals(typeof(CFB)))
                    {
                        if (_isParallel = ((CFB)_cipherEngine).IsParallel && !((CFB)_cipherEngine).IsEncryption)
                            _blockSize = ((CFB)_cipherEngine).ParallelBlockSize;
                    }
                    _cipherPadding = GetPadding((PaddingModes)_volumeKey.Description.PaddingType);
                }
            }
        }
Exemple #27
0
        /// <summary>
        /// Transform an array with the symmetric cipher
        /// </summary>
        private byte[] SymmetricTransform(ICipherMode Cipher, byte[] Data)
        {
            byte[] ptext = new byte[Data.Length];
            Cipher.Transform(Data, ptext);

            return ptext;
        }
Exemple #28
0
 private void Dispose(bool Disposing)
 {
     if (!_isDisposed && Disposing)
     {
         try
         {
             if (_cipherType != null && _disposeEngine)
             {
                 _cipherType.Dispose();
                 _cipherType = null;
             }
             if (_msgCode != null)
             {
                 Array.Clear(_msgCode, 0, _msgCode.Length);
                 _msgCode = null;
             }
             if (_tmpZeroes != null)
             {
                 Array.Clear(_tmpZeroes, 0, _tmpZeroes.Length);
                 _tmpZeroes = null;
             }
             if (_wrkBuffer != null)
             {
                 Array.Clear(_wrkBuffer, 0, _wrkBuffer.Length);
                 _wrkBuffer = null;
             }
             if (_L != null)
             {
                 Array.Clear(_L, 0, _L.Length);
                 _L = null;
             }
             if (_LU != null)
             {
                 Array.Clear(_LU, 0, _LU.Length);
                 _LU = null;
             }
             if (_LU2 != null)
             {
                 Array.Clear(_LU2, 0, _LU2.Length);
                 _LU2 = null;
             }
         }
         finally
         {
             _isDisposed = true;
         }
     }
 }
Exemple #29
0
        /// <summary>
        /// Initialize the class
        /// </summary>
        /// <param name="Cipher">Instance of the block cipher</param>
        /// <param name="MacBits">Expected MAC return size in Bits; must be less or equal to Cipher Block size in bits</param>
        /// <param name="DisposeEngine">Dispose of digest engine when <see cref="Dispose()"/> on this class is called</param>
        /// 
        /// <exception cref="CryptoMacException">Thrown if an invalid Mac or block size is used</exception>
        public CMAC(IBlockCipher Cipher, int MacBits, bool DisposeEngine = true)
        {
            if ((MacBits % 8) != 0)
                throw new CryptoMacException("CMAC:Ctor", "MAC size must be multiple of 8!", new ArgumentOutOfRangeException());
            if (MacBits > (Cipher.BlockSize * 8))
                throw new CryptoMacException("CMAC:Ctor", String.Format("MAC size must be less or equal to {0}!", Cipher.BlockSize * 8), new ArgumentOutOfRangeException());
            if (Cipher.BlockSize != 8 && Cipher.BlockSize != 16)
                throw new CryptoMacException("CMAC:Ctor", "Block size must be either 64 or 128 bits!", new ArgumentException());

            _disposeEngine = DisposeEngine;
            _cipherType = new CBC(Cipher);
            _blockSize = _cipherType.BlockSize;
            _digestSize = MacBits / 8;
            _msgCode = new byte[_blockSize];
            _wrkBuffer = new byte[_blockSize];
            _tmpZeroes = new byte[_blockSize];
            _wrkOffset = 0;
        }
Exemple #30
0
 /// <summary>
 /// Initialize the class with a Block Cipher wrapped in a <see cref="VTDev.Libraries.CEXEngine.Crypto.Cipher.Symmetric.Block.Mode.ICipherMode">Cipher Mode</see>, and optional <see cref="VTDev.Libraries.CEXEngine.Crypto.Cipher.Symmetric.Block.Padding.IPadding">Padding</see> instances.
 /// <para>This constructor requires a fully initialized <see cref="VTDev.Libraries.CEXEngine.Crypto.Enumeration.CipherModes">CipherMode</see> instance.
 /// If the <see cref="VTDev.Libraries.CEXEngine.Crypto.Enumeration.PaddingModes">PaddingMode</see> parameter is null, X9.23 padding will be used if required.</para>
 /// </summary>
 ///
 /// <param name="Cipher">The <see cref="VTDev.Libraries.CEXEngine.Crypto.Enumeration.SymmetricEngines">Block Cipher</see> wrapped in a <see cref="VTDev.Libraries.CEXEngine.Crypto.Cipher.Symmetric.Block.Mode.ICipherMode">Cipher</see> mode</param>
 /// <param name="Padding">The <see cref="VTDev.Libraries.CEXEngine.Crypto.Cipher.Symmetric.Block.Padding.IPadding">Padding</see> instance</param>
 ///
 /// <exception cref="System.ArgumentNullException">Thrown if a null Cipher is used</exception>
 /// <exception cref="System.ArgumentException">Thrown if an uninitialized Cipher is used</exception>
 public CompressionCipher(ICipherMode Cipher, IPadding Padding = null) :
     base(Cipher, Padding)
 {
 }
Exemple #31
0
        private byte[] Transform2(ICipherMode Cipher, byte[] Data, int BlockSize)
        {
            // slower, mem copy can be expensive on large data..
            int blocks = Data.Length / BlockSize;
            byte[] outData = new byte[Data.Length];
            byte[] inBlock = new byte[BlockSize];
            byte[] outBlock = new byte[BlockSize];

            if (Cipher.Name == "CTR")
            {
                Cipher.Transform(Data, outData);
            }
            else
            {
                for (int i = 0; i < blocks; i++)
                {
                    Buffer.BlockCopy(Data, i * BlockSize, inBlock, 0, BlockSize);
                    Cipher.Transform(inBlock, outBlock);
                    Buffer.BlockCopy(outBlock, 0, outData, i * BlockSize, BlockSize);
                }

                if (blocks * BlockSize < Data.Length)
                    Cipher.Transform(Data, blocks * BlockSize, outData, blocks * BlockSize);
            }

            return outData;
        }
Exemple #32
0
        private byte[] Transform1(ICipherMode Cipher, byte[] Data, int BlockSize)
        {
            // best way, use the offsets
            int blocks = Data.Length / BlockSize;
            byte[] outData = new byte[Data.Length];

            for (int i = 0; i < blocks; i++)
                Cipher.Transform(Data, i * BlockSize, outData, i * BlockSize);

            // last partial in CTR
            if (blocks * BlockSize < Data.Length)
                Cipher.Transform(Data, blocks * BlockSize, outData, blocks * BlockSize);

            return outData;
        }
Exemple #33
0
 /// <summary>
 /// Initialize the class with a Block <see cref="ICipherMode">Cipher</see> and optional <see cref="IPadding">Padding</see> instances.
 /// <para>This constructor requires a fully initialized <see cref="VTDev.Libraries.CEXEngine.Crypto.Enumeration.CipherModes">CipherMode</see> instance.
 /// If the <see cref="VTDev.Libraries.CEXEngine.Crypto.Enumeration.PaddingModes">PaddingMode</see> parameter is null, X9.23 padding will be used if required.</para>
 /// </summary>
 /// 
 /// <param name="Compress">The volume cipher is in compression mode (encrypt)</param>
 /// <param name="Cipher">The <see cref="VTDev.Libraries.CEXEngine.Crypto.Enumeration.SymmetricEngines">Block Cipher</see> wrapped in a <see cref="ICipherMode">Cipher</see> mode</param>
 /// <param name="Padding">The <see cref="IPadding">Padding</see> instance</param>
 /// <param name="DisposeEngine">Dispose of cipher engine when Dispose() on this class is called</param>
 /// 
 /// <exception cref="System.ArgumentNullException">Thrown if a null <see cref="ICipherMode">Cipher</see> is used</exception>
 /// <exception cref="System.ArgumentException">Thrown if an uninitialized Cipher is used</exception>
 public CompressionCipher(bool Compress, ICipherMode Cipher, IPadding Padding = null, bool DisposeEngine = false)
     : base(Cipher, Padding, DisposeEngine)
 {
     _isCompression = Compress;
 }
Exemple #34
0
        public EngineSpeedTest(SymmetricEngines Engine, CipherModes Mode, int DataSize, int KeySize, int Rounds, bool Encryption, bool Parallel, TestTypes TestType = TestTypes.FileIO)
        {
            _cipherType   = Mode;
            _dataSize     = DataSize;
            _roundCount   = Rounds;
            _engineType   = Engine;
            _isEncryption = Encryption;
            _isParallel   = Parallel;
            _keySize      = KeySize;
            _keyParam     = GetKeyParams();
            _testType     = TestType;

            if (IsStreamCipher())
            {
                _streamCipher = GetStreamEngine();
                _streamCipher.Initialize(_keyParam);

                if (_isParallel && _engineType == SymmetricEngines.ChaCha || _engineType == SymmetricEngines.Salsa)
                {
                    if (_dataSize > MB100)
                    {
                        _blockSize = MB100;
                    }
                    else if (DataSize > MB10)
                    {
                        _blockSize = MB10;
                    }
                    else if (DataSize > MB1)
                    {
                        _blockSize = MB1;
                    }
                    else
                    {
                        _blockSize = 1024;
                    }

                    // align block
                    if (_isParallel)
                    {
                        _blockSize -= (_blockSize % (64 * Environment.ProcessorCount));
                    }
                }
                else
                {
                    _blockSize = 64000;
                }
            }
            else
            {
                _cipherEngine = GetCipher();
                _cipherEngine.Initialize(_isEncryption, _keyParam);

                // set parallel
                if (_cipherEngine.GetType().Equals(typeof(CTR)))
                {
                    ((CTR)_cipherEngine).IsParallel = _isParallel;
                }
                else if (_cipherEngine.GetType().Equals(typeof(CBC)))
                {
                    ((CBC)_cipherEngine).IsParallel = _isParallel;
                }
                else if (_cipherEngine.GetType().Equals(typeof(CFB)))
                {
                    ((CFB)_cipherEngine).IsParallel = _isParallel;
                }

                // set block
                if (_isParallel && (_cipherType.Equals(CipherModes.CTR) ||
                                    _cipherType.Equals(CipherModes.CBC) && !_isEncryption ||
                                    _cipherType.Equals(CipherModes.CFB) && !_isEncryption))
                {
                    if (_dataSize > MB100)
                    {
                        _blockSize = MB100;
                    }
                    else if (DataSize > MB10)
                    {
                        _blockSize = MB10;
                    }
                    else if (DataSize > MB1)
                    {
                        _blockSize = MB1;
                    }
                    else
                    {
                        _blockSize = 1024;
                    }

                    // align block
                    if (_isParallel)
                    {
                        _blockSize -= (_blockSize % (16 * Environment.ProcessorCount));
                    }

                    if (_cipherEngine.GetType().Equals(typeof(CTR)))
                    {
                        ((CTR)_cipherEngine).ParallelBlockSize = _blockSize;
                    }
                    else if (_cipherEngine.GetType().Equals(typeof(CBC)))
                    {
                        ((CBC)_cipherEngine).ParallelBlockSize = _blockSize;
                    }
                    else if (_cipherEngine.GetType().Equals(typeof(CFB)))
                    {
                        ((CFB)_cipherEngine).ParallelBlockSize = _blockSize;
                    }
                }
                else
                {
                    _blockSize = _cipherEngine.BlockSize;
                }
            }

            _inputBuffer  = new byte[_blockSize];
            _outputBuffer = new byte[_blockSize];
        }
Exemple #35
0
        /// <summary>
        /// Initialize the class with a CipherDescription Structure; containing the cipher implementation details, and a <see cref="KeyParams"/> class containing the Key material.
        /// <para>This constructor creates and configures cryptographic instances based on the cipher description contained in a CipherDescription.
        /// Cipher modes, padding, and engines are destroyed automatically through this classes Dispose() method.</para>
        /// </summary>
        ///
        /// <param name="Encryption">Cipher is an encryptor</param>
        /// <param name="Description">A <see cref="VTDev.Libraries.CEXEngine.Crypto.Common.CipherDescription"/> containing the cipher description</param>
        /// <param name="KeyParam">A <see cref="VTDev.Libraries.CEXEngine.Crypto.Common.KeyParams"/> class containing the encryption Key material</param>
        ///
        /// <exception cref="CryptoProcessingException">Thrown if an invalid CipherDescription or KeyParams is used</exception>
        public PacketCipher(bool Encryption, CipherDescription Description, KeyParams KeyParam)
        {
            if (!CipherDescription.IsValid(Description))
            {
                throw new CryptoProcessingException("PacketCipher:CTor", "The key Header is invalid!", new ArgumentException());
            }
            if (KeyParam == null)
            {
                throw new CryptoProcessingException("PacketCipher:CTor", "KeyParam can not be null!", new ArgumentNullException());
            }

            m_disposeEngine = true;
            m_isEncryption  = Encryption;
            m_blockSize     = Description.BlockSize;
            m_isParallel    = false;

            if (m_isStreamCipher = IsStreamCipher((SymmetricEngines)Description.EngineType))
            {
                m_streamCipher = GetStreamCipher((StreamCiphers)Description.EngineType, Description.RoundCount);
                m_streamCipher.Initialize(KeyParam);

                if (m_streamCipher.GetType().Equals(typeof(ChaCha20)))
                {
                    if (m_isParallel = ((ChaCha20)m_streamCipher).IsParallel)
                    {
                        m_blockSize = ((ChaCha20)m_streamCipher).ParallelBlockSize;
                    }
                }
                else
                {
                    if (m_isParallel = ((Salsa20)m_streamCipher).IsParallel)
                    {
                        m_blockSize = ((Salsa20)m_streamCipher).ParallelBlockSize;
                    }
                }
            }
            else
            {
                m_cipherEngine = GetCipherMode((CipherModes)Description.CipherType, (BlockCiphers)Description.EngineType, Description.BlockSize, Description.RoundCount, (Digests)Description.KdfEngine);
                m_cipherEngine.Initialize(m_isEncryption, KeyParam);

                if (m_isCounterMode = m_cipherEngine.GetType().Equals(typeof(CTR)))
                {
                    if (m_isParallel = ((CTR)m_cipherEngine).IsParallel)
                    {
                        m_blockSize = ((CTR)m_cipherEngine).ParallelBlockSize;
                    }
                }
                else
                {
                    if (m_cipherEngine.GetType().Equals(typeof(CBC)))
                    {
                        if (m_isParallel = ((CBC)m_cipherEngine).IsParallel && !((CBC)m_cipherEngine).IsEncryption)
                        {
                            m_blockSize = ((CBC)m_cipherEngine).ParallelBlockSize;
                        }
                    }
                    else if (m_cipherEngine.GetType().Equals(typeof(CFB)))
                    {
                        if (m_isParallel = ((CFB)m_cipherEngine).IsParallel && !((CFB)m_cipherEngine).IsEncryption)
                        {
                            m_blockSize = ((CFB)m_cipherEngine).ParallelBlockSize;
                        }
                    }
                }
            }
        }
Exemple #36
0
        /// <summary>
        /// Initialize the class with a CipherDescription Structure; containing the cipher implementation details, and a <see cref="KeyParams"/> class containing the Key material.
        /// <para>This constructor creates and configures cryptographic instances based on the cipher description contained in a CipherDescription. 
        /// Cipher modes, padding, and engines are destroyed automatically through this classes Dispose() method.</para>
        /// </summary>
        /// 
        /// <param name="Encryption">Cipher is an encryptor</param>
        /// <param name="Description">A <see cref="CipherDescription"/> containing the cipher description</param>
        /// <param name="KeyParam">A <see cref="KeyParams"/> class containing the encryption Key material</param>
        /// 
        /// <exception cref="CryptoProcessingException">Thrown if an invalid <see cref="CipherDescription">CipherDescription</see> or <see cref="KeyParams">KeyParams</see> is used</exception>
        public PacketCipher(bool Encryption, CipherDescription Description, KeyParams KeyParam)
        {
            if (!CipherDescription.IsValid(Description))
                throw new CryptoProcessingException("PacketCipher:CTor", "The key Header is invalid!", new ArgumentException());
            if (KeyParam == null)
                throw new CryptoProcessingException("PacketCipher:CTor", "KeyParam can not be null!", new ArgumentNullException());

            _disposeEngine = true;
            _isEncryption = Encryption;
            _blockSize = Description.BlockSize;
            _isParallel = false;

            if (_isStreamCipher = IsStreamCipher((SymmetricEngines)Description.EngineType))
            {
                _streamCipher = GetStreamEngine((SymmetricEngines)Description.EngineType, Description.RoundCount, (Digests)Description.KdfEngine);
                _streamCipher.Initialize(KeyParam);

                if (_streamCipher.GetType().Equals(typeof(Fusion)))
                {
                    if (_isParallel = ((Fusion)_streamCipher).IsParallel)
                        _blockSize = ((Fusion)_streamCipher).ParallelBlockSize;
                }
            }
            else
            {
                _cipherEngine = GetCipher((CipherModes)Description.CipherType, (SymmetricEngines)Description.EngineType, Description.RoundCount, Description.BlockSize, (Digests)Description.KdfEngine);
                _cipherEngine.Initialize(_isEncryption, KeyParam);

                if (_isCounterMode = _cipherEngine.GetType().Equals(typeof(CTR)))
                {
                    if (_isParallel = ((CTR)_cipherEngine).IsParallel)
                        _blockSize = ((CTR)_cipherEngine).ParallelBlockSize;
                }
                else
                {
                    if (_cipherEngine.GetType().Equals(typeof(CBC)))
                    {
                        if (_isParallel = ((CBC)_cipherEngine).IsParallel && !((CBC)_cipherEngine).IsEncryption)
                            _blockSize = ((CBC)_cipherEngine).ParallelBlockSize;
                    }
                    else if (_cipherEngine.GetType().Equals(typeof(CFB)))
                    {
                        if (_isParallel = ((CFB)_cipherEngine).IsParallel && !((CFB)_cipherEngine).IsEncryption)
                            _blockSize = ((CFB)_cipherEngine).ParallelBlockSize;
                    }
                }
            }
        }
Exemple #37
0
        /// <summary>
        /// Process the clients private identity.
        /// <para>Decrypts and stores the clients private identity using the clients Auth-Stage Symmetric Key.</para>
        /// </summary>
        /// 
        /// <param name="PacketStream">A Stream containing the raw packet data</param>
        private void ProcessAuth(MemoryStream PacketStream)
        {
            // get the header
            DtmPacket pktHdr = new DtmPacket(PacketStream);
            byte[] data = new byte[pktHdr.PayloadLength];
            PacketStream.Read(data, 0, data.Length);
            // create the clients auth-stage symmetric cipher
            _cltSymProcessor = SymmetricInit(_cltIdentity.Session, _cltKeyParams);
            // decrypt the payload
            byte[] dec = SymmetricTransform(_cltSymProcessor, data);
            // remove random padding
            dec = UnwrapMessage(dec);
            // get the clients private id
            _cltIdentity = new DtmIdentity(new MemoryStream(dec));

            // notify user
            long resp = 0;
            if (IdentityReceived != null)
            {
                DtmIdentityEventArgs args = new DtmIdentityEventArgs(DtmExchangeFlags.Auth, resp, _cltIdentity);
                IdentityReceived(this, args);
                resp = args.Flag;
                if (args.Cancel)
                {
                    // back out of session
                    TearDown();
                }
            }
        }
Exemple #38
0
        /// <summary>
        /// Sends the servers private identity; <see cref="DtmIdentity"/>, encrypted with the servers Symmetric Key.
        /// </summary>
        /// 
        /// <returns>A raw packet containing the packet header, and the servers private identity</returns>
        private MemoryStream CreateAuth()
        {
            // send secret id and return auth status in options flag
            _srvIdentity.Identity = _dtmHost.SecretId;
            // create the servers auth-stage symmetric cipher
            _srvSymProcessor = SymmetricInit(_srvIdentity.Session, _srvKeyParams);
            byte[] data = _srvIdentity.ToBytes();
            // wrap the id with random
            data = WrapMessage(data, _dtmParameters.MaxMessageAppend, _dtmParameters.MaxMessagePrePend);
            // encrypt the identity
            byte[] enc = SymmetricTransform(_srvSymProcessor, data);
            // payload container
            MemoryStream pldStm = new MemoryStream(enc);
            // stage completed
            _exchangeState = DtmExchangeFlags.Auth;

            return pldStm;
        }
Exemple #39
0
        /// <summary>
        /// Initialize the class with a Block <see cref="ICipherMode">Cipher</see> and optional <see cref="IPadding">Padding</see> instances.
        /// <para>This constructor requires a fully initialized <see cref="CipherModes">CipherMode</see> instance.
        /// If the <see cref="PaddingModes">PaddingMode</see> parameter is null, X9.23 padding will be used if required.</para>
        /// </summary>
        /// 
        /// <param name="Cipher">The <see cref="SymmetricEngines">Block Cipher</see> wrapped in a <see cref="ICipherMode">Cipher</see> mode</param>
        /// <param name="Padding">The <see cref="IPadding">Padding</see> instance</param>
        /// <param name="DisposeEngine">Dispose of cipher engine when <see cref="Dispose()"/> on this class is called</param>
        /// 
        /// <exception cref="CryptoProcessingException">Thrown if a null or uninitialized <see cref="ICipherMode">Cipher</see> is used</exception>
        public PacketCipher(ICipherMode Cipher, IPadding Padding = null, bool DisposeEngine = false)
        {
            if (Cipher == null)
                throw new CryptoProcessingException("PacketCipher:CTor", "The Cipher can not be null!", new ArgumentNullException());
            if (!Cipher.IsInitialized)
                throw new CryptoProcessingException("PacketCipher:CTor", "The Cipher has not been initialized!", new ArgumentException());

            _disposeEngine = DisposeEngine;
            _cipherEngine = Cipher;
            _isStreamCipher = false;
            _blockSize = _cipherEngine.BlockSize;
            _isEncryption = _cipherEngine.IsEncryption;
            _isParallel = false;

            if (_isCounterMode = _cipherEngine.GetType().Equals(typeof(CTR)))
            {
                if (_isParallel = ((CTR)_cipherEngine).IsParallel)
                    _blockSize = ((CTR)_cipherEngine).ParallelBlockSize;
            }
            else
            {
                if (_cipherEngine.GetType().Equals(typeof(CBC)))
                    _isParallel = ((CBC)_cipherEngine).IsParallel && !((CBC)_cipherEngine).IsEncryption;
            }
        }
Exemple #40
0
        /// <summary>
        /// The VPN is two-way established.
        /// <para>Note that SessionEstablished event is used, it is expected that processing will continue externally.
        /// In this case the post-exchange symmetric cipher instances are not initialized internally, 
        /// and the Send and Receive methods will throw an error, i.e. you can use either the event or the internal processors.</para>
        /// </summary>
        /// 
        /// <param name="PacketStream">A Stream containing the raw packet data</param>
        private void ProcessEstablish(MemoryStream PacketStream)
        {
            // clear the auth processors
            _srvSymProcessor.Dispose();
            _cltSymProcessor.Dispose();

            // initialize the Send/Receive encryption ciphers
            _srvSymProcessor = SymmetricInit(_srvIdentity.Session, _srvKeyParams);
            _cltSymProcessor = SymmetricInit(_cltIdentity.Session, _cltKeyParams);

            // one or the other
            if (SessionEstablished != null)
            {
                // app can continue processing out of class; must set the DestroyEngine flag to false in the constructor if this class is to be disposed
                DtmEstablishedEventArgs args = new DtmEstablishedEventArgs(_clientSocket.Client, _srvSymProcessor, _cltSymProcessor, 0);
                SessionEstablished(this, args);
            }

            _isEstablished = true;
        }
Exemple #41
0
 private void Dispose(bool Disposing)
 {
     if (!_isDisposed && Disposing)
     {
         try
         {
             if (_disposeEngine)
             {
                 if (_cipherEngine != null)
                 {
                     _cipherEngine.Dispose();
                     _cipherEngine = null;
                 }
                 if (_streamCipher != null)
                 {
                     _streamCipher.Dispose();
                     _streamCipher = null;
                 }
             }
         }
         finally
         {
             _isDisposed = true;
         }
     }
 }
Exemple #42
0
        /// <summary>
        /// Tear down the connection; destroys all structures provided by this class
        /// </summary>
        private void TearDown()
        {
            if (_rndGenerator != null)
            {
                _rndGenerator.Dispose();
                _rndGenerator = null;
            }
            if (_authKeyPair != null)
            {
                _authKeyPair.Dispose();
                _authKeyPair = null;
            }
            if (_cltAsmParams != null)
            {
                _cltAsmParams.Dispose();
                _cltAsmParams = null;
            }
            if (_cltPublicKey != null)
            {
                _cltPublicKey.Dispose();
                _cltPublicKey = null;
            }
            if (_primKeyPair != null)
            {
                _primKeyPair.Dispose();
                _primKeyPair = null;
            }
            // cipher streaming managed through class
            if (SessionEstablished == null || _disposeEngines == true)
            {
                if (_cltKeyParams != null)
                {
                    _cltKeyParams.Dispose();
                    _cltKeyParams = null;
                }
                if (_srvKeyParams != null)
                {
                    _srvKeyParams.Dispose();
                    _srvKeyParams = null;
                }
                if (_srvSymProcessor != null)
                {
                    _srvSymProcessor.Dispose();
                    _srvSymProcessor = null;
                }
                if (_cltSymProcessor != null)
                {
                    _cltSymProcessor.Dispose();
                    _cltSymProcessor = null;
                }
            }

            _bufferCount = 0;
            _bytesSent = 0;
            _bytesReceived = 0;
            _cltIdentity.Reset();
            _fileCounter = 0;
            _maxSendCounter = 0;
            _maxSendAttempts = MAXSNDATTEMPT;
            _rcvSequence = 0;
            _sndSequence = 0;
        }
Exemple #43
0
 private void Dispose(bool Disposing)
 {
     if (!_isDisposed && Disposing)
     {
         try
         {
             if (_disposeEngine)
             {
                 if (_cipherEngine != null)
                 {
                     _cipherEngine.Dispose();
                     _cipherEngine = null;
                 }
                 if (_cipherPadding != null)
                 {
                     _cipherPadding = null;
                 }
                 if (_streamCipher != null)
                 {
                     _streamCipher.Dispose();
                     _streamCipher = null;
                 }
             }
             if (_disposeStream)
             {
                 if (_inStream != null)
                 {
                     _inStream.Dispose();
                     _inStream = null;
                 }
                 if (_outStream != null)
                 {
                     _outStream.Dispose();
                     _outStream = null;
                 }
             }
         }
         finally
         {
             _isDisposed = true;
         }
     }
 }