title: HMAC SHA1 with NSData input Objective-C
body: <p>I need to hash a NSData input with HMAC-SHA1. I used this code:</p>
  
  <pre><code>- (NSString *)HMACSHA1:(NSData *)data {
      NSParameterAssert(data);
  
      const char *cKey = [@"SampleSecretKey012345678" cStringUsingEncoding:NSUTF8StringEncoding];
      const void *cData = [data bytes];
  
      unsigned char cHMAC[CC_SHA1_DIGEST_LENGTH];
  
      CCHmac(kCCHmacAlgSHA1, cKey, strlen(cKey), cData, strlen(cData), cHMAC);
  
      NSData *HMAC = [[NSData alloc] initWithBytes:cHMAC length:sizeof(cHMAC)];\
  
      /* Returns hexadecimal string of NSData. Empty string if data is empty. */
  
      const unsigned char *dataBuffer = (const unsigned char *)[HMAC bytes];
  
      if (!dataBuffer) {
          return [NSString string];
      }
  
      NSUInteger dataLength = [HMAC length];
      NSMutableString *hexString = [NSMutableString stringWithCapacity:(dataLength * 2)];
  
      for (int i = 0; i &lt; dataLength; ++i) {
          [hexString appendFormat:@"%02x", (unsigned int)dataBuffer[i]];
      }
  
      return [NSString stringWithString:hexString];
  }
  </code></pre>
  
  <p>but the hex string output is always wrong (checked from server). I think the problem is this line:</p>
  
  <p><code>const void *cData = [data bytes];</code></p>
  
  <p>because if convert data (sample "test" string) in the same way as key:</p>
  
  <p><code>const void *cData = [@"test" cStringUsingEncoding:NSUTF8StringEncoding];</code></p>
  
  <p>then check the result using this page: <a href="http://myeasywww.appspot.com/utility/free/online/Crypt_Decrypt-MD5-AES-HMAC-SHA-DES-RABBIT/en?command=UTILITY&amp;ID=2" rel="nofollow">HMAC crypt</a>, the result is matched.</p>
  
  <p>If I hash a NSString then I can use <code>cStringUsingEncoding:</code> but I can't figure out convert NSData to <code>const void*</code>. Anyone can help me? Thanks!</p>