示例#1
0
        private static byte[] CryptoTransformCore(byte[] value, byte[] key, byte[] initializationVector, AdvancedEncryptionStandardCommand command)
        {
            ValidateInput(value, key, initializationVector);
            byte[] output = null;

            using (Aes rijndael = Aes.Create())
            {
                rijndael.BlockSize = BlockSize;
                rijndael.Key       = key;
                rijndael.IV        = initializationVector;
                rijndael.Padding   = PaddingMode.PKCS7;
                rijndael.Mode      = CipherMode.CBC;

                MemoryStream tempStream   = null;
                CryptoStream cryptoStream = null;
                try
                {
                    switch (command)
                    {
                    case AdvancedEncryptionStandardCommand.Decrypt:
                        tempStream   = new MemoryStream(value);
                        cryptoStream = new CryptoStream(tempStream, rijndael.CreateDecryptor(), CryptoStreamMode.Read);
                        output       = new byte[value.Length];
                        cryptoStream.Read(output, 0, output.Length);
                        tempStream = null;
                        output     = ByteUtility.RemoveTrailingZeros(output);
                        break;

                    case AdvancedEncryptionStandardCommand.Encrypt:
                        tempStream   = new MemoryStream();
                        cryptoStream = new CryptoStream(tempStream, rijndael.CreateEncryptor(), CryptoStreamMode.Write);
                        cryptoStream.Write(value, 0, value.Length);
                        cryptoStream.FlushFinalBlock();
                        output     = tempStream.ToArray();
                        tempStream = null;
                        break;
                    }
                }
                finally
                {
                    if (cryptoStream != null)
                    {
                        cryptoStream.Dispose();
                    }
                    if (tempStream != null)
                    {
                        tempStream.Dispose();
                    }
                }
            }
            return(output);
        }