Why cripple the .NET RSA implementation?

I just found out that RSACryptoServiceProvider, the RSA implementation in .NET, does not allow you to use a private key to encrypt data. I’m no cryptographic expert, but I do know how asymmetric key algorithms like RSA work, and that you can use a private key for encryption. That’s how signing works. But why cripple the implementation and limit it to just signing?

The rationale is in the common application of public-key cryptography, where:

  • Encrypting with the public key ensures confidentiality, i.e. the process known as encryption in common tongue. Encrypting with a public key ensures that only the entity in possession of the private key can read the data.
  • Encrypting with the private key ensures authenticity, i.e. the process known as signing in common tongue. There is no need to encrypt the entire data stream to ensure authenticity, so the common approach is to calculate a hash of the data and sign the hash instead.

To facilitate these patterns, the .NET public-key cryptography API is designed so that:

  • Encrypt() encrypts with a public key, Decrypt() requires a private key.
  • SignData() encrypts with a private key, but since that implies a signature, one must provide a hashing algorithm and a private key. VerifyData() uses a public key.

But I want to encrypt with my private key! Yes, this is what SignData() does, but it does so to just the hash calculated by the provided hashing algorithm, since that is the de-facto approach for signing, and implementing my own HashAlgorithm that passes in all the data is just wrong.

OK, these are the common uses, but why limit the API to that? There is no limitation in the RSA algorithm to my knowledge that prevents other uses than the two offered by RSACryptoServiceProvider. In fact, if I wanted to perform the traditional signing approach, I could just hash the data myself and encrypt it with my private key myself. Or even better, SignData() could be available to help me for convenience.

So, how do you apply RSA in .NET in an uncommon manner? Don’t use .NET’s cryptography API, but embrace an open source alternatives like BouncyCastle, which saves your day.

Strongly typed data binding in Windows Forms

Windows Forms data binding is a great tool for model-view-style applications, where the connection between the model and its view is easily declared. However, data binding is also an error-prone and tedious process with no IntelliSense support where properties are specified as strings.

Tired of the need of looking up property names when you declare data bindings? Sick of mistyping a property name when you bind and not discovering the mistake until you run your application? Have a look at Strongbind.

Strongbind vs traditional data binding

Traditional data binding is typically declared like this:

// Assume we have a binding source with 
// a description, and a text box
// This binds the Text property of the text 
// box to the Description property of the source
textBox.DataBindings.Add("Text", bindingSource, 
    "Description");

Obviously, many errors can arise from this declaration: Your control may not have a Text property, or you might have spelled it wrong. The same goes the Description property of your source.

The same declaration in Strongbind is written as follows:

using(BindingScope scope = new BindingScope())
{
    // Create bindables
    IBusinessObject bindableSource = 
        scope.CreateSource(bindingSource);
    TextBox bindableTarget = 
        scope.CreateTarget(textBox);</p>

<pre><code>// Declare bindings
Binder.Bind(bindableSource.Description)
    .To(bindableTarget.Text);
</code></pre>

<p>}

As you probably understand, the risk of mistyping is removed, and we get IntelliSense support out of the box.

Behind the scenes of Strongbind

To achieve this strongly typed data binding, Strongbind uses a technique known as proxying. Strongbind dynamically generates a proxy for your business object and your control, and uses the proxies to intercept the calls to the property getters during runtime to declare the data binding. Hence, you need to declare a bindable source and bindable target first to create the proxies, and then use these proxies during the binding declaration. You will get a runtime error if you try to use your real objects when declaring data bindings.

Limitations of Strongbind

Although Strongbind makes data binding a far more declarative process, the library does have its limitations.

Controls containing ActiveX components are not supported. If the control containing an ActiveX component is a custom control created by you, you can get around it by declaring an interface for the control and specifying that as the type to use when declaring your binding source:

// The control interface 
// (must inherit IBindableComponent)
public interface IBindableAXControl 
    : IBindableComponent 
{
    string Text { get; set; }
}</p>

<p>// Declare the binding target this way within a 
// binding scope
IBindableAXControl source = 
   scope.CreateTarget<IBindableAXControl>(control);

Also, binding to concrete binding sources with non-virtual properties is not supported. Again, the recommended workaround is to create an interface for your binding source and use that when declaring the data bindings. (You always want to create these interfaces, since decoupling your objects’ interfaces from their implementation is recommended for testability, maintainability, and is generally A Good Thing(tm).)

// The business object interface
public interface IBusinessObject
{
    string Description { get; set; }
}</p>

<p>// Declare the binding source this way within a 
// binding scope
IBusinessObject bindableSource = 
    scope.CreateSource<IBusinessObject>(source);

Apart from these two issues, which can be worked around in most cases, Strongbind should work flawlessly. If it does not, I would be happy to know.

Where do I get it?

Strongbind is an open source project hosted at Google Code. To get the latest version, check out the code from its repository.

Strongbind is still in an early development stage, so no releases have been created yet. I still encourage you to check out and start using the library as soon as possible, though. A beta will be released as soon as I feel comfortable doing it.

If you want to contribute to Strongbind, I would be happy to welcome you. Visit http://strongbind.googlecode.com for instructions.

Bind away!

Extension methods for copying or cloning objects

C# 3.0 includes a new feature known as extension methods, and fiddling with it triggered the idea of creating a mechanism for copying or cloning (virtually) any .NET object or graph of objects. The manifestation of that idea has become a rather decent little framework for copying objects. It performs a deep copy as automatically as it possibly can, and provides mechanisms to easily solve many of the cases which cannot be covered automatically. It is great for copying your custom object hierarchies, and saves you the pain of a solution like implementing ICloneable for an entire hierarchy of objects. Click here to grab it now, and read on for a presentation.

Let’s start off with a few words on extension methods. They are best explained through an example. Let’s say we want to be able to calculate area given size. Wouldn’t it be nice to be able to add GetArea to the already existing Size class? Well, let’s do so!

public static class ExtensionMethods
{
  public static int GetArea(this Size size)
  {
    return size.Width * size.Height;
  }
}
As you can see, the new syntax simply allows you to tell the compiler that the this of this method is a Size. This means that the method is an extension of the Size class.

As mentioned, I had the idea of extending the very base of the C# class hierarchy (System.Object) with a method for copying or cloning “any” object. Obviously, the method cannot automatically copy any object, since it cannot possibly know how to construct an object from an arbitrary class. Hence, a small framework needed to be created. The goals were to:

  • Enable copying of many objects automatically.
  • Enable copying of virtually any object with very little effort.
  • Automate and hide away as much as possible (The KISS Principle).

The result is Copyable (pun intended).

The Copyable framework

Copyable is a small framework for copying (or cloning, if you will) objects. The straightforward way of using it is to just reference the assembly it’s in from your project, and start copying!

SomeType instance = new SomeType();
// ...do lots of stuff to the object...
SomeType copy = instance.Copy(); // Create a deep copy

The instance copy is now a deep copy of instance, no matter how complex the object graph for instance is. The relations in the copy graph is the same as in instance, but all objects in the copy object graph are copies of those in instance.

For the automated copy to work, though, one of the following statements must hold for instance:

  • Its type must have a parameterless constructor, or
  • It must be a Copyable, or
  • It must have an IInstanceProvider registered for its type.

Besides the Copy method, The Copyable class and IInstanceProvider interface are the two major building blocks of the Copyable framework. Each of these blocks enable copying of objects that cannot automatically be copied.

The Copyable base class

Copyable is an abstract base class for objects that can be copied. To create a copyable class, you simply subclass Copyable and call its constructor with the arguments of your constructor.

class MyClass : Copyable
{
  public MyClass(int a, double b, string c)
    : base(a, b, c)
  {
  }
}

This code above makes MyClass a copyable class. Note that if MyClass had had a parameterless constructor, subclassing Copyable would not be necessary.

MyClass can now be copied just like the previous example.

MyClass a = new MyClass(1, 2.0, "3");
MyClass b = a.Copy();

The introduction of the Copyable base class solves many problems, but not all. Let’s say you wanted to copy a System.Drawing.SolidBrush. This class does not have a parameterless constructor, which means it cannot be copied “automatically” by the framework. Also, you cannot alter it so that it subclasses Copyable. So, what do you do? You create an instance provider.

The IInstanceProvider interface

An instance provider is defined by the interface IInstanceProvider. As the name clearly states, the implementation is a provider of instances. One instance provider can provide instances of one given type. The Copyable framework automatically detects IInstanceProvider implementations in all assembies in its application domain, so all you need to do to create a working instance provider is to define it. No registration or other additional operations are required. To simplify the implementation of instance providers and the IInstanceProvider interface, an abstract class InstanceProvider is included in the framework.

public class SolidBrushProvider</dt>
<dd>InstanceProvider<SolidBrush>
{
public override SolidBrush CreateTypedCopy(SolidBrush s)
{
return new SolidBrush(s.Color);
}
}

This implementation will be used automatically by the Copyable framework. NOTE: To be usable, the instance provider MUST have a parameterless constructor.

The instance provider pattern does not solve the case where you want different initial states for your SolidBrush instances depending on which context you use them for copying. For those cases, an overload of Copy() exists which takes an already created instance as an argument. This argument will become the copy.

SolidBrush instance = new SolidBrush(Color.Red);
instance.Color = Color.Black;
SolidBrush copy = new SolidBrush(Color.Red);
instance.Copy(copy); // Create a deep copy

In this example, copy is now of the color Color.Black.

Limitations and pitfalls

Although this solution works in most cases, it’s not a silver bullet. Be aware when you copy classes that hold unmanaged resources such as handles. If these classes are designed on the premise that their resources are exclusive to them, they will manage them as they see fit. Imagine if you copied a class which holds a handle, disposed one of the instances, and continued using the copy. The handle will (probably) be freed by the original instance, and the copy will generate an access violation by attempting reading or writing freed memory.

That’s it! The Copyable framework can be downloaded from here. For those interested in reading more on extension methods, For additional information, MSDN provides an excellent explanation in the C# Programming Guide, and Scott Guthrie has an introduction article here.

Enjoy Copyable, and please let me know if you find it useful or come across any problems with it.

UPDATE 2009-12-11: Due to popular demand, I have made the source code for Copyable available under the MIT license. The source can be downloaded here.

UPDATE 2010-01-31: The requirement of parameterless constructors has been removed in the latest version of Copyable available on GitHub. A new release will follow soon.