Skip to content

Instantly share code, notes, and snippets.

@mxriverlynn
Created February 4, 2011 16:40
Show Gist options
  • Save mxriverlynn/811336 to your computer and use it in GitHub Desktop.
Save mxriverlynn/811336 to your computer and use it in GitHub Desktop.
Hiding sensitive information with base64 encoding and binary serialization
class Program
{
static void Main(string[] args)
{
var foo = new Base64Dictionary();
foo["bar"] = "baz";
foo["foo"] = "bar";
foo.WriteTo("test.bin");
var bar = Base64Dictionary.ReadFrom("test.bin");
Console.WriteLine("foo = " + bar["foo"]);
Console.WriteLine("bar = " + bar["bar"]);
Console.Read();
}
}
[Serializable]
public class Base64Dictionary: Dictionary<string, string>
{
public string this[string key]
{
get
{
var encoded_key = Convert.ToBase64String(Encoding.UTF8.GetBytes(key));
var encoded_value = base[encoded_key];
return Encoding.UTF8.GetString(Convert.FromBase64String(encoded_value));
}
set
{
var encoded_key = Convert.ToBase64String(Encoding.UTF8.GetBytes(key));
var encoded_value = Convert.ToBase64String(Encoding.UTF8.GetBytes(value));
base[encoded_key] = encoded_value;
}
}
public Base64Dictionary() { }
public Base64Dictionary(SerializationInfo info, StreamingContext context) : base(info, context) { }
public void WriteTo(string file)
{
IFormatter formatter = new BinaryFormatter();
using (Stream stream = new FileStream(file, FileMode.Create, FileAccess.Write, FileShare.None))
{
formatter.Serialize(stream, this);
}
}
public static Base64Dictionary ReadFrom(string file)
{
Base64Dictionary obj;
IFormatter formatter = new BinaryFormatter();
using (Stream stream = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read))
{
obj = (Base64Dictionary) formatter.Deserialize(stream);
}
return obj;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment