Taylor Leese
Taylor Leese

Reputation: 52292

C# - CryptographicException "Bad Hash"

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);

Upvotes: 4

Views: 4942

Answers (2)

Vladimir
Vladimir

Reputation: 11

byte[] bPlainText;
bPlainText = Encoding.UTF8.GetBytes(PlainText);
SHA256 sha256 = new SHA256Managed();
bPlainText=sha256.ComputeHash(bPlainText);

Upvotes: 0

Paul Sasik
Paul Sasik

Reputation: 81429

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.

Upvotes: 3

Related Questions