Exemplo n.º 1
0
        public static byte[] EncryptIGE(byte[] originPlaintext, byte[] key, byte[] iv)
        {
            var plaintext = originPlaintext
                            .Concat(Helpers.GenerateRandomBytes(Helpers.PositiveMod(-originPlaintext.Length, 16)))
                            .ToArray();

            var iv1 = new byte[iv.Length / 2];
            var iv2 = new byte[iv.Length / 2];

            Array.Copy(iv, 0, iv1, 0, iv1.Length);
            Array.Copy(iv, iv1.Length, iv2, 0, iv2.Length);

            var aes = new AesEngine();

            aes.Init(true, key);

            var blocksCount = plaintext.Length / 16;
            var ciphertext  = new byte[plaintext.Length];

            var ciphertextBlock = new byte[16];
            var plaintextBlock  = new byte[16];

            for (int blockIndex = 0; blockIndex < blocksCount; blockIndex++)
            {
                Array.Copy(plaintext, 16 * blockIndex, plaintextBlock, 0, 16);

                for (int i = 0; i < 16; i++)
                {
                    plaintextBlock[i] ^= iv1[i];
                }

                aes.ProcessBlock(plaintextBlock, 0, ciphertextBlock, 0);

                for (int i = 0; i < 16; i++)
                {
                    ciphertextBlock[i] ^= iv2[i];
                }

                Array.Copy(ciphertextBlock, 0, iv1, 0, 16);
                Array.Copy(plaintext, 16 * blockIndex, iv2, 0, 16);
                Array.Copy(ciphertextBlock, 0, ciphertext, blockIndex * 16, 16);
            }

            return(ciphertext);
        }
Exemplo n.º 2
0
        public static byte[] DecryptIGE(byte[] ciphertext, byte[] key, byte[] iv)
        {
            var iv1 = new byte[iv.Length / 2];
            var iv2 = new byte[iv.Length / 2];

            Array.Copy(iv, 0, iv1, 0, iv1.Length);
            Array.Copy(iv, iv1.Length, iv2, 0, iv2.Length);

            var aes = new AesEngine();

            aes.Init(false, key);

            var plaintext   = new byte[ciphertext.Length];
            var blocksCount = ciphertext.Length / 16;

            var ciphertextBlock = new byte[16];
            var plaintextBlock  = new byte[16];

            for (var blockIndex = 0; blockIndex < blocksCount; blockIndex++)
            {
                for (var i = 0; i < 16; i++)
                {
                    ciphertextBlock[i] = (byte)(ciphertext[blockIndex * 16 + i] ^ iv2[i]);
                }

                aes.ProcessBlock(ciphertextBlock, 0, plaintextBlock, 0);

                for (var i = 0; i < 16; i++)
                {
                    plaintextBlock[i] ^= iv1[i];
                }

                Array.Copy(ciphertext, blockIndex * 16, iv1, 0, 16);
                Array.Copy(plaintextBlock, 0, iv2, 0, 16);

                Array.Copy(plaintextBlock, 0, plaintext, blockIndex * 16, 16);
            }

            return(plaintext);
        }