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 9015959
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 16, 20262026-06-16T03:52:45+00:00 2026-06-16T03:52:45+00:00

So I have a basic crypto class. Note that this is a simplified implementation

  • 0

So I have a basic crypto class. Note that this is a simplified implementation to illustrate the question.

Now to my mind both these methods have an extra byte array and string instance.

xmlString and bytes in Encrypt

and

decryptedString and decryptedBytes in Decrypt

So how can I rework the usage of streams in this class to minimize the memory usage?

class Crypto 
{
    Rijndael rijndael;

    public Crypto()
    {
        rijndael = Rijndael.Create();
        rijndael.Key = Encoding.ASCII.GetBytes("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"); ;
        rijndael.IV = Encoding.ASCII.GetBytes("bbbbbbbbbbbbbbbb"); ;
        rijndael.Padding = PaddingMode.PKCS7;
    }

    public byte[] Encrypt(object obj)
    {
        var settings = new XmlWriterSettings
            {
                OmitXmlDeclaration = true
            };

        var ns = new XmlSerializerNamespaces();
        ns.Add("", "");

        var sb = new StringBuilder();
        var xmlSerializer = new XmlSerializer(obj.GetType());
        using (var xmlWriter = XmlWriter.Create(sb, settings))
        {
            xmlSerializer.Serialize(xmlWriter, obj, ns);
            xmlWriter.Flush();
        }

        var xmlString = sb.ToString();
        var bytes = Encoding.UTF8.GetBytes(xmlString);
        using (var encryptor = rijndael.CreateEncryptor())
        using (var stream = new MemoryStream())
        using (var crypto = new CryptoStream(stream, encryptor, CryptoStreamMode.Write))
        {
            crypto.Write(bytes, 0, bytes.Length);
            crypto.FlushFinalBlock();
            stream.Position = 0;
            var encrypted = new byte[stream.Length];
            stream.Read(encrypted, 0, encrypted.Length);
            return encrypted;
        }
    }

    public T Decrypt<T>(byte[] encryptedValue)
    {
        byte[] decryptedBytes;
        using (var decryptor = rijndael.CreateDecryptor())
        using (var stream = new MemoryStream())
        using (var crypto = new CryptoStream(stream, decryptor, CryptoStreamMode.Write))
        {
            crypto.Write(encryptedValue, 0, encryptedValue.Length);
            crypto.FlushFinalBlock();
            stream.Position = 0;
            decryptedBytes = new Byte[stream.Length];
            stream.Read(decryptedBytes, 0, decryptedBytes.Length);
        }

        var ser = new XmlSerializer(typeof(T));

        var decryptedString = Encoding.UTF8.GetString(decryptedBytes);
        using (var stringReader = new StringReader(decryptedString))
        using (var xmlReader = new XmlTextReader(stringReader))
        {
            return (T)ser.Deserialize(xmlReader);

        }
    }

}

And here is a unit test

[TestFixture]
public class Tests
{
    [Test]
    public void Run()
    {
        var before = new MyClassForSerialize()
            {
                Property = "Sdf"
            };

        var dataEncryptor = new Crypto();
        var encrypted = dataEncryptor.Encrypt(before);
        var after = dataEncryptor.Decrypt<MyClassForSerialize>(encrypted);
        Assert.AreEqual(before.Property, after.Property);
    }
}
public class MyClassForSerialize
{
    public string Property { get; set; }
}

=== Edit ===

Based on the anser from Damien_The_Unbeliever I tried this. Which fails the unit test

public byte[] Encrypt(object obj)
{
    var settings = new XmlWriterSettings
    {
        OmitXmlDeclaration = true
    };

    var ns = new XmlSerializerNamespaces();
    ns.Add("", "");
    var xmlSerializer = new XmlSerializer(obj.GetType());

    using (var encryptor = rijndael.CreateEncryptor())
    using (var stream = new MemoryStream())
    using (var crypto = new CryptoStream(stream, encryptor, CryptoStreamMode.Write))
    {
        using (var xmlWriter = XmlWriter.Create(crypto, settings))
        {
            xmlSerializer.Serialize(xmlWriter, obj, ns);
            xmlWriter.Flush();
        }
        crypto.FlushFinalBlock();
        stream.Position = 0;
        return stream.ToArray();
    }
}
  • 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-06-16T03:52:47+00:00Added an answer on June 16, 2026 at 3:52 am

    You can construct your XmlWriter directly on top of your CryptoStream (pass crypto to XmlWriter.Create), rather than using a separate buffer. (Ditto for decryption)

    And MemoryStream has a ToArray method so you don’t have to manually allocate, re-position and read from it.

    Other than that, it looks like a reasonable implementation – are there specific issues that need fixing?


    Based on your edit, if I change decrypt to:

        public T Decrypt<T>(byte[] encryptedValue)
        {
            using (var decryptor = rijndael.CreateDecryptor())
            using (var stream = new MemoryStream(encryptedValue))
                using (var crypto = new CryptoStream(stream, decryptor, CryptoStreamMode.Read))
                using (var xmlReader = XmlReader.Create(crypto))
                {
                    var ser = new XmlSerializer(typeof(T));
                    return (T)ser.Deserialize(xmlReader);
    
                }
        }
    

    Then it seems to work for me.


    The new version is including an XML BOM, whereas the old one wasn’t. The XmlReader should cope, I’d have thought, but appears not to. Try the following settings in Encrypt:

    var settings = new XmlWriterSettings
    {
        OmitXmlDeclaration = true,
        Encoding = new UTF8Encoding(false)
    };
    

    And now it works with the old Decrypt function.

    Full Solution

    Encrypt

    public byte[] Encrypt(object obj)
    {
        var settings = new XmlWriterSettings
            {
                OmitXmlDeclaration = true,
                Encoding = new UTF8Encoding(false)
            };
    
        var ns = new XmlSerializerNamespaces();
        ns.Add("", "");
    
        var xmlSerializer = new XmlSerializer(obj.GetType());
        using (var encryptor = rijndael.CreateEncryptor())
        using (var stream = new MemoryStream())
        using (var crypto = new CryptoStream(stream, encryptor, CryptoStreamMode.Write))
        {
            using (var xmlWriter = XmlWriter.Create(crypto, settings))
            {
                xmlSerializer.Serialize(xmlWriter, obj, ns);
                xmlWriter.Flush();
            }
            crypto.FlushFinalBlock();
            return stream.ToArray();
        }
    }
    

    Decrypt

    public T Decrypt<T>(byte[] encryptedValue)
    {
        using (var decryptor = rijndael.CreateDecryptor())
        using (var stream = new MemoryStream(encryptedValue))
        using (var crypto = new CryptoStream(stream, decryptor, CryptoStreamMode.Read))
        {
            var ser = new XmlSerializer(typeof(T));
            return (T)ser.Deserialize(crypto);
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have basic code that looks like this: while(inputfileStream.good()) { for(int i = 0;i<levels;i++)
I have a basic web service that returns the following object as JSON: public
I have a basic math question. I am trying to get a percentage from
I have basic issue that i don't understand, we use HEAT to consume directory
I have basic stored procedure that performs a full text search against 3 columns
I'm new to both Pylons and AuthKit. I have basic authentication via AuthKit working
I have basic function that prints network errors based on enum NetworkError. that looks
Let's say I have a Car class in a game that can be played
I have basic client-side validation working in my MVC3 RC2 application, but I'm now
I have basic JavaScript code that needs to tell how many names out of

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.