Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6773551
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 26, 20262026-05-26T15:40:54+00:00 2026-05-26T15:40:54+00:00

Why doesn’t this code work? Probably I’ve done somethig wrong, but I can’t find

  • 0

Why doesn’t this code work? Probably I’ve done somethig wrong, but I can’t find what.

When I run the code below I see that the only a part of message is correctly decrypted. As I understand, the cryptoStreamReader.ReadToEnd() doesn’t read the whole file for some reason.

Actually I’ve solved the task by using XmlTextReader and StringReader for encryption/decryption instead of MemoryStream. But I want to know what’s wrong with that code. Could anyone help me please to find it out? Thank you in advance!

–

using System;
using System.IO;
using System.Runtime.Serialization;
using System.Security.Cryptography;
using System.Collections.Generic;

namespace Tests
{
    internal static class Program
    {
        private static void Main()
        {
#if GENERATE_DATA
            var list = new List<int>();
            for (int i = 0; i <= 5 * 1024; i++)
                list.Add(i);
            using (var fileStream = new FileStream("data.xml", FileMode.Create))
            {
                var serializer = new DataContractSerializer(list.GetType());
                serializer.WriteObject(fileStream, list);
            }
#endif


            var originalData = GetData<List<int>>();

            SerializeAndEncrypt(originalData);
            var restoredData = DecryptAndDeserialize<List<int>>();

            Console.ReadKey();
        }

        private static T GetData<T>()
        {
            using (var fileStream = new FileStream("data.xml", FileMode.Open))
            {
                var serializer = new DataContractSerializer(typeof(T));
                return (T)serializer.ReadObject(fileStream);
            }
        }

        private const string ENCRYPTED_DATA_FILE_NAME = "data.enc";

        // 32 bytes
        private static readonly byte[] KEY = new byte[]
                                             {
                                                 1, 2, 3, 4, 5, 6, 7, 8, 9, 0,
                                                 1, 2, 3, 4, 5, 6, 7, 8, 9, 0,
                                                 1, 2, 3, 4, 5, 6, 7, 8, 9, 0,
                                                 1, 2
                                             };

        // 16 bytes
        private static readonly byte[] INITIALIZATION_VECTOR = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6 };

        private static string _toEncrypt;
        private static string _decrypted;

        private static void SerializeAndEncrypt<T>(T data)
        {
            var memoryStream = new MemoryStream();
            var serializer = new DataContractSerializer(typeof(T));
            serializer.WriteObject(memoryStream, data);
            memoryStream.Position = 0L;
            var memoryStreamReader = new StreamReader(memoryStream);

            var fileStream = File.Open(ENCRYPTED_DATA_FILE_NAME, FileMode.Create);
            var aes = Aes.Create();
            var cryptoTransform = aes.CreateEncryptor(KEY, INITIALIZATION_VECTOR);
            var cryptoStream = new CryptoStream(fileStream, cryptoTransform, CryptoStreamMode.Write);
            var cryptoStreamWriter = new StreamWriter(cryptoStream);


            _toEncrypt = memoryStreamReader.ReadToEnd();
            cryptoStreamWriter.Write(_toEncrypt);


            cryptoStream.Close();
            fileStream.Close();
            memoryStream.Close();
        }

        private static T DecryptAndDeserialize<T>()
        {
            var fileStream = File.Open(ENCRYPTED_DATA_FILE_NAME, FileMode.Open);
            var aes = Aes.Create();
            var cryptoTransform = aes.CreateDecryptor(KEY, INITIALIZATION_VECTOR);
            var cryptoStream = new CryptoStream(fileStream, cryptoTransform, CryptoStreamMode.Read);
            var cryptoStreamReader = new StreamReader(cryptoStream);

            var memoryStream = new MemoryStream();
            var memoryStreamWriter = new StreamWriter(memoryStream);


            // The following line is shorter than the original (_toEncrypt). Why? :(
            _decrypted = cryptoStreamReader.ReadToEnd();
            memoryStreamWriter.Write(_decrypted);


            memoryStream.Position = 0L;
            var serializer = new DataContractSerializer(typeof(T));
            var result = (T)serializer.ReadObject(memoryStream);


            memoryStream.Close();
            cryptoStream.Close();
            fileStream.Close();

            return result;
        }
    }
}

–

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-26T15:40:54+00:00Added an answer on May 26, 2026 at 3:40 pm

    You have to flush your StreamWriter in order to get buffered data written to the underlying
    device:

    private static void SerializeAndEncrypt<T>(T data)
    {                
      ...
    
      _toEncrypt = memoryStreamReader.ReadToEnd();
      cryptoStreamWriter.Write(_toEncrypt);
    
      // Flush your stream writer. So all buffered
      // data get written to the underlying device.
      cryptoStreamWriter.Flush(); 
    
      cryptoStream.Close();
      fileStream.Close();
      memoryStream.Close();
    }
    
    private static T DecryptAndDeserialize<T>()
    {
      ...
    
      _decrypted = cryptoStreamReader.ReadToEnd();
      memoryStreamWriter.Write(_decrypted);
    
      // Flush buffered data.
      memoryStreamWriter.Flush();
    
      memoryStream.Position = 0L;
      var serializer = new DataContractSerializer(typeof(T));
      var result = (T)serializer.ReadObject(memoryStream);
      memoryStream.Close();
      cryptoStream.Close();
      fileStream.Close();
    
      return result;
    }
    

    Hope, this helps.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Why doesn't this work? I have bypassed this before but i can't remember how
Why doesn't Html.ActionLink work in the below code? This is a page in the
Why doesn't this jQuery code work? $(document).ready(function () { $('currentPage').click(function() { $('myaccount').slideDown('slow', function() {
doesn't work.. can't find any solution to prevent submit page reload only if ajax
Why doesn't this code work? I'am using FF. <head> <script type=text/javascript> document.getElementById(someID).onclick = function(){
Doesn't seem to work for me, maybe I just doing it wrong
Why doesn't this work (when parameter is set to 1) : SELECT * FROM
Doesn't matter what I do, I simply can't get this to play a sound
Why doesn't the file input element show up at all??? see code and screen
This doesn't work. I've got an exception from SQL databse that column does not

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.