Signing XML in .Net has been supported since I started working with .Net. Signing XML with SHA-256 signatures is a different story, this wasn’t supported out of the box and you had to write some obscure code. Luckily this will change with the release of .Net 4.6.2. In this post I will show how to sign XML with SHA-256 signatures before the release of .Net 4.6.2 and after.
The first step in both scenario’s is to obtain a digital certificate which can be used for SHA-256 signing on Windows. A good to follow tutorial can be found here. After obtaining this certificate you can write code which uses the certificate to digitally sign XML.
Before .Net 4.6.2
The first step is to register a SignatureDescription class that defines SHA-256 as the digest algorithm. .NET already contains a class called “RSAPKCS1SHA1SignatureDescription” that supports SHA1. We have to create a similar class for SHA-256:
We need to register this class with the framework before we can use it:
You can see it being registered on line 12, in the static initializer of our extension class. This class also contains a method which can be used to digitally sign an XML document with SHA-256:
You can see the reference being made to SHA-256 on line 32 and on line 24. With this method you can sign XML documents using SHA-256, pre .Net 4.6.2.
After .Net 4.6.2
After .Net 4.6.2 is released, we don’t need any of our custom classes, as both the SHA-256 description class and the namespace constants (they are present on the SignedXml class) are provided by the framework. This means that the modified method for .Net 4.6.2 will look like this:
With the release of .Net 4.2.6, the platform get’s a long awaited update to the Crypto api’s. You can change the references in the above method to references to SHA-384 or SHA-512 and those will also work. For a complete overview of what else is new in the Crypto api’s and other stuff, you can take a look here.