Exemplo n.º 1
0
        public static byte[] Decrypt(byte[] key, byte[] ciphertext)
        {
            if (key == null) throw new ArgumentNullException("key");
            if (key.Length != 16)
                throw new ArgumentOutOfRangeException("key length must be 16 bytes");
            if (ciphertext == null) throw new ArgumentNullException("ciphertext");
            if ((ciphertext.Length % 8) != 0)
                throw new Exception("ciphertext length must be a multiple of 8 bytes");

            byte[] input_whitening_key = new byte[8];
            Buffer.BlockCopy(key, 8, input_whitening_key, 0, 8);
            byte[] output_whitening_key = BuildOutputWhiteningKey(key);

            XOR input_whitener = new XOR(input_whitening_key);
            XOR output_whitener = new XOR(output_whitening_key);
            byte[] plaintext = new byte[ciphertext.Length];
            byte[] desKey = new byte[8];
            Buffer.BlockCopy(key, 0, desKey, 0, 8);

            for (int i = 0; i < (ciphertext.Length / 8); i++)
            {
                byte[] ciphertextBytes = new byte[8];
                Buffer.BlockCopy(ciphertext, i * 8, ciphertextBytes, 0, 8);
                byte[] whitenedCiphertextBytes = output_whitener.Crypt(ciphertextBytes);
                byte[] decryptedBytes =
                    input_whitener.Crypt(DecryptBytes(desKey, new byte[8], whitenedCiphertextBytes));
                Buffer.BlockCopy(decryptedBytes, 0, plaintext, i * 8, decryptedBytes.Length);
            }

            return plaintext;
        }