hash_hmac

近期做了一个项目有用到 hmac 算法 当然php 有现成的函数了 hash_hmac()

但是在IOS端怎么也获取不到对应的值

现在记录一下 

hash_hmac(加密算法,秘钥,加密数据,HEX or BUFFER)

这里我们实现的是 HMac_SHA1 算法

 

1 <?php
2  $hash = hash_hmac ('sha1',$key,$data,false);
3  echo $hash;
4  
5 ?>

IOS 端 查阅的资料基本都是基于NSDATA 或者 Hmac_sha1 BASE64 的

 

而基本的 HEX 的方法 确没有查到

几经实验 现将 实现方法记录如下

 

 

01 + (NSString *) hmacSha1:(NSString*)key text:(NSString*)text
02 {
03     const char *cKey  = [key cStringUsingEncoding:NSUTF8StringEncoding];
04     const char *cData = [text cStringUsingEncoding:NSUTF8StringEncoding];
05      
06     uint8_t cHMAC[CC_SHA1_DIGEST_LENGTH];
07      
08     CCHmac(kCCHmacAlgSHA1, cKey, strlen(cKey), cData, strlen(cData), cHMAC);
09      
10     //NSData *HMAC = [[NSData alloc] initWithBytes:cHMAC length:CC_SHA1_DIGEST_LENGTH];
11     NSString *hash;
12     NSMutableString* output = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2];
13     for(int i = 0; i < CC_SHA1_DIGEST_LENGTH; i++)
14         [output appendFormat:@"%02x", cHMAC[i]];
15     hash = output;
16  
17     return hash;
18 }

posted on 2014-11-12 17:44  三十一  阅读(2533)  评论(0编辑  收藏  举报

导航