none
Decrypt file into memory RRS feed

  • Question

  • Hello guys,

    So i have function for decrypting my files.

    Looks like this:

    public static bool FileDecrypt(string inputFile, string outputFile, string password)
            {
    
                byte[] passwordBytes = Encoding.UTF8.GetBytes(password);
                byte[] salt = new byte[32];
    
                FileStream fsCrypt = new FileStream(inputFile, FileMode.Open);
                fsCrypt.Read(salt, 0, salt.Length);
    
                RijndaelManaged AES = new RijndaelManaged();
                AES.KeySize = 256;
                AES.BlockSize = 128;
                var key = new Rfc2898DeriveBytes(passwordBytes, salt, 50000);
                AES.Key = key.GetBytes(AES.KeySize / 8);
                AES.IV = key.GetBytes(AES.BlockSize / 8);
                AES.Padding = PaddingMode.PKCS7;
                AES.Mode = CipherMode.CFB;
    
                CryptoStream cs = new CryptoStream(fsCrypt, AES.CreateDecryptor(), CryptoStreamMode.Read);
    
                FileStream fsOut = new FileStream(outputFile, FileMode.Create);
    
                    int read;
                    byte[] buffer = new byte[1048576];
      
                    try
                    {
                        while ((read = cs.Read(buffer, 0, buffer.Length)) > 0)
                        {
                            Application.Current.Dispatcher.Invoke(DispatcherPriority.Background, new ThreadStart(delegate { }));
                            fsOut.Write(buffer, 0, read);
                        }
                    }
                    catch (CryptographicException ex_CryptographicException)
                    {
                        fsOut.Close();
                        fsCrypt.Close();
                        LogWriter loger = new LogWriter("Cryptography error: " + ex_CryptographicException.ToString());
                        return false;
                    }
                    catch (Exception ex)
                    {
                        fsOut.Close();
                        fsCrypt.Close();
                        LogWriter loger = new LogWriter("Exception error: " + ex.ToString());
                        return false;
                    }
    
                    try
                    {
                        cs.Close();
                    }
                    catch (Exception ex)
                    {
                        fsCrypt.Close();
                        fsOut.Close();
                        LogWriter loger = new LogWriter("Error when closing Cryptostream. Error: " + ex.ToString());
                        return false;
                    }
                    finally
                    {
                        fsOut.Close();
                        fsCrypt.Close();
                    }
                        
            return true;
                
    
            }

    And i would like to make function which decrypts the file only into memorystream or returns that memorystream would be more helpfull.

    And then i would like to use Xmlserializer on that memorystream. So the file stays encrypted on the harddrive and i still can use the xml configuration from that file.

    Is that somehow possible?

    Thanks for answers,

    Best regards,

    John

    Sunday, November 24, 2019 7:57 PM

All replies

  • Just replace your fsOut with MemoryStream and return it instead (remember, don't .Close() it!).
    Monday, November 25, 2019 1:23 AM
    Answerer
  • Hi Johny V, 

    Thank you for posting here.

    For your question, you want to use Xmlserializer on the memorystream.

    I make a test on my side, I encrypt the xml file, then I decrypt the file and use Xmlserializer to get the data.  

    You can refer to and modify the following code.

       [XmlRootAttribute("student", IsNullable = false)]
        public class student
        {
            public int id { get; set; }
            public string name { get; set; }
        }
        class Program
        {
            static void Main(string[] args)
            {
                string path = @"path… ";
                try
                {
                    string originalXMLData = File.ReadAllText("…");
                    using (RijndaelManaged myRijndael = new RijndaelManaged())
                    {
                        myRijndael.GenerateKey();
                        myRijndael.GenerateIV();
    
                        byte[] encrypted = EncryptStringToBytes(originalXMLData, myRijndael.Key, myRijndael.IV);
                        File.WriteAllBytes(path, encrypted);
                        DecryptFromBytes(encrypted, myRijndael.Key, myRijndael.IV);
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine("Error: {0}", e.Message);
                }
                Console.ReadLine();
            }
            static byte[] EncryptStringToBytes(string plainText, byte[] Key, byte[] IV)
            {
                if (plainText == null || plainText.Length <= 0)
                    throw new ArgumentNullException("plainText");
                if (Key == null || Key.Length <= 0)
                    throw new ArgumentNullException("Key");
                if (IV == null || IV.Length <= 0)
                    throw new ArgumentNullException("IV");
                byte[] encrypted;
    
                using (RijndaelManaged rijAlg = new RijndaelManaged())
                {
                    rijAlg.Key = Key;
                    rijAlg.IV = IV;
                    ICryptoTransform encryptor = rijAlg.CreateEncryptor(rijAlg.Key, rijAlg.IV);
    
                    using (MemoryStream msEncrypt = new MemoryStream())
                    {
                        using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                        {
                            using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                            {
                                swEncrypt.Write(plainText);
                            }
                            encrypted = msEncrypt.ToArray();
                        }
                    }
                }
                return encrypted;
            }
    

    My Decrypt function:

            static void DecryptFromBytes(byte[] cipherText, byte[] Key, byte[] IV)
            {
                if (cipherText == null || cipherText.Length <= 0)
                    throw new ArgumentNullException("cipherText");
                if (Key == null || Key.Length <= 0)
                    throw new ArgumentNullException("Key");
                if (IV == null || IV.Length <= 0)
                    throw new ArgumentNullException("IV");
    
                string plaintext = null;
                using (RijndaelManaged rijAlg = new RijndaelManaged())
                {
                    rijAlg.Key = Key;
                    rijAlg.IV = IV;
    
                    ICryptoTransform decryptor = rijAlg.CreateDecryptor(rijAlg.Key, rijAlg.IV);
    
                    using (MemoryStream msDecrypt = new MemoryStream(cipherText))
                    {
                        using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                        {
                            XmlSerializer serializer = new XmlSerializer(typeof(student));
                            student stu = (student)serializer.Deserialize(csDecrypt);
                            Console.WriteLine($"id: {stu.id}  name: {stu.name}");
                        }
                    }
                }
            }
    

    My originalXMLData:

    Result:

    Hope it can help you.

    Best Regards,

    Xingyu Zhao



    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Monday, November 25, 2019 3:26 AM
    Moderator