RSS

Category Archives: C#

Standardising String Cryptography

I was writing the new Twitter Client for TweetPivot when I hit a problem. I needed to store a small amount of information on our users’ machines; specifically in isolated storage. Most of this would be fine as plain text but one field needed to be encrypted. This meant I had to solve a problem I seem to come back to again and again – simple string cryptography.

Crypto Rule #1 seems to be “Don’t roll your own.”. OK fine, so give me something pre-rolled. C# / .Net doesn’t contain the method I was looking for:

string Encrypt(string plainText, string password, string salt);

Luckily, @blowdart came to my rescue and posted this code. Now, there’s a few things worth pointing out about this:

  1. Barry’s book sales suggest he might actually know what he’s doing, but who else amongst us has the confidence and knowledge to say that it’s safe and reliable?
  2. Did anyone read the code and think “actually, TripleDES would suit my needs, not Rijndael”?

Answer: probably no.

So, given that a) it’s hard to do correctly and b) this standard method would probably suit 99% of developers 99% of the time why, then, do we not find this in the BCL? If I want to open a file I can use System.IO.File.OpenRead(string path). If I need to take more control over the process I can use a StreamReader and dictate encodings etc.

I’ve included my final code below (you deserve something for reading this far!). Porting it into Silverlight simplifies matters – mainly because there’s only one implementation of SymmetricAlgorithm. “But Barry defaulted to Rijndael. Does this mean that Silverlight is less secure than standard .Net applications?” Another crypto conundrum!

I do feel that this functionality needs abstracting behind a simplified facade. I genuinely don’t care how long my initialisation vector is or whether I’m using DES, DoubleDES or even TripleDES. Cryptography is simply a tool for hiding stuff and it should be easier, safer and more confidence-imspiring than it currently is. @blowdart’s subsequent tweet kinda sums up the complexity of the subject. Signatures, really? You might just as well have asked me if I wanted tweeters with it! #referenceToOldJoke

using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;

public static class CryptographicExtensions
{
  public static string Encrypt(this string plainText, string password, string salt)
  {
    var algorithm = new AesManaged();

    algorithm.SetKeyAndIV(password, salt);

    return Encrypt(algorithm, plainText);
  }

  public static string Encrypt(this string plainText, ref byte[] key, ref byte[] iv)
  {
    if (string.IsNullOrEmpty(plainText))
      return plainText;

    var algorithm = new AesManaged();

    if (key != null)
      algorithm.Key = key;
    else
      key = algorithm.Key;

    if (iv != null)
      algorithm.IV = iv;
    else
      iv = algorithm.IV;

    return Encrypt(algorithm, plainText);
  }

  private static string Encrypt(SymmetricAlgorithm algorithm, string plainText)
  {
    var plainTextAsBytes = Encoding.UTF8.GetBytes(plainText);

    using (ICryptoTransform transform = algorithm.CreateEncryptor())
    {
      using (var outputStream = new MemoryStream())
      {
      using (var inputStream = new CryptoStream(outputStream, transform, CryptoStreamMode.Write))
      {
        inputStream.Write(plainTextAsBytes, 0, plainText.Length);
        inputStream.FlushFinalBlock();
        var cipherText = outputStream.ToArray();
        return Convert.ToBase64String(cipherText);
      }
    }
  }

  public static string Decrypt(this string cypherText, string password, string salt)
  {
    var algorithm = new AesManaged();

    algorithm.SetKeyAndIV(password, salt);

    return Decrypt(algorithm, cypherText);
  }

  public static string Decrypt(this string cypherText, byte[] key, byte[] iv)
  {
    if (string.IsNullOrEmpty(cypherText))
      return cypherText;

    if (key == null)
      throw new ArgumentNullException("key");

    if (iv == null)
      throw new ArgumentNullException("iv");

    var algorithm = new AesManaged { Key = key, IV = iv };

    return Decrypt(algorithm, cypherText);
  }

  private static string Decrypt(SymmetricAlgorithm algorithm, string cypherText)
  {
    var cipherTextAsBytes = Convert.FromBase64String(cypherText);

    using (ICryptoTransform transform = algorithm.CreateDecryptor())
    {
      using (var outputStream = new MemoryStream())
      {
        using (var inputStream = new CryptoStream(outputStream, transform, CryptoStreamMode.Write))
        {
          inputStream.Write(cipherTextAsBytes, 0, cipherTextAsBytes.Length);
          inputStream.FlushFinalBlock();
          var plainTextAsBytes = outputStream.ToArray();

          return Encoding.UTF8.GetString(plainTextAsBytes, 0, plainTextAsBytes.Length);
        }
      }
    }
  }

  public static void SetKeyAndIV(this SymmetricAlgorithm algorithm, string password, string salt)
  {
    string paddedSalt = salt;

    while (paddedSalt.Length < 8 )
      paddedSalt += salt;

    var rfc2898 = new Rfc2898DeriveBytes(password, Encoding.UTF8.GetBytes(paddedSalt));

    algorithm.Key = rfc2898.GetBytes(algorithm.KeySize / 8);
    algorithm.IV = rfc2898.GetBytes(algorithm.BlockSize / 8);
  }
}
 
3 Comments

Posted by on October 12, 2010 in C#

 

Tags: ,

Immutable, Auto-Implemented Properties in C#

Over the past few months I’ve been getting a lot more into immutability. If you want to know why you should be using immutable types start with this blog post by Bertrand Le Roy.

Until recently I, like most other developers had been creating my properties like this…

public class Person
{
  public DateTime BirthDate { get; private set; }
  public string FavouriteSong { get; set;}

  public Person(DateTime birthDate)
  {
    BirthDate = birthDate;
  }
}

Pretty straight forward – the BirthDate is required and must be set during construction of the object whilst the FavouriteSong is optional. The other reason for writing properties this way is simplicity and code succinctness. It also allows more ‘interesting’ properties to be more easily identified. For instance, this new Age property stands out from the other two and ‘asks’ to be unit tested.

public class Person
{
  public DateTime BirthDate { get; private set; }
  public string FavouriteSong { get; set;}

  public int Age
  {
    get
    {
      var now = DateTime.Today;
      var age = now.Year - bday.Year;

      if (bday > now.AddYears(-age))
        age--;

      return age;
    }
  }

  public Person(DateTime birthDate)
  {
    BirthDate = birthDate;
  }
}

I should, however, be making the BirthDate property immutable – it isn’t gonna change! This does make the code less neat though…

public class Person
{
  private readonly DateTime _birthDate;
  public DateTime BirthDate { get { return _birthDate; } }</pre>
  public string FavouriteSong { get; set;}

  public int Age
  {
    get
    {
      var now = DateTime.Today;
      var age = now.Year - bday.Year;

      if (bday > now.AddYears(-age))
        age--;

      return age;
    }
  }

  public Person(DateTime birthDate)
  {
    _birthDate = birthDate;
  }
}

Auto-implemented properties are a .Net construct and are used as a template, at design-time, to create a ‘real’ pair of _get _set methods. So, what I’d like to be able to do is this …

public class Person
{
  public DateTime BirthDate { get; private readonly set; }
  public Person(DateTime birthDate)
  {
    _birthDate = birthDate;
  }
}

Anyone from Microsoft like to chime in?

 
Leave a comment

Posted by on August 16, 2010 in C#

 

Tags:

Introduction to Code Contracts

Firstly, to those who went to DDDSW last weekend. Apologies if this post just re-hashes what Barry Carr said during his Code Contracts talk. I didn’t see if myself although it was the existence of this item on the agenda that prompted me to investigate this topic.

Now, let me start by saying “I love Code Contracts”. They will save you time, code and headaches if you implement them correctly. Rather than just talk theory I thought it would be more informative to go through a worked example together…

The Bank Demo

We’ve been asked to add a simple feature to an existing banking application that allows transfers to be made from one account to another. Here are the, entirely sensible, starting classes we’ve created…

interface IAccount
{
  string Name { get; }
  double Balance { get; }
}
class BankAccount : IAccount
{
  string Name { get; set; }
  double Balance { get; set; }
}

static class TransferService
{
  public static void TransferMoney(IAccount from, IAccount to, double amount)
  {
    from.Balance -= amount;
    to.Balance += amount;
  }
}

Well, that would work – mostly; but we have no exception handling or validation. So, here’s how we would normally amend that…

Ugly Validation

interface IAccount
{
  string Name { get; }
  double Balance { get; set; }
}
class BankAccount : IAccount
{
  // Name is required, so add it to the constructor...
  public BankAccount(string name)
  {
    if (string.IsNullOrEmpty(name))
      throw new ArgumentNullException("name");

    Name = name;
  }
  public readonly string Name;
  public double Balance { get; set; }
}

static class TransferService
{
  public static void TransferMoney(IAccount from, IAccount to, double amount)
  {
    // None of the accounts can be null and the amount must be positive...
    if (from == null)
      throw new ArgumentNullException("from");
    if (to == null)
      throw new ArgumentNullException("to");
    if (from.Balance < amount)
      throw new ArgumentOutOfRangeException("from account does not have enough money to transfer");

    from.Balance -= amount;
    to.Balance += amount;
  }
}

Ok, so that’s better; but we’re starting to really muddy our previously clean classes with all the new validation code. The other problem is that the interface (IAccount) doesn’t define the full contract. What we actually want to enforce is ‘has a Name property’, ‘has a Balance property’ AND ‘the Name property cannot be empty’. Clearly there’s no mechanism in the language to specify our final requirement – but it’s important. To fix this we find ourselves leaking contract information into classes – in this case our BankAccount class. Now, we could solve this by creating an abstract Account class but then the TransferService would have to change as well and, to be honest, you may as well just get rid of the interface because you cannot use it without the abstract class.

Whilst we’ve been thinking about this the ‘boss’ reminds us that the Balance on any account can never be negative. OK, well that destroys our nice, clean auto-implemented property! The BankAccount class now needs to be amended to this…

class BankAccount : IAccount
{
  // Name is required, so add it to the constructor...
  public BankAccount(string name)
  {
    if (string.IsNullOrEmpty(name))
      throw new ArgumentNullException("name");
    Name = name;
  }
  public readonly string Name;

  private double _balance;

  public double Balance
  {
    get
    {
      return _balance;
    }
    set
    {
      if (value < 0)
        throw new ArgumentOutOfRangeException("Your Bank does not allow your account to be negative.");
      _balance = value;
    }
  }
}

I think I prefer the cleanness of our original BankAccount class – how do I get that back?

Well, wouldn’t it be the best thing you’d heard this month if you could define the whole of your contract just via the interface? 3rd party developers could then create their own account classes to use in your Transfer Service without you having to tell them about the extra Name or Balance validation. This is where Code Contracts come in.

Contract Requirements

The Contract class in the System.Diagnostics.Contracts namespace has a number of static methods that can be used in a similar way to assertions in unit tests. With them we can tidy up our validation code…

interface IAccount
{
  string Name { get; }
  double Balance { get; set; }
}
class BankAccount : IAccount
{
  // Name is required, so add it to the constructor...
  public BankAccount(string name)
  {
    Contract.Requires<ArgumentNullException>(!string.IsNullOrEmpty(name));

    Name = name;
  }
  public readonly string Name;

  private double _balance;

  public double Balance
  {
    get
    {
      return _balance;
    }
    set
    {
      Contract.Requires<ArgumentNullException>(value >= 0, "Your Bank does not allow your account to be negative.");

      _balance = value;
    }
  }
}

static class TransferService
{
  public static void TransferMoney(IAccount from, IAccount to, double amount)
  {
    Contract.Requires<ArgumentNullException>(from != null, "from cannot be null");
    Contract.Requires<ArgumentNullException>(to != null, "to cannot be null");
    Contract.Requires<ArgumentNullException>(from.Balance >= amount, "'from' account does not have enough money to transfer");

    from.Balance -= amount;
    to.Balance += amount;
  }
}

So now you’re thinking “Well, that’s nice. My code is a little tidier, but I’ve effectively just changed syntax.”. And you’d be right – almost. The benefit to using the Contract methods is that they can be evaluated at compile time and during static analysis. However, in order to reach the tipping point where you might start thinking “OK, I’m going to use this!” we have to start using some of the Contract Attributes.

Contract Attributes

Contract Attributes allow you to move your validation to a separate class.

[ContractClass(typeof(AccountContract))]
interface IAccount
{
  string Name { get; }
  double Balance { get; set; }
}
[ContractClassFor(typeof(IAccount))]
class AccountContract : IAccount
{
  public string Name
  {
    get
    {
      return string.Empty;
    }
  }

  public double Balance
  {
    get
    {
      return 0;
    }
    set
    {
      Contract.Requires<ArgumentNullException>(value >= 0, "Your Bank does not allow your account to be negative.");
    }
  }
}

class BankAccount : IAccount
{
  public readonly string Name;
  public double Balance { get; set; }

  public BankAccount(string name)
  {
    Name = name;
  }
}

Now that’s much nicer. Now all my validation logic is in a separate class and, with the use of the ContractClass and ContractClassFor attributes, my interface now defines my entire contract.

Contract Invariance

Another very useful attribute is ContractInvariantMethod. This allows you to decorate one, and only one, method in your class that contains contract logic that will be validated every time a property changes on your class. You don’t even have to worry about calling it yourself! We could use that to tidy up our AccountContract class…

[ContractClassFor(typeof(IAccount))]
class AccountContract : IAccount
{
  public string Name;
  public double Balance { get; set; }

  [ContractInvariantMethod]
  private void ObjectInvariant()
  {
    Contract.Invariant(!string.IsNullOrEmpty(Name), "Name cannot be empty.");
    Contract.Invariant(Balance >= 0, "Balance cannot be negative.");
  }
}

In order to introduce another feature of the Contracts namespace I will change the IAccount interface so that Balance is only gettable. This, then, requires the addition of 2 new methods to withdraw and deposit money to the account…

[ContractClass(typeof(AccountContract))]
interface IAccount
{
  string Name { get; }
  double Balance { get; }
  void WithdrawMoney(double amount);
  void DepositMoney(double amount);
}

Change Awareness (OldValue)

So, what contract should we define for these new methods? In each case ‘amount’ needs to be non-negative but also the Balance needs to change by the correct amount. If I deposit £10 I expect my Balance to increase by the same amount. We can make good use of Contract.OldValue for this…

[ContractClassFor(typeof(IAccount))]
class AccountContract : IAccount
{
  public string Name { get; private set; }
  public double Balance { get; set; }

  [ContractInvariantMethod]
  private void ObjectInvariant()
  {
    Contract.Invariant(!string.IsNullOrEmpty(Name), "Name cannot be empty.");
    Contract.Invariant(Balance >= 0, "Balance cannot be negative.");
  }

  public void WithdrawMoney(double amount)
  {
    Contract.Requires<ArgumentNullException>(amount >= 0);

    Contract.Ensures(Balance == Contract.OldValue(Balance) - amount);
  }
  public void DepositMoney(double amount)
  {
    Contract.Requires<ArgumentNullException>(amount >= 0);

    Contract.Ensures(Balance == Contract.OldValue(Balance) + amount);
  }
}

Putting it all together

Finally, you’re going to need to download a Microsoft DevLabs addon to Visual Studio to make all this work. DevLabs: Code Contracts automatically changes your code during compilation to bind you contract classes referenced in your interfaces to you concrete classes.

Conclusions

Code Contracts simplify validation, complete your interface definitions and keep you code clean. It enhances Design Patterns, for instance the Adapter Pattern, by allowing your interface to express your entire intent. I haven’t covered anywhere near what this namespace can do for you, so go check out the rest yourselves!

 
Leave a comment

Posted by on June 8, 2010 in C#

 

Tags:

Enhancing the Aggregate Pattern in Domain Driven Design with Weak References

Note: This post makes use of the generic WeakReference class illustrated in this post.

I’m working my way through Eric Evan‘s wonderful book Domain Driven Design and, already, it has a place on my “books-every-developer-should-read” shelf. One of the 3 main design patterns covered in chapter 6 is Aggregate. One of the tenets of this pattern is that external objects can request a reference to an internal object of the Aggregate on the assumption that they use it fleetingly and do not hold a permanent reference to it. The reason for this is that the Aggregate needs to be disposable as a whole and this will not happen if some internal objects are still being referenced.

Now, the problem with this is that, certainly in .Net, there is nothing in the language to enforce this requirement. As a developer you have to write your Aggregates and hope that the next developer to consume them understands the pattern requirements. A simple recipe for disaster!

Enter the genreric WeakReference class.

I’ll extend Eric’s example using his idea of a Car class (omitting any Factory or Repository complications)…

public enum WheelLocation
{
  FrontLeft,
  FrontRight,
  RearLeft,
  RearRight
}
public class Wheel : IDisposable
{
  public readonly WheelLocation Location;

  public Wheel(WheelLocation location)
  {
    Location = location;
  }

  public void Dispose()
  {
  }
}

public class Car : IDisposable
{
  public readonly Guid ID;
  private readonly IList<Wheel> _wheels;

  public Car(Guid id)
  {
    ID = id;

    _wheels = new List<Wheel>(4);

    _wheels.Add(new Wheel(WheelLocation.FrontLeft));
    _wheels.Add(new Wheel(WheelLocation.FrontRight));
    _wheels.Add(new Wheel(WheelLocation.RearLeft));
    _wheels.Add(new Wheel(WheelLocation.RearRight));
  }

  public void Dispose()
  {
    foreach (IDisposable obj in _wheels)
      obj.Dispose();
  }

  public Wheel GetWheel(WheelLocation location)
  {
    return _wheels.Where(w => w.Location == location).Single();
  }
}

So, we now have a nicely encapsulated Car Aggregate class that can also, indirectly, supply any consumers with references to its internal objects (Wheels). Here’s a (kinda dumb!) usage example…

public class WheelEventArgs : EventArgs
{
  public readonly Wheel Wheel;

  public CarEventArgs(Wheel wheel)
    : base()
  {
    Wheel = wheel;
  }
}

public class CarConsumer
{
  public void CreateCar(Guid id)
  {
    using (var car = new Car(id))
    {
      OnCarCreate(car);
    }
  }

  protected virtual void OnCarCreated(Car car)
  {
    if (CarCreated != null)
    {
      CarCreated(this, new EventArgs(car.GetWheel(WheelLocation.FrontLeft));
      CarCreated(this, new EventArgs(car.GetWheel(WheelLocation.FrontRight));
      CarCreated(this, new EventArgs(car.GetWheel(WheelLocation.RearLeft));
      CarCreated(this, new EventArgs(car.GetWheel(WheelLocation.RearRight));
    }
  }

  public event CarCreated;
}

The problem here is that we have no way of knowing whether the classes that registered to the CarCreated event still have references to the Wheel objects when we come to dispose our Car class.

So, what we can do is change the GetWheel method to return weak references to the internal wheels…

public WeakReference<Wheel> GetWheel(WheelLocation location)
{
  return new WeakReference<Wheel>(_wheels.Where(w => w.Location == location).Single());
}

Now, this doesn’t prevent the external objects from securing a strong reference to the wheels and it doesn’t stop dumb developers doing dumb things; but it does indicate our intention with the pattern. “Hey, look, I’m returning a WeakReference to this object – there’s a reason for it!

 
1 Comment

Posted by on April 20, 2010 in C#

 

Tags: , ,

Generic WeakReference Class

The WeakReference class is used to get a reference to an object X in such a way that the garbage collector (GC) can still reclaim it. Holding a ‘normal’, strong reference to object X would stop the GC from collecting it.

The .Net BCL currently only contains a non-generic class for this functionality, so I wrote a simple generic version…

namespace System
{
  public class WeakReference<T> : WeakReference
  {
    public new T Object
    {
      get
      {
        return (T)base.Target;
      }
      set
      {
        base.Target = value;
      }
    }
    public WeakReference(T target)
      : base(target)
    {
    }
    public WeakReference(T target, bool trackResurrection)
      : base(target, trackResurrection)
    {
    }
    protected WeakReference(SerializationInfo info, StreamingContext context)
      : base(info, context)
    {
    }
  }
}

And here’s how you can use it…

public class Dog : IDisposable
{
  public readonly string Name;

  public Dog(string name)
  {
    Name = name;
  }

  // IDisposable routines left out for brevity
}

public class Consumer
{
  public void DoSomething()
  {
    using (var myDog = new Dog("Dioji"))
    {
      var weakReference = new WeakReference<Dog>(myDog);

      Console.WriteLine("My dog is called '{0}'.", weakReference.Object.Name);
    }
  }
}

I’ll demonstrate why this can be really useful in my next post on the “Enhancing the Aggregate Pattern in Domain Driven Design with Weak References“.

 
Leave a comment

Posted by on April 20, 2010 in C#

 

Tags: ,

Supercede Instance Pattern

This is a pattern introduced (to me at least) by Michael Feathers in his book “Working Effectively with Legacy Code“. It deals with occasions where you have a Singleton pattern that it consumed by a large number of classes. This impedes these classes being Unit Tested as they all have a hidden dependency.

The first solution to this is to add a constructor overload to every class. You will also need to extract an interface for the Singleton. For instance…

public class MyClass
{
  public MyClass()
  {
  }

  public void DoWork()
  {
    MySingleton.Instance.DoWork();
  }
}

… would become …

public class MyClass
{
  private IMySingleton _worker;

  public MyClass()
    : this (MySingleton.Instance)
  {
  }

  public MyClass(IMySingleton worker)
  {
    _worker = worker;
  }

  public void DoWork()
  {
    _worker.DoWork();
  }
}

You won’t have to change any other code once the above it implemented. What this achieves is that your Unit Tests have the opportunity to use a Dependency Inversion pattern by using the non-default constructor. Simple, and nothing new.

However, this can be an awful lot of work – directly proportional to the number of classes that consume your singleton. This is where the Supercede Instance Pattern comes in.

This is probably a fair representation of the Singleton Pattern…

public class MySingleton : IMySingleton
{
  private MySingleton()
  {
  }
  
  private static IMySingleton _instance;

  public static IMySingleton Instance
  {
    get
    {
      // Double locking mechanism omitted for brevity...
      if (_instance == null)
        _instance = new MySingleton();
    }
  }
}

All we need to do is add a new method to the above class…

public class MySingleton : IMySingleton
{
  // All previous members omitted for brevity</pre>
  public static void SupercedeInstance(IMySingleton newInstance)
  {
    _instance = newInstance;
  }
}

Et voila. Your unit tests can call this new method and inject their own, chosen object into the Singleton. You’ve now broken the dependency of masses of classes in one hit. Nice.

Final point, if your language allows you could conditionally remove this method. That would keep your singleton ‘safe’ in the wild. For example…

public class MySingleton : IMySingleton
{
  #if RUNNING_UNIT_TESTS
  
  public static void SupercedeInstance(IMySingleton newInstance)
  {
    _instance = instance;
  }

  #endif
}
 
Leave a comment

Posted by on January 9, 2010 in C#

 

Tags: , , , ,

Moq Setup Causes Compiler Error CA1506

I have been using Moq to help enable some unit tests and I’ve been getting intermittent build exceptions caused by the Code Analysis engine when calling the Setup method of my new mock object.

Example:

var mock = new Mock<IDoSomething>();

mock.Setup(x => x.DoSomething());

CA1506 is raised as a warning to Avoid excessive class coupling. This is, obviously, a little strange. Stranger still is that this warning results in a compilation error.

Anyway, it’s a bug in Visual Studio. The workaround is just to remove this check from your Code Analysis (goto Project Properties | Code Analysis | Maintainability Rules and uncheck CA1506).

 
Leave a comment

Posted by on December 7, 2009 in C#

 

Tags: , ,