i have an assignment and i need to encrypt the objects before serializing them into the file. i've looked for information and all i found was encrypting strings. is this my only option?to encrypt each field of the object and then assemble them all to the original object? Thanks.
i have about 5 different types of objects:Product,Employee and so on. i have the whole code and i serialize and desrialize those objects to a file pretty easily. all i need now,is a way to encrypt the object before i serialize it. i've looked into CryptoStream but i didn't see a method which enables it. Help?
//Edit:
i need to do encryption on the fly-it means:
Do all encryption in memory so that unencrypted data is never written to disk. in other words, don’t write unencrypted data to a file, read it, encrypt it, and write it back –this method is very vulnerable.

Recommended Answers

All 35 Replies

Do you have to encrypt BEFORE serializing? Serializing and then encrypting makes far more sense to me.

See this for how to serialize:

http://www.paxium.co.uk/PublicArticle/Article/493

Then just encrypt the xml. This way you can write one piece of code which will work for anything.

Hi no123, welcome. :)
Encrypting after serialization, would have the same effect I guess.

i need to do encryption on the fly-it means:
Do all encryption in memory so that unencrypted data is never written to disk. in other words, don’t write unencrypted data to a file, read it, encrypt it, and write it back –this method is very vulnerable.

if i serialize and then encrypt-it's exactly what i'm not supposed to do,right?

No - you can serialise in memory, encrypt in memory and then write to disk.

To clarify - serialization doesn't mean to serialise to disk - you can serialize to many places - the screen, a printer, a disk, memory, over a network etc.

ohhh thank you.
then,can you explain to me how to serialize to memory and then encrypt the object?
i only used serialization to a file,that's why i figured i have to do the encryption before that.

Try this:

using System;
using System.Text;
using System.Xml.Serialization;
using System.IO;

namespace ConsoleSerialisation
{
    public class Program
    {
        private static readonly Encoding LocalEncoding = Encoding.UTF8;

        static void Main(string[] args)
        {
            using (MemoryStream stream = new MemoryStream())
            {
                Person sarah = new Person("Sarah", "Smith", 28);

                XmlSerializer personSerialiser = new XmlSerializer(typeof(Person));

                personSerialiser.Serialize(stream, sarah);

                //At this point it is in an in memory stream

                //This puts it into a string
                var output = LocalEncoding.GetString(stream.ToArray());

                //TODO - Encode the string here

                Console.WriteLine(output);
            }

            Console.Read();
        }
    }

    [Serializable]
    public class Person
    {
        public Person()
        {

        }

        public Person(string firstname, string surname, int age)
        {
            FirstName = firstname;
            SurName = surname;
            Age = age;
        }

        public string FirstName { get; set; }

        public string SurName { get; set; }

        public int Age { get; set; }
    }
}

thank you so much :)
i have a question-can i serialize different objects to the same memory stream?
for example-both person and animal or something like that.
does it have to be xml?i dont understand much about it but i serialized just to a text file.

If you are serializing and then encrypting and writing to a file then the reverse will be read from disk, decrypt and then create an object in memory, then does it matter whether it's xml? You can also serialise to binary as well - see the link I posted earlier. You could also write your own serialization classes to serialize to 4th century Gaelic if you like but you never read it serialized as a human so it doesn't matter right?

You can serialize to one stream or file by using encapsulation I think. Again there is more info on this in the link I gave earlier but I think if you have an Animal and a Person and you want to serialize together in one go then then you can do something like:

var dave = new Person("Dave", "Amour");
var cat = new Cat("Joey", 7);

If you then have a class that has these as members of a collection, or as properties maybe then you serialise that, not the individual objects. Hope that makes sense?

this helped me alot,thank you so much :)
i will try writing the code and see how it goes.
i have a little question-i'm using DateTime and i saw that there's a method of TryParse. but i have a DateTime object and i can't use that method,it's not there,i need something for it?

It's because TryParse is a static method. You have to use the class name instead of the object in your code. See here for example.

thank you :)

@ddanbe - think you posted in the wrong thread. On the whiskey already!?

@no123 - youre welcome

Well, I'm sipping a beer right now, and what's wrong with answering a side question posed here?

Apologies ddanbe, I never realised there was a side question, only just spotted it. I really did think you had posted in the wrong thread!

No harm done, perhaps we should share a whiskey sometimes. :)

Next time I'm in Belgium definatley, haven't been for about 35 years though!

is it possible to change my current code which has serialization to file into serialization to memory?

Yes I would think so.

Can you show use your code?

List<Object> toRemove = new List<Object>();
            if (File.Exists("remove3.bin"))
            {
                Stream osRemove = File.OpenRead("remove3.bin");
                BinaryFormatter removeDeseri = new BinaryFormatter();
                while (osRemove.Position != osRemove.Length)
                {
                    //deserialize each object
                    var removeDeserialized = removeDeseri.Deserialize(osRemove);
                    //add individual object to a list
                    toRemove.Add(removeDeserialized);
                }
                osRemove.Close();
            }
Stream removeStream = File.Create("remove3.bin");

This is deserialisation code - do you have serialization code?

Stream stream = File.Create("file9.bin");
            BinaryFormatter seri = new BinaryFormatter();
            foreach (Object p1 in list)
            {
                if (!isContained(p1, toRemove))
                {
                    seri.Serialize(stream, p1);
                }
            }

here :)

i haven't found a message button to message you.hope you see that-i posted the serializatin code you wanted.

Replacing the file stream with a memory stream should do the job:

MemoryStream stream = new MemoryStream();
BinaryFormatter seri = new BinaryFormatter();
foreach (Object p1 in list)
{
    if (!isContained(p1, toRemove))
    {
        seri.Serialize(stream, p1);
    }
}

thanks :)
so after that,i need to turn the stream into a string,encrypt it and then serialize to file?

Sorry got a bit distracted yesterday so thanks for stepping in tinstaafl.

Don't forget to wrap IDisposbale objects in a using statement thouhg.

thank you:)
can you expand about the using statement?
why do i need to dispose them?

if the encryption you're using relies on text and since the object is serialized in binary format you will probably need to encode the data using something like base85 encoding first. If not then you'll need to read the data as binary data not text.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.