views:

42

answers:

1

I'm receiving a CryptographicException "Bad Hash.\r\n" from the code below when I call CreateSignature. Any ideas as to what might be causing this?

RSAPKCS1SignatureFormatter RSAFormatter = 
    new RSAPKCS1SignatureFormatter(new RSACryptoServiceProvider());
RSAFormatter.SetHashAlgorithm("SHA256");
byte[] signedHash = RSAFormatter.CreateSignature(myHash);
+2  A: 

Your code snippet does not show how you get myHash but my guess is that it is not a 32 byte array. From MSDN:

The hash size for the SHA256 algorithm is 256 bits.

Try defining your myHash like this: (Just an ugly sample here)

    // 256 bit hash size
    byte[] myHash = { 59,4,248,102,77,97,142,201,
          210,12,224,93,25,41,100,197,
          210,12,224,93,25,41,100,197,
          213,134,130,135, 213,134,130,135};

When i ran your code with a hash of any other size i got the same exact error. Running with the array defined above, 256 bits or 32 bytes, it worked.

Paul Sasik
Looks like my understanding was wrong. I thought CreateSignature would create the hash and the signature, but it looks like SetHashAlgorithm is intended to inform the formatter what hash algorithm was used. Is that correct?
Taylor Leese
Yes. It's a strange API. One static call to set a static flag and then another to consume it? Odd. If the designers had thought it through better they would have made it instances or for static calls, included the algorithm type with each call as a param.
Paul Sasik