Skip to content

Instantly share code, notes, and snippets.

@gauteh
Last active October 7, 2019 09:30
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save gauteh/669901 to your computer and use it in GitHub Desktop.
Save gauteh/669901 to your computer and use it in GitHub Desktop.
Demonstrates how to serialize and encrypt any object in C#
/*
* crypttest.cs: Demonstrates how to serialize and encrypt any object
*
* Gaute Hope <eg@gaute.vetsj.com>
*
* To deserialize it you need to know the unencrypted serialized length.
* So to store or send also pass the length, e.g. create a struct like this:
*
* public struct EncryptedObject {
* public int length;
* public byte[] encrypteddata;
* }
*
* Serialize it and send it, e.g. over a NetworkStream (Deserializing directly
* on the NetworkStream works with this since the CryptStream would work
* on a MemoryStream where it knows when the end is reached.)
*
*/
using System;
using System.IO;
using System.Security.Cryptography;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
namespace crypttest
{
class MainClass
{
[Serializable]
public struct Data {
public string d;
}
public static void Main (string[] args)
{
Console.WriteLine ("Hello World!");
IFormatter form = new BinaryFormatter ();
Console.WriteLine ("Serialization test");
Data sd = new Data ();
sd.d = "testing";
MemoryStream ser = new MemoryStream ();
form.Serialize (ser, (object) sd);
Console.WriteLine ("Size: " + ser.Length);
Console.WriteLine ("Deserializing..");
ser.Position = 0; // Rewind stream
Data restoredd = (Data) form.Deserialize (ser);
Console.WriteLine ("Got: " + restoredd.d);
Console.WriteLine ("Setup crypto..");
Rijndael alg = Rijndael.Create ();
alg.GenerateIV ();
alg.GenerateKey ();
Console.WriteLine ("Encrypt test..");
ser.Position = 0;
MemoryStream enc = new MemoryStream ();
CryptoStream cw = new CryptoStream (enc, alg.CreateEncryptor (), CryptoStreamMode.Write);
cw.Write (ser.ToArray(), 0, (int) ser.Length);
Console.WriteLine ("Encrypted: " + enc.Length);
cw.FlushFinalBlock (); // Also .Close()'s
Console.WriteLine ("Final Encrypted: " + enc.Length);
enc.Position = 0; // rewind
byte [] benc = enc.ToArray ();
Console.WriteLine ("Decrypt test..");
MemoryStream bencr = new MemoryStream (benc);
CryptoStream cr = new CryptoStream (bencr, alg.CreateDecryptor (), CryptoStreamMode.Read);
byte[] buf = new byte [(int) ser.Length];
cr.Read (buf, 0, (int) ser.Length);
MemoryStream unenc = new MemoryStream (buf);
unenc.Position = 0;
Console.WriteLine ("Deserialize test..");
Data resd = (Data) form.Deserialize (unenc);
Console.WriteLine ("Got: " + resd.d);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment