Tuesday, November 2, 2010

HMAC MD5 in Flex and .Net

Regarding to my previous post, HMAC is a message authentication code (MAC) and can be used to verify the integrity and authentication of a message. I was trying to consume WCF Rest services from Flex. I wanted to create a digital signature for the URL of the service in flex and then send to WCF side in .Net and then create that hash and then compare with that signature sent from flex side, I spent some hours having a problem, because the hash sent from flex side did not match the hash computed on the WCF .net side. finally I found the reason and make it work. the point was in wcf side, after computing the hash,I need to convert to hex string.

Flex side
---------------------------------------------
import mx.utils.Base64Encoder;    
import com.adobe.crypto.MD5;
import com.adobe.crypto.HMAC;
 
var hashed: String = HMAC.hash(secret, msg, MD5);
var encoder : Base64Encoder = new Base64Encoder();
encoder.insertNewLines=false;
encoder.encode(hashed);
return encoder.toString();


.Net WCF side
----------------------------------------------
private static string CreateSignature(string uri, string secret)
{
    byte[] secretBytes = System.Text.UTF8Encoding.UTF8.GetBytes(secret);
    System.Security.Cryptography.HMACMD5 hmac = new System.Security.Cryptography.HMACMD5(secretBytes);
    byte[] dataBytes = System.Text.UTF8Encoding.UTF8.GetBytes(uri);
    byte[] computedHash = hmac.ComputeHash(dataBytes);
    //--------------------------------------------------
    System.Text.StringBuilder sb = new System.Text.StringBuilder();
    for (int i = 0; i < computedHash.Length; i++)
    {
       sb.Append(computedHash[i].ToString("x2")); // hex format
    }
    //-------------------------------------------------------
    string encoded = Convert.ToBase64String(System.Text.UTF8Encoding.UTF8.GetBytes(sb.ToString()));
    return encoded;
}

Cheers!

2 comments:

Jack said...

Thanks !

lauren said...

I am also working on some requirement to consume WCF Rest services from Flex.For which I am facing exactly same problem.I was not aware that in wcf side, after computing the hash,I need to convert to hex string.As you mentioned above hopefully this will solve my problem too.Thanks for sharing it here
electronic signature sharepoint

Post a Comment