Dictionary key 根據ASCII排序並拼接key和value並HMACMD5-iOS

weixin_34279579發表於2017-01-06
//簽名演算法
//簽名生成的通用步驟如下:
//第一步,設所有傳送或者接收到的資料為集合M,將集合M內非空引數值的引數按照引數名ASCII碼從小到大排序(字典序),使用URL鍵值對的格式(即key1=value1&key2=value2…)拼接成字串stringA。
//特別注意以下重要規則:
//◆ 引數名ASCII碼從小到大排序(字典序);
//◆ 如果引數的值為空不參與簽名;
//◆ 引數名區分大小寫;


+(NSString *)signStr:(NSMutableDictionary*)dict
{
    NSMutableString *contentString  =[NSMutableString string];
    NSArray *keys = [dict allKeys];
    //按字母順序排序
    NSArray *sortedArray = [keys sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
    return [obj1 compare:obj2 options:NSNumericSearch];
}];
//拼接字串
  for (NSString *categoryId in sortedArray) {

      if (![[dict objectForKey:categoryId] isEqualToString:@""]
          && ![[dict objectForKey:categoryId] isEqualToString:@"sign"]
          && ![[dict objectForKey:categoryId] isEqualToString:@"key"]
        )
    {
        [contentString appendFormat:@"%@%@", categoryId, [dict objectForKey:categoryId]];
    }
  }
//HMACMD5
  NSString *signStr = [SignTool HMACMD5WithString:contentString WithKey:APPSECRET];
  return signStr;
}
+ (NSString *)HMACMD5WithString:(NSString *)toEncryptStr WithKey:(NSString *)keyStr
{
 const char *cKey  = [keyStr cStringUsingEncoding:NSUTF8StringEncoding];
const char *cData = [toEncryptStr cStringUsingEncoding:NSUTF8StringEncoding];
const unsigned int blockSize = 64;
char ipad[blockSize];
char opad[blockSize];
char keypad[blockSize];

unsigned int keyLen = strlen(cKey);
CC_MD5_CTX ctxt;
if (keyLen > blockSize) {
    CC_MD5_Init(&ctxt);
    CC_MD5_Update(&ctxt, cKey, keyLen);
    CC_MD5_Final((unsigned char *)keypad, &ctxt);
    keyLen = CC_MD5_DIGEST_LENGTH;
}
else {
    memcpy(keypad, cKey, keyLen);
}

memset(ipad, 0x36, blockSize);
memset(opad, 0x5c, blockSize);

int i;
for (i = 0; i < keyLen; i++) {
    ipad[i] ^= keypad[i];
    opad[i] ^= keypad[i];
}

CC_MD5_Init(&ctxt);
CC_MD5_Update(&ctxt, ipad, blockSize);
CC_MD5_Update(&ctxt, cData, strlen(cData));
unsigned char md5[CC_MD5_DIGEST_LENGTH];
CC_MD5_Final(md5, &ctxt);

CC_MD5_Init(&ctxt);
CC_MD5_Update(&ctxt, opad, blockSize);
CC_MD5_Update(&ctxt, md5, CC_MD5_DIGEST_LENGTH);
CC_MD5_Final(md5, &ctxt);

const unsigned int hex_len = CC_MD5_DIGEST_LENGTH*2+2;
char hex[hex_len];
for(i = 0; i < CC_MD5_DIGEST_LENGTH; i++) {
    snprintf(&hex[i*2], hex_len-i*2, "%02x", md5[i]);
}

NSData *HMAC = [[NSData alloc] initWithBytes:hex length:strlen(hex)];
NSString *hashStr = [[NSString alloc] initWithData:HMAC encoding:NSUTF8StringEncoding] ;
NSString *hash= [hashStr uppercaseString];

return hash;
}

相關文章