Ejemplo n.º 1
0
 protected override byte[] GetExtensionData()
 {
     return(Label.GetBytes().Concatenate(BlockSize.GetBytes(),
                                         Packed.Print(),
                                         DelayTime.GetBytes(),
                                         ColorIndex.GetBytes()));
 }
Ejemplo n.º 2
0
        /// <summary>
        /// Определяет количество циклов
        /// </summary>
        /// <param name="blockSize"></param>
        /// <param name="keySize"></param>
        /// <returns></returns>
        private static int GetAmountRounds(BlockSize blockSize, KeySize keySize)
        {
            if (blockSize == BlockSize.Size128)
            {
                switch (keySize)
                {
                case KeySize.Size128:
                    return(10);

                case KeySize.Size192:
                    return(12);

                case KeySize.Size256:
                    return(14);
                }
            }
            else if (blockSize == BlockSize.Size192)
            {
                switch (keySize)
                {
                case KeySize.Size128:
                case KeySize.Size192:
                    return(12);

                case KeySize.Size256:
                    return(14);
                }
            }
            else if (blockSize == BlockSize.Size256)
            {
                return(14);
            }

            throw new Exception("Неверные размеры");
        }
Ejemplo n.º 3
0
    void Start()
    {
        active = (Behaviour)GetComponent("Halo");
        //active.enabled = false;
        //haloSprite.SetActive(false);

        active.enabled = true;
        haloSprite.SetActive(true);

        playerObj = GameObject.FindGameObjectWithTag("Player");
        pSize     = playerObj.GetComponent <PlayerSize>();
        blockSize = GetComponent <BlockSize>();

        rb    = GetComponent <Rigidbody2D>();
        state = GameObject.Find("Overlord").GetComponent <GameState>();
        //Start with the object frozen or not
        if (frozen)
        {
            rb.constraints = RigidbodyConstraints2D.FreezeAll;
            this.GetComponent <SpriteRenderer>().color = freezeColor;
        }
        else
        {
            snowParticalsSystem.Stop();
        }
        if (fly)
        {
            this.GetComponent <SpriteRenderer>().color = floatColor;
        }
        else
        {
            bubbleParticalsSystem.Stop();
        }
    }
Ejemplo n.º 4
0
        /// <summary>This version of DecryptData takes the encrypted message, password
        /// and IV as strings and decrypts the message, returning the plain text as a string.
        /// </summary>
        /// <param name="message">The encrypted message</param>
        /// <param name="password">The password/key that was used to encrypt the message</param>
        /// <param name="initialisationVector">The IV as a string</param>
        /// <param name="blockSize">The block size used in encrypting the message</param>
        /// <param name="keySize">The key size used in encrypting the message</param>
        /// <param name="cryptMode">The encryption mode, CBC or ECB, used in encrypting the message</param>
        /// <param name="messageAsHex">Whether the encrypted message was returned as Hex</param>
        public static string DecryptData(string message, string password,
                                         string initialisationVector, BlockSize blockSize,
                                         KeySize keySize, EncryptionMode cryptMode, bool messageAsHex)
        {
            byte[] messageData, passwordData, vectorData;

            // Dont do any work is the message is empty
            if (message.Length <= 0)
            {
                return("");
            }

            System.Text.UnicodeEncoding encoderUnicode = new System.Text.UnicodeEncoding();

            // Was message supplied in Hex or as simple string
            if (messageAsHex)
            {
                messageData = HexToBytes(message);
            }
            else
            {
                messageData = encoderUnicode.GetBytes(message);
            }

            // Convert key and IV to byte arrays
            passwordData = encoderUnicode.GetBytes(password);
            vectorData   = encoderUnicode.GetBytes(initialisationVector);

            // Return the decrypted plain test as a string
            return(encoderUnicode.GetString(DecryptData(messageData, passwordData,
                                                        vectorData, blockSize, keySize, cryptMode)));
        }
Ejemplo n.º 5
0
        private void SetNbNkNr(KeySize keySize, BlockSize blockSize)
        {
            int x = (int)(keySize);
            int y = (int)(blockSize);

            this.Nr = NbNkNr[x, y];

            if (KeySize.Bits128 == keySize)
            {
                this.Nk = 4;
            }
            else if (KeySize.Bits128 == keySize)
            {
                this.Nk = 6;
            }
            else if (KeySize.Bits256 == keySize)
            {
                this.Nk = 8;
            }

            if (BlockSize.Bits128 == blockSize)
            {
                this.Nb = 4;
            }
            else if (BlockSize.Bits128 == blockSize)
            {
                this.Nb = 6;
            }
            else if (BlockSize.Bits256 == blockSize)
            {
                this.Nb = 8;
            }
        }
Ejemplo n.º 6
0
        /// <summary>This version of EncryptData takes the message, password
        /// and IV as strings and encrypts the message, returning the encrypted text as a string.
        /// </summary>
        /// <param name="message">The plain text message</param>
        /// <param name="password">The password/key to encrypt the message with</param>
        /// <param name="initialisationVector">The IV as a string</param>
        /// <param name="blockSize">The block size used to encrypt the message</param>
        /// <param name="keySize">The key size used to encrypt the message</param>
        /// <param name="cryptMode">The encryption mode, CBC or ECB, used to encrypt the message</param>
        /// <param name="returnAsHex">Whether the encrypted message is to be returned as Hex</param>
        public static string EncryptData(string message, string password,
                                         string initialisationVector, BlockSize blockSize,
                                         KeySize keySize, EncryptionMode cryptMode, bool returnAsHex)
        {
            byte[] messageData, passwordData, vectorData;

            // If message is empty dont bother doing any work
            if (message.Length <= 0)
            {
                return("");
            }

            System.Text.UnicodeEncoding encoderUnicode = new System.Text.UnicodeEncoding();

            // Convert message, key and IV to byte arrays
            messageData  = encoderUnicode.GetBytes(message);
            passwordData = encoderUnicode.GetBytes(password);
            vectorData   = encoderUnicode.GetBytes(initialisationVector);

            // Return encrypted message as string (hex version of bytes if required)
            if (returnAsHex)
            {
                return(BytesToHex(EncryptData(messageData, passwordData,
                                              vectorData, blockSize, keySize, cryptMode)));
            }
            else
            {
                return(encoderUnicode.GetString(EncryptData(messageData, passwordData,
                                                            vectorData, blockSize, keySize, cryptMode)));
            }
        }
Ejemplo n.º 7
0
        public static int GetBlockSize(BlockSize blockSize)
        {
            switch (blockSize)
            {
            case BlockSize.bs128:
            {
                return(128);
            }

            case BlockSize.bs192:
            {
                return(192);
            }

            case BlockSize.bs256:
            {
                return(256);
            }

            default:
            {
                return(256);
            }
            }
        }
Ejemplo n.º 8
0
    private void Grow()
    {
        Debug.Log("Grow!");

        int random = Random.Range(0, 3);

        switch (blockSize)
        {
        case BlockSize.small:
            blockSize = BlockSize.medium;
            graphicsSlot.localScale             = new Vector3(MEDIUM_SIZE, MEDIUM_SIZE, MEDIUM_SIZE);
            GetComponent <BoxCollider2D>().size = new Vector2(MEDIUM_SIZE / 2, MEDIUM_SIZE * 1.2f);
            groundCheck.transform.localPosition = new Vector2(0, MEDIUM_SIZE / -2);

            if (random == 0)
            {
                audioManager.interactionSound(interactionSounds.grow1);
            }
            else if (random == 1)
            {
                audioManager.interactionSound(interactionSounds.grow2);
            }
            else
            {
                audioManager.interactionSound(interactionSounds.grow3);
            }

            break;

        case BlockSize.medium:
            blockSize = BlockSize.large;
            graphicsSlot.localScale             = new Vector3(LARGE_SIZE, LARGE_SIZE, LARGE_SIZE);
            GetComponent <BoxCollider2D>().size = new Vector2(LARGE_SIZE / 2, LARGE_SIZE * 1.2f);
            groundCheck.transform.localPosition = new Vector2(0, LARGE_SIZE / -2);

            if (random == 0)
            {
                audioManager.interactionSound(interactionSounds.grow1);
            }
            else if (random == 1)
            {
                audioManager.interactionSound(interactionSounds.grow2);
            }
            else
            {
                audioManager.interactionSound(interactionSounds.grow3);
            }

            break;

        case BlockSize.large:
            blockSize = BlockSize.large;
            graphicsSlot.localScale             = new Vector3(LARGE_SIZE, LARGE_SIZE, LARGE_SIZE);
            GetComponent <BoxCollider2D>().size = new Vector2(LARGE_SIZE / 2, LARGE_SIZE * 1.2f);
            groundCheck.transform.localPosition = new Vector2(0, LARGE_SIZE / -2);

            break;
        }
    }
Ejemplo n.º 9
0
 /// <summary>
 ///     Returns the encryption IV to be used with the Rijndael algorithm
 /// </summary>
 public static byte[] GenerateIV(KeySize keySize, BlockSize blockSize)
 {
     using (var rm = GetRijndaelManaged(null, null, keySize, blockSize))
     {
         rm.GenerateIV();
         return(rm.IV);
     }
 }
Ejemplo n.º 10
0
 public GrigView(IMyCubeGrid cubeGrid)
 {
     this.id   = cubeGrid.EntityId.ToString(SEAUtilities.CultureInfoUS);
     this.name = cubeGrid.DisplayName;
     this.size = cubeGrid.GridSizeEnum == VRage.Game.MyCubeSize.Small ?
                 BlockSize.small : (cubeGrid.IsStatic ?
                                    BlockSize.station :
                                    BlockSize.large);
 }
Ejemplo n.º 11
0
 public override string ToString()
 {
     return(string.Format(
                "Blocks\tBlockIndex:{0},StartPosition:{1},BlockSize:{2},CompletedPosition:{3},FilePath:{4}",
                BlockIndex.ToString(),
                StartPosition.ToString(),
                BlockSize.ToString(),
                CompletedPosition.ToString(),
                FilePath));
 }
Ejemplo n.º 12
0
 public override string ToString()
 {
     return(string.Format(
                "Apply\tLastModified:{0},FileSize:{1},AllowRanges:{2},BlockSize:{3},ActuallyChunks{4}",
                LastModified.ToString("yyyy-MM-dd HH:mm:ss"),
                FileSize.ToString(),
                AllowRanges.ToString(),
                BlockSize.ToString(),
                ActuallyChunks.ToString()
                ));
 }
Ejemplo n.º 13
0
        /// <summary>
        /// Returns a hash code for this instance.
        /// </summary>
        /// <returns>
        /// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.
        /// </returns>
        public override int GetHashCode()
        {
            var hashCode = -16010822;

            hashCode = hashCode * -1521134295 + BlockSize.GetHashCode();
            hashCode = hashCode * -1521134295 + Encoding.GetHashCode();
            hashCode = hashCode * -1521134295 + ExtraSize.GetHashCode();
            hashCode = hashCode * -1521134295 + Channels.GetHashCode();
            hashCode = hashCode * -1521134295 + SampleRate.GetHashCode();
            hashCode = hashCode * -1521134295 + BitDepth.GetHashCode();
            return(hashCode);
        }
Ejemplo n.º 14
0
 private void Init(BlockSize blockSize, KeySize keySize)
 {
     if (blockSize == BlockSize.B128)
     {
         Nb = 2;
         if (keySize == KeySize.K128)
         {
             Nk = 2;
             Nr = 10;
         }
         else if (keySize == KeySize.K256)
         {
             Nk = 4;
             Nr = 14;
         }
         else
         {
             throw new ArgumentNullException("Key size not supported");
         }
     }
     else if (blockSize == BlockSize.B256)
     {
         Nb = 4;
         if (keySize == KeySize.K256)
         {
             Nk = 4;
             Nr = 14;
         }
         else if (keySize == KeySize.K512)
         {
             Nk = 8;
             Nr = 18;
         }
         else
         {
             throw new ArgumentNullException("Key size not supported");
         }
     }
     else
     {
         Nb = 8;
         if (keySize == KeySize.K512)
         {
             Nk = 8;
             Nr = 18;
         }
         else
         {
             throw new ArgumentNullException("Key size not supported");
         }
     }
 }
Ejemplo n.º 15
0
 protected override byte[] GetExtensionData()
 {
     return(Label.GetBytes().Concatenate(BlockSize.GetBytes(),
                                         TextGridLeft.GetBytes(),
                                         TextGridTop.GetBytes(),
                                         TextGridWidth.GetBytes(),
                                         TextGridHeight.GetBytes(),
                                         CellWidth.GetBytes(),
                                         CellHeight.GetBytes(),
                                         TextFgColorIndex.GetBytes(),
                                         TextBgColorIndex.GetBytes(),
                                         PlainTextData.StringToBuff()));
 }
Ejemplo n.º 16
0
        public Aes(KeySize keySize, byte[] keyBytes, BlockSize blockSize)
        {
            BuildNaNkNr();

            SetNbNkNr(keySize, blockSize);

            this.key = new byte[this.Nk * 4];  // 16, 24, 32 bytes


            BuildSbox();
            BuildInvSbox();
            BuildRcon();
            KeyExpansion();
        }
Ejemplo n.º 17
0
    void SpawnNewBlock()
    {
        // Random value between 0 and 2 to assign size of block.
        BlockSize blockSize = BlockSize.Normal;

        // Determine size of next block (2x2, 3x3, etc...)
        BlockType[] nextBlock;
        if (!MultiSizedBlocks)
        {
            nextBlock = new BlockType[4];
        }
        else
        {
            // Determine if next block is 2x2, 2x3 or 3x2
            blockSize = GetRandomBlockSize();

            // 1/3rd chance for 2x2, otherwise needs 6 spaces for the block
            if (blockSize == 0)
            {
                nextBlock = new BlockType[4];
            }
            else
            {
                nextBlock = new BlockType[6];
            }
        }

        // Set 'CurrBlock' based on block size (2x2, 3x3, etc...)
        int startX = BoardWidth / 2;
        int startY = BoardHeight - 2;

        // If starting block is 3 high, move the startY down;
        if (blockSize == BlockSize.Tall)
        {
            startY = BoardHeight - 3;
        }

        // Randomly determine the blocks for the array
        for (int i = 0; i < nextBlock.Length; ++i)
        {
            nextBlock[i] = GetRandomBlockColor();
        }

        // Always initialize the first four blocks (NEED TO CONSIDER as rotating 3x2 or 2x3 changes things up!!!)
        SetBlockCluster(nextBlock, blockSize);

        // Set array of blocks to populate
        // TEST
        SetBlockAtPosition(BlockType.Red, startX, startY);
    }
Ejemplo n.º 18
0
        /// <summary>
        /// Устанавливает первичные настройки для блоков текста и ключа
        /// </summary>
        /// <param name="blockSize"></param>
        /// <param name="keySize"></param>
        /// <param name="key"></param>
        public void SetSettings(BlockSize blockSize, KeySize keySize, byte[] key)
        {
            var keyLengthInBytes = RijndaelSizesConverter.KeySizeToInt(keySize) / 8;

            if (key.Length != keyLengthInBytes)
            {
                throw new Exception("Неверная длина ключа");
            }

            _blockSize = blockSize;
            _keySize   = keySize;
            _key       = key;

            GenerateKeyExpansion();
        }
Ejemplo n.º 19
0
        private static TxSize ReadTxSize(ref Vp9Common cm, ref MacroBlockD xd, bool allowSelect, ref Reader r)
        {
            TxMode    txMode    = cm.TxMode;
            BlockSize bsize     = xd.Mi[0].Value.SbType;
            TxSize    maxTxSize = Luts.MaxTxSizeLookup[(int)bsize];

            if (allowSelect && txMode == TxMode.TxModeSelect && bsize >= BlockSize.Block8x8)
            {
                return(ReadSelectedTxSize(ref cm, ref xd, maxTxSize, ref r));
            }
            else
            {
                return((TxSize)Math.Min((int)maxTxSize, (int)Luts.TxModeToBiggestTxSize[(int)txMode]));
            }
        }
    // Update is called once per frame
    void Update()
    {
        while (player != null && blockArrowPointer < player.transform.position.x + safeMargin)
        {
            int        value        = Random.Range(0, blocks.Length);
            GameObject blocksPrefab = Instantiate(blocks[value]);
            BlockSize  bs           = blocksPrefab.GetComponent <BlockSize>();
            blocksPrefab.transform.position = new Vector3(blockArrowPointer + bs.blocksize / 2, 0, 0);
            blockArrowPointer += bs.blocksize;
        }

        if (player != null)
        {
            camfollow.transform.position = new Vector3(player.transform.position.x, camfollow.transform.position.y, camfollow.transform.position.z);
        }
    }
Ejemplo n.º 21
0
        internal string ToFeedbackString()
        {
            var info = $@"{ApplicationFullVersion}
{ApplicationDescription}

";

            var repoDefaults = new Repository();

            var colInfo = new int[] { 0, 30, 65, 75 };
            var table   = new List <string[]>()
            {
                new string[] { "Configuration entry", "Description", "Value", "Default" },
                new string[] { "===================", "===========", "=====", "=======" },
                Array.Empty <string>(),
                new string[] { nameof(UploadFolder), "Upload Folder", UploadFolder, repoDefaults.UploadFolder },
                new string[] { nameof(ArchiveFolder), "Archive Folder", ArchiveFolder, repoDefaults.ArchiveFolder },
                new string[] { nameof(TransferCheckpointFilename), "Transfer Checkpoint Filename", TransferCheckpointFilename, repoDefaults.TransferCheckpointFilename },
                new string[] { nameof(BlockSize), "Tx Block Size", BlockSize.ToSizeSuffix(), repoDefaults.BlockSize.ToSizeSuffix() },
                new string[] { nameof(ParallelOperations), "Parallel Operations", ParallelOperations.ToString(), repoDefaults.ParallelOperations.ToString() },
                new string[] { nameof(DefaultConnectionLimit), "Default Connection Limit", DefaultConnectionLimit.ToString(), repoDefaults.DefaultConnectionLimit.ToString() },
                new string[] { nameof(Expect100Continue), "Wait for '100' response?", Expect100Continue.ToString(), repoDefaults.Expect100Continue.ToString() },
                new string[] { nameof(Recursive), "Recurse the upload folder", Recursive.ToString(), repoDefaults.Recursive.ToString() },
                Array.Empty <string>(),
                new string[] { nameof(BlobContainerUri), "Azure Blob Container", BlobDirectory?.Uri.ToString(), repoDefaults.BlobDirectory?.Uri.ToString() },
                new string[] { nameof(FileContainerUri), "Azure File Directory", FileDirectory?.Uri.ToString(), repoDefaults.FileDirectory?.Uri.ToString() },
                Array.Empty <string>(),
                new string[] { "For details of the configuration options see: https://github.com/Azure/azure-storage-net-data-movement/" },
            };

            table.ForEach(row =>
            {
                var line = "";
                for (int i = 0; i < row.Length; i++)
                {
                    if (line.Length > colInfo[i])
                    {
                        info = info.TrimEnd(' ') + $"\n{line}";
                        line = string.Empty;
                    }
                    line = $"{line.PadRight(colInfo[i])}{row[i]} ";
                }
                info = info.TrimEnd(' ') + $"\n{line}";
            });

            return(info);
        }
Ejemplo n.º 22
0
        private byte[] Encrypt(byte[] toEncrypt, byte[] pwd, KeySize keySize, BlockSize blockSize)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                using (RijndaelManaged rm = new RijndaelManaged())
                {
                    rm.KeySize   = (int)keySize;
                    rm.BlockSize = (int)blockSize;

                    var key = new Rfc2898DeriveBytes(pwd, GetRandomBytes(), 1000);
                    rm.Key = key.GetBytes(rm.KeySize / 8);
                    rm.IV  = key.GetBytes(rm.BlockSize / 8);
                }
            }

            throw new NotImplementedException();
        }
Ejemplo n.º 23
0
    // Update is called once per frame
    void Update()
    {
        while (player != null && blockArrowPointer < player.transform.position.x + safeMargin)
        {
            int        value        = Random.Range(0, blocks.Length);
            GameObject blocksPrefab = Instantiate(blocks[value]);
            BlockSize  bs           = blocksPrefab.GetComponent <BlockSize>();
            blocksPrefab.transform.position = new Vector3(blockArrowPointer + bs.blocksize / 2, 0, 0);
            blockArrowPointer += bs.blocksize;
        }

        if (player != null)
        {
            score          = score + Time.deltaTime;
            ScoreText.text = ("Score:") + Mathf.RoundToInt(score).ToString();
            camfollow.transform.position = new Vector3(player.transform.position.x, camfollow.transform.position.y, camfollow.transform.position.z);
        }
    }
Ejemplo n.º 24
0
        public static int BlockSizeToInt(BlockSize blockSize)
        {
            {
                switch (blockSize)
                {
                case BlockSize.Size128:
                    return(128);

                case BlockSize.Size192:
                    return(192);

                case BlockSize.Size256:
                    return(256);

                default:
                    throw new ArgumentOutOfRangeException(nameof(blockSize), blockSize, null);
                }
            }
        }
Ejemplo n.º 25
0
        /// <summary>
        /// Устанавливает первичные настройки для блоков текста и ключа
        /// </summary>
        /// <param name="blockSize"></param>
        /// <param name="keySize"></param>
        /// <param name="key"></param>
        public void SetSettings(BlockSize blockSize, KeySize keySize, string key)
        {
            if (key.Length % 2 != 0)
            {
                throw new Exception("Bad key length");
            }

            var bytes = new byte[key.Length / 2];

            var index = 0;

            while (key.Length > 0)
            {
                var tmp = key.Substring(0, 2);
                key = key.Substring(2, key.Length - 2);

                bytes[index] = (byte)Convert.ToInt32(tmp, 16);
                index++;
            }

            SetSettings(blockSize, keySize, bytes);
        }
Ejemplo n.º 26
0
        /// <summary>
        ///     Creates a RijndaelManaged cipher based on the given key material and the given block and key size.
        /// </summary>
        /// <param name="key">The (HEXADECIMAL) key used during the creation of the cipher for encryption</param>
        /// <param name="blockSize">Block size of the cipher</param>
        /// <param name="keySize">Key Size of the cipher</param>
        public CommandResult <RijndaelManaged> CreateCustomCipher(string key, BlockSize blockSize, AesKeySize keySize)
        {
            if (String.IsNullOrWhiteSpace(key))
            {
                return(CommandResultFactory.Fail("There was no key provided for the cipher", (RijndaelManaged)null));
            }

            byte[] byteKey;
            try
            {
                byteKey = key.ToHexBytes();
                if (byteKey == null || byteKey.Length != (int)keySize / 8)
                {
                    return(CommandResultFactory.Fail($"The cipher creation key for the encryption did not match the specified key size of {keySize}", (RijndaelManaged)null));
                }
            }
            catch (FormatException)
            {
                return(CommandResultFactory.Fail("The key was malformed and therefore threw a Format Exception when converting to a byte array.", (RijndaelManaged)null));
            }
            catch (Exception e)
            {
                return(CommandResultFactory.Fail($"There was an exception thrown while trying to create the cipher. It is as follows:\n\t{e.Message}", (RijndaelManaged)null));
            }

            var cipher = new RijndaelManaged
            {
                KeySize   = (int)keySize,
                BlockSize = (int)blockSize,
                Padding   = PaddingMode.ISO10126,
                Mode      = CipherMode.CBC,
                Key       = byteKey
            };

            return(CommandResultFactory.Ok(cipher));
        }
Ejemplo n.º 27
0
        /// <summary>This version of DecryptData takes the encrypted message, password 
        /// and IV as byte arrays and decrypts the message, returning the plain text as 
        /// a byte array.
        /// </summary>
        /// <param name="message">The encrypted message</param>
        /// <param name="password">The password/key that was used to encrypt the message</param>
        /// <param name="initialisationVector">The IV</param>
        /// <param name="blockSize">The block size used in encrypting the message</param>
        /// <param name="keySize">The key size used in encrypting the message</param>
        /// <param name="cryptMode">The encryption mode, CBC or ECB, used in encrypting the message</param>
        public static byte[] DecryptData(byte[] message, byte[] password,
            byte[] initialisationVector, BlockSize blockSize,
            KeySize keySize, EncryptionMode cryptMode)
        {
            byte[] messageData, keyBlock, vectorBlock, dataBlock;
            int messageLength, encodedLength, nb, nk;

            // Dont do any work if message is empty
            encodedLength = message.Length;
            if (encodedLength <= 0)
                return message;

            // Set up arrays based on block size
            switch (blockSize)
            {
                case BlockSize.Block128:
                    nb = 4;
                    break;
                case BlockSize.Block192:
                    nb = 6;
                    break;
                default:	// assume 256
                    nb = 8;
                    break;
            }

            vectorBlock = new byte[nb * 4];
            dataBlock = new byte[nb * 4];

            for (int i = 0; i < (nb * 4); i++)
            {
                vectorBlock[i] = 0;
                dataBlock[i] = 0;
            }

            // Set up array based on key size
            switch (keySize)
            {
                case KeySize.Key128:
                    nk = 4;
                    break;
                case KeySize.Key192:
                    nk = 6;
                    break;
                default:	// assume 256
                    nk = 8;
                    break;
            }

            keyBlock = new byte[nk * 4];

            for (int i = 0; i < (nk * 4); i++)
            {
                keyBlock[i] = 0;
            }

            // Key will be zero padded, or trimmed to correct size
            for (int i = 0; (i < password.Length) && (i < (nk * 4)); i++)
                keyBlock[i] = password[i];

            // Vector will be zero padded, or trimmed to correct size
            for (int i = 0; (i < initialisationVector.Length) && (i < (nb * 4)); i++)
                vectorBlock[i] = initialisationVector[i];

            // Prepare the key and tables using the Rijndael fuinctions
            gentables();
            gkey(nb, nk, keyBlock);

            // Decrypt a block at a time
            for (int i = 0; i < encodedLength; i += (nb * 4))
            {
                Array.Copy(message, i, dataBlock, 0, (nb * 4));

                decrypt(dataBlock);

                // If CBC mode we need to do some extra XORing
                if (cryptMode == EncryptionMode.ModeCBC)
                {
                    for (int j = 0; j < (nb * 4); j++)
                        dataBlock[j] ^= vectorBlock[j];

                    Array.Copy(message, i, vectorBlock, 0, (nb * 4));
                }

                Array.Copy(dataBlock, 0, message, i, (nb * 4));
            }

            // Message length was originally put on front of message, so retrieve it
            messageLength = (int)message[0] | (((int)message[1]) << 8) |
                (((int)message[2]) << 16) | (((int)message[3]) << 24);

            // Get the original message from the clear text
            messageData = new byte[messageLength];
            Array.Copy(message, 4, messageData, 0, messageLength);

            return messageData;
        }
Ejemplo n.º 28
0
 public void Validate()
 {
     if (this.GetEncoderModeIndex() < 0)
     {
         throw new Exception("unsupported encoder mode");
     }
     this.SetDefaultValuesForMode();
     if (Padding < 0)
     {
         throw new Exception("unsupported padding value " + Padding.ToString());
     }
     if (BlockSize != 0 && (BlockSize < 256 || BlockSize >= FlakeConstants.MAX_BLOCKSIZE))
     {
         throw new Exception("unsupported block size " + BlockSize.ToString());
     }
     if (MinLPCOrder > MaxLPCOrder || MaxLPCOrder > lpc.MAX_LPC_ORDER)
     {
         throw new Exception("invalid MaxLPCOrder " + MaxLPCOrder.ToString());
     }
     if (MinFixedOrder < 0 || MinFixedOrder > 4)
     {
         throw new Exception("invalid MinFixedOrder " + MinFixedOrder.ToString());
     }
     if (MaxFixedOrder < 0 || MaxFixedOrder > 4)
     {
         throw new Exception("invalid MaxFixedOrder " + MaxFixedOrder.ToString());
     }
     if (MinPartitionOrder < 0)
     {
         throw new Exception("invalid MinPartitionOrder " + MinPartitionOrder.ToString());
     }
     if (MinPartitionOrder > MaxPartitionOrder || MaxPartitionOrder > 8)
     {
         throw new Exception("invalid MaxPartitionOrder " + MaxPartitionOrder.ToString());
     }
     if (PredictionType == PredictionType.None)
     {
         throw new Exception("invalid PredictionType " + PredictionType.ToString());
     }
     if (PredictionType != PredictionType.Fixed)
     {
         if (WindowMethod == WindowMethod.Invalid)
         {
             throw new InvalidOperationException("invalid WindowMethod " + WindowMethod.ToString());
         }
         if (WindowFunctions == WindowFunction.None)
         {
             throw new InvalidOperationException("invalid WindowFunctions " + WindowFunctions.ToString());
         }
         if (EstimationDepth > 32 || EstimationDepth < 1)
         {
             throw new InvalidOperationException("invalid EstimationDepth " + EstimationDepth.ToString());
         }
         if (MinPrecisionSearch < 0 || MinPrecisionSearch >= lpc.MAX_LPC_PRECISIONS)
         {
             throw new Exception("unsupported MinPrecisionSearch value");
         }
         if (MaxPrecisionSearch < 0 || MaxPrecisionSearch >= lpc.MAX_LPC_PRECISIONS)
         {
             throw new Exception("unsupported MaxPrecisionSearch value");
         }
         if (MaxPrecisionSearch < MinPrecisionSearch)
         {
             throw new Exception("unsupported MaxPrecisionSearch value");
         }
     }
     if (!AllowNonSubset && !IsSubset())
     {
         throw new Exception("the encoding parameters specified do not conform to the FLAC Subset");
     }
 }
Ejemplo n.º 29
0
 /// <summary>
 /// Creates a new generic instance of the Huffman compression format.
 /// </summary>
 /// <param name="blockSize">The block size used.</param>
 internal Huffman(BlockSize blockSize)
     : base((byte)blockSize)
 {
     this.CompressBlockSize = blockSize;
 }
Ejemplo n.º 30
0
        public override int GetHashCode()
        {
            int hash = 1;

            if (Id.Length != 0)
            {
                hash ^= Id.GetHashCode();
            }
            if (FolderId.Length != 0)
            {
                hash ^= FolderId.GetHashCode();
            }
            if (createdAt_ != null)
            {
                hash ^= CreatedAt.GetHashCode();
            }
            if (Name.Length != 0)
            {
                hash ^= Name.GetHashCode();
            }
            if (Description.Length != 0)
            {
                hash ^= Description.GetHashCode();
            }
            hash ^= Labels.GetHashCode();
            if (TypeId.Length != 0)
            {
                hash ^= TypeId.GetHashCode();
            }
            if (ZoneId.Length != 0)
            {
                hash ^= ZoneId.GetHashCode();
            }
            if (Size != 0L)
            {
                hash ^= Size.GetHashCode();
            }
            if (BlockSize != 0L)
            {
                hash ^= BlockSize.GetHashCode();
            }
            hash ^= productIds_.GetHashCode();
            if (Status != global::Yandex.Cloud.Compute.V1.Disk.Types.Status.Unspecified)
            {
                hash ^= Status.GetHashCode();
            }
            if (sourceCase_ == SourceOneofCase.SourceImageId)
            {
                hash ^= SourceImageId.GetHashCode();
            }
            if (sourceCase_ == SourceOneofCase.SourceSnapshotId)
            {
                hash ^= SourceSnapshotId.GetHashCode();
            }
            hash ^= instanceIds_.GetHashCode();
            if (diskPlacementPolicy_ != null)
            {
                hash ^= DiskPlacementPolicy.GetHashCode();
            }
            hash ^= (int)sourceCase_;
            if (_unknownFields != null)
            {
                hash ^= _unknownFields.GetHashCode();
            }
            return(hash);
        }
Ejemplo n.º 31
0
        public override long Decompress(Stream instream, long inLength, Stream outstream)
        {
            #region GBATEK format specification

            /*
             *  Data Header (32bit)
             *      Bit0-3   Data size in bit units (normally 4 or 8)
             *      Bit4-7   Compressed type (must be 2 for Huffman)
             *      Bit8-31  24bit size of decompressed data in bytes
             *  Tree Size (8bit)
             *      Bit0-7   Size of Tree Table/2-1 (ie. Offset to Compressed Bitstream)
             *  Tree Table (list of 8bit nodes, starting with the root node)
             *      Root Node and Non-Data-Child Nodes are:
             *      Bit0-5   Offset to next child node,
             *              Next child node0 is at (CurrentAddr AND NOT 1)+Offset*2+2
             *              Next child node1 is at (CurrentAddr AND NOT 1)+Offset*2+2+1
             *      Bit6     Node1 End Flag (1=Next child node is data)
             *      Bit7     Node0 End Flag (1=Next child node is data)
             *      Data nodes are (when End Flag was set in parent node):
             *      Bit0-7   Data (upper bits should be zero if Data Size is less than 8)
             *  Compressed Bitstream (stored in units of 32bits)
             *      Bit0-31  Node Bits (Bit31=First Bit)  (0=Node0, 1=Node1)
             */
            #endregion

            long readBytes = 0;

            byte      type      = (byte)instream.ReadByte();
            BlockSize blockSize = BlockSize.FOURBIT;
            if (type != (byte)blockSize)
            {
                blockSize = BlockSize.EIGHTBIT;
            }
            if (type != (byte)blockSize)
            {
                throw new InvalidDataException(String.Format(Main.Get_Traduction("S05"), type.ToString("X")));
            }
            byte[] sizeBytes = new byte[3];
            instream.Read(sizeBytes, 0, 3);
            int decompressedSize = IOUtils.ToNDSu24(sizeBytes, 0);
            readBytes += 4;
            if (decompressedSize == 0)
            {
                sizeBytes = new byte[4];
                instream.Read(sizeBytes, 0, 4);
                decompressedSize = IOUtils.ToNDSs32(sizeBytes, 0);
                readBytes       += 4;
            }

            #region Read the Huff-tree

            if (readBytes >= inLength)
            {
                throw new NotEnoughDataException(0, decompressedSize);
            }
            int treeSize = instream.ReadByte(); readBytes++;
            if (treeSize < 0)
            {
                throw new InvalidDataException(Main.Get_Traduction("S06"));
            }

            treeSize = (treeSize + 1) * 2;

            if (readBytes + treeSize >= inLength)
            {
                throw new InvalidDataException(Main.Get_Traduction("S07"));
            }

            long treeEnd = (instream.Position - 1) + treeSize;

            // the relative offset may be 4 more (when the initial decompressed size is 0), but
            // since it's relative that doesn't matter, especially when it only matters if
            // the given value is odd or even.
            HuffTreeNode rootNode = new HuffTreeNode(instream, false, 5, treeEnd);

            readBytes += treeSize;
            // re-position the stream after the tree (the stream is currently positioned after the root
            // node, which is located at the start of the tree definition)
            instream.Position = treeEnd;

            #endregion

            // the current u32 we are reading bits from.
            uint data = 0;
            // the amount of bits left to read from <data>
            byte bitsLeft = 0;

            // a cache used for writing when the block size is four bits
            int cachedByte = -1;

            // the current output size
            int          currentSize = 0;
            HuffTreeNode currentNode = rootNode;
            byte[]       buffer      = new byte[4];

            while (currentSize < decompressedSize)
            {
                #region find the next reference to a data node
                while (!currentNode.IsData)
                {
                    // if there are no bits left to read in the data, get a new byte from the input
                    if (bitsLeft == 0)
                    {
                        if (readBytes >= inLength)
                        {
                            throw new NotEnoughDataException(currentSize, decompressedSize);
                        }
                        int nRead = instream.Read(buffer, 0, 4);
                        if (nRead < 4)
                        {
                            throw new StreamTooShortException();
                        }
                        readBytes += nRead;
                        data       = IOUtils.ToNDSu32(buffer, 0);
                        bitsLeft   = 32;
                    }
                    // get the next bit
                    bitsLeft--;
                    bool nextIsOne = (data & (1 << bitsLeft)) != 0;
                    // go to the next node, the direction of the child depending on the value of the current/next bit
                    currentNode = nextIsOne ? currentNode.Child1 : currentNode.Child0;
                }
                #endregion

                #region write the data in the current node (when possible)
                switch (blockSize)
                {
                case BlockSize.EIGHTBIT:
                {
                    // just copy the data if the block size is a full byte
                    outstream.WriteByte(currentNode.Data);
                    currentSize++;
                    break;
                }

                case BlockSize.FOURBIT:
                {
                    // cache the first half of the data if the block size is a half byte
                    if (cachedByte < 0)
                    {
                        cachedByte = currentNode.Data << 4;
                    }
                    else
                    {
                        // if we already cached a half-byte, combine the two halves and write the full byte.
                        cachedByte |= currentNode.Data;
                        outstream.WriteByte((byte)cachedByte);
                        currentSize++;
                        // be sure to forget the two written half-bytes
                        cachedByte = -1;
                    }
                    break;
                }

                default:
                    throw new Exception(String.Format(Main.Get_Traduction("S08"), blockSize.ToString()));
                }
                #endregion

                outstream.Flush();

                // make sure to start over next round
                currentNode = rootNode;
            }

            // the data is 4-byte aligned. Although very unlikely in this case (compressed bit blocks
            // are always 4 bytes long, and the tree size is generally 4-byte aligned as well),
            // skip any padding due to alignment.
            if (readBytes % 4 != 0)
            {
                readBytes += 4 - (readBytes % 4);
            }

            if (readBytes < inLength)
            {
                throw new TooMuchInputException(readBytes, inLength);
            }

            return(decompressedSize);
        }
Ejemplo n.º 32
0
 static Huffman()
 {
     CompressBlockSize = BlockSize.EIGHTBIT;
 }
Ejemplo n.º 33
0
        /// <summary>This version of DecryptData takes the encrypted message, password 
        /// and IV as strings and decrypts the message, returning the plain text as a string.
        /// </summary>
        /// <param name="message">The encrypted message</param>
        /// <param name="password">The password/key that was used to encrypt the message</param>
        /// <param name="initialisationVector">The IV as a string</param>
        /// <param name="blockSize">The block size used in encrypting the message</param>
        /// <param name="keySize">The key size used in encrypting the message</param>
        /// <param name="cryptMode">The encryption mode, CBC or ECB, used in encrypting the message</param>
        /// <param name="messageAsHex">Whether the encrypted message was returned as Hex</param>
        public static string DecryptData(string message, string password,
            string initialisationVector, BlockSize blockSize,
            KeySize keySize, EncryptionMode cryptMode, bool messageAsHex)
        {
            byte[] messageData, passwordData, vectorData;

            // Dont do any work is the message is empty
            if (message.Length <= 0)
                return "";

            //System.Text.UnicodeEncoding encoderUnicode = new System.Text.UnicodeEncoding(); //MTreat
            System.Text.ASCIIEncoding encoderASCII = new System.Text.ASCIIEncoding();  //MTreat

            // Was message supplied in Hex or as simple string
            if (messageAsHex)
                messageData = HexToBytes(message);
            else
                //messageData = encoderUnicode.GetBytes(message); //MTreat
                messageData = encoderASCII.GetBytes(message); //MTreat

            // Convert key and IV to byte arrays
            //passwordData = encoderUnicode.GetBytes(password); //MTreat
            //vectorData = encoderUnicode.GetBytes(initialisationVector); //MTreat
            passwordData = encoderASCII.GetBytes(password); //MTreat
            vectorData = encoderASCII.GetBytes(initialisationVector); //MTreat

            // Return the decrypted plain test as a string
            //return encoderUnicode.GetString(DecryptData(messageData, passwordData, //MTreat
            //  vectorData, blockSize, keySize, cryptMode)); //MTreat
            return encoderASCII.GetString(DecryptData(messageData, passwordData, //MTreat
                vectorData, blockSize, keySize, cryptMode)); //MTreat
        }
Ejemplo n.º 34
0
        // -------------------------------------------------------------------------------------
        // The code below are utility functions for calling the Rijndael code above
        // -------------------------------------------------------------------------------------
        /// <summary>This version of EncryptData takes the message, password 
        /// and IV as byte arrays and encrypts the message, returning the encrypted text 
        /// as a byte array.
        /// 
        /// NOTE: In this implementation I add four bytes to the start of the message and
        /// use that space to store the length of the message. Then the sister DecryptData
        /// function knows where to trim the message before returning it. Not all
        /// encryption routines will use this method. The only parts specified in the
        /// Rijndael standard are for use of the gentables, gkey, encrypt and decrypt
        /// functions. So if you have some data encrypted with another implementation
        /// of Rijndael, or you are encypting data that will be decrypted with another
        /// implementation, then you will need to know how they are recording the length of
        /// the message (if at all), and if you are encrypting/decrypting strings whether
        /// they based it on Ascii or Unicode (or some other character set).
        /// </summary>
        /// <param name="message">The encrypted message</param>
        /// <param name="password">The password/key to encrypt the message with</param>
        /// <param name="initialisationVector">The IV as a string</param>
        /// <param name="blockSize">The block size used to encrypt the message</param>
        /// <param name="keySize">The key size used to encrypt the message</param>
        /// <param name="cryptMode">The encryption mode, CBC or ECB, used to encrypt the message</param>
        public static byte[] EncryptData(byte[] message, byte[] password,
            byte[] initialisationVector, BlockSize blockSize,
            KeySize keySize, EncryptionMode cryptMode)
        {
            byte[] messageData, keyBlock, vectorBlock, dataBlock;
            int messageLength, encodedLength, nb, nk;

            // Dont do any work if message is empty
            messageLength = message.Length;
            if (messageLength <= 0)
                return message;

            // Set up arrays based on block size
            switch (blockSize)
            {
                case BlockSize.Block128:
                    nb = 4;
                    break;
                case BlockSize.Block192:
                    nb = 6;
                    break;
                default:	// assume 256
                    nb = 8;
                    break;
            }

            vectorBlock = new byte[nb * 4];
            dataBlock = new byte[nb * 4];

            for (int i = 0; i < (nb * 4); i++)
            {
                vectorBlock[i] = 0;
                dataBlock[i] = 0;
            }

            // Set up array based on key size
            switch (keySize)
            {
                case KeySize.Key128:
                    nk = 4;
                    break;
                case KeySize.Key192:
                    nk = 6;
                    break;
                default:	// assume 256
                    nk = 8;
                    break;
            }

            keyBlock = new byte[nk * 4];

            for (int i = 0; i < (nk * 4); i++)
            {
                keyBlock[i] = 0;
            }

            // Key will be zero padded, or trimmed to correct size
            for (int i = 0; (i < password.Length) && (i < (nk * 4)); i++)
                keyBlock[i] = password[i];

            // Vector will be zero padded, or trimmed to correct size
            for (int i = 0; (i < initialisationVector.Length) && (i < (nb * 4)); i++)
                vectorBlock[i] = initialisationVector[i];

            // Prepare the key and tables using the Rijndael fuinctions
            gentables();
            gkey(nb, nk, keyBlock);

            // Add 4 bytes to message to store message length, then make sure the length
            // is a Mod of the block size
            encodedLength = messageLength + 4;

            if ((encodedLength % (nb * 4)) != 0)
                encodedLength += ((nb * 4) - (encodedLength % (nb * 4)));

            messageData = new byte[encodedLength];

            // Put message length on front of message
            messageData[0] = (byte)messageLength;
            messageData[1] = (byte)(messageLength >> 8);
            messageData[2] = (byte)(messageLength >> 16);
            messageData[3] = (byte)(messageLength >> 24);

            Array.Copy(message, 0, messageData, 4, messageLength);

            // Zero pad the end of the array
            for (int i = (messageLength + 4); i < encodedLength; i++)
                messageData[i] = 0;

            // Loop through the message encrypting it a block at a time
            for (int i = 0; i < encodedLength; i += (nb * 4))
            {
                Array.Copy(messageData, i, dataBlock, 0, (nb * 4));

                // Do some XORing if in CBC mode
                if (cryptMode == EncryptionMode.ModeCBC)
                    for (int j = 0; j < (nb * 4); j++)
                        dataBlock[j] ^= vectorBlock[j];

                encrypt(dataBlock);

                if (cryptMode == EncryptionMode.ModeCBC)
                    Array.Copy(dataBlock, 0, vectorBlock, 0, dataBlock.Length);

                Array.Copy(dataBlock, 0, messageData, i, (nb * 4));
            }

            return messageData;
        }
Ejemplo n.º 35
0
        /// <summary>This version of EncryptData takes the message, password 
        /// and IV as strings and encrypts the message, returning the encrypted text as a string.
        /// </summary>
        /// <param name="message">The plain text message</param>
        /// <param name="password">The password/key to encrypt the message with</param>
        /// <param name="initialisationVector">The IV as a string</param>
        /// <param name="blockSize">The block size used to encrypt the message</param>
        /// <param name="keySize">The key size used to encrypt the message</param>
        /// <param name="cryptMode">The encryption mode, CBC or ECB, used to encrypt the message</param>
        /// <param name="returnAsHex">Whether the encrypted message is to be returned as Hex</param>
        public static string EncryptData(string message, string password,
            string initialisationVector, BlockSize blockSize,
            KeySize keySize, EncryptionMode cryptMode, bool returnAsHex)
        {
            byte[] messageData, passwordData, vectorData;

            // If message is empty dont bother doing any work
            if (message.Length <= 0)
                return "";

            //System.Text.UnicodeEncoding encoderUnicode = new System.Text.UnicodeEncoding(); //MTreat

            // Convert message, key and IV to byte arrays
            //messageData = encoderUnicode.GetBytes(message); //MTreat
            //passwordData = encoderUnicode.GetBytes(password); //MTreat
            //vectorData = encoderUnicode.GetBytes(initialisationVector); //MTreat

            System.Text.ASCIIEncoding encoderASCII = new System.Text.ASCIIEncoding(); //MTreat

            // Convert message, key and IV to byte arrays
            messageData = encoderASCII.GetBytes(message); //MTreat
            passwordData = encoderASCII.GetBytes(password); //MTreat
            vectorData = encoderASCII.GetBytes(initialisationVector); //MTreat

            // Return encrypted message as string (hex version of bytes if required)
            if (returnAsHex)
                return BytesToHex(EncryptData(messageData, passwordData,
                    vectorData, blockSize, keySize, cryptMode));
            else
                //return encoderUnicode.GetString(EncryptData(messageData, passwordData, //MTreat
                //    vectorData, blockSize, keySize, cryptMode)); //MTreat
                return encoderASCII.GetString(EncryptData(messageData, passwordData, //MTreat
                    vectorData, blockSize, keySize, cryptMode)); //MTreat
        }