Friday, October 15, 2010

Digital Signature in REST Services to maintain the integrity of sensitive data in URI

When we think about REST web service, we all have heard this recommendation that we had better keep the application state on the client side, if the data regarding to the application state is not that large, then we can put that data in the URI, if you decide to do that to manage the state, then you need to have some kind of checking to make sure that state data has not been tampered. one option is using digital signature.
We are going to use signature to maintain the integrity of sensitive data contained in the URI. To detect tampering, we compute the digital signature of the data in the URI using hash algorithms like HMACMD5 and then encode using base64 and then put that signature in the URL as another query parameter.
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;

then on the server, for any coming request, we can compute the hash again and compare with the signature parameter in the query string. if it is the same, it means the URI has not been altered.


richa said...

Hey Saeed, you have given a detailed account of digital signatures in rest services.Moreover,you have given the code.I will certainly try it and let you know about it.
electronic signature

myrtle mayers said...

Hi there! glad to drop by your page and found these very interesting and informative stuff. Thanks for sharing, keep it up!

- online signature

Post a Comment