Thursday, August 19, 2010

Getting a “System.ArgumentException: Value was invalid” when trying to sign data using SHA256CryptoServiceProvider

Here is the symptom:
1.    You are using RSACryptoServiceProvider for computing SHA-2 signatures.
2.    Doing this you get unhandled exceptions of type "System.ArgumentException" in mscorlib.dll saying "Value was invalid".
3.    A typical call that failed was:
byte[] signature = rsa.SignData(data, new SHA256CryptoServiceProvider());
4.    The SHA1CryptoServiceProvider did not reproduce the exception.
5.    Additionally you have FIPS policy enabled.
The environment might be Windows Vista and above with .Net Framework version 3.5 or above. The code snippet that reproduces this issue is:
namespace SignData 
{ 
   class Program 
   { 
       static void Main(string[] args) 
       { 
           byte[] data = new byte[] { 0, 1, 2, 3, 4, 5 };

           using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider()) 
           { 
               SHA256CryptoServiceProvider ha = new SHA256CryptoServiceProvider(); 
               byte[] signature = rsa.SignData(data, ha);

               if (rsa.VerifyData(data, new SHA256CryptoServiceProvider(), signature)) 
               { 
                   Console.WriteLine("RSA-SHA256 signature verified"); 
               } 
               else 
               { 
                   Console.WriteLine("RSA-SHA256 signature failed to verify"); 
               } 
           } 
       } 
   } 
}


This code is directly referenced from the blog http://blogs.msdn.com/shawnfa/archive/2008/08/25/using-rsacryptoserviceprovider-for-rsa-sha256-signatures.aspx and my intension is to show the exception.
Read more: LogIn SDK - Windows SDK team blog