将上述代码封装成一个函数
时间: 2024-02-26 10:57:39 浏览: 68
好的,这里是我封装后的代码,函数的参数依次为 JSON 字符串指针、密钥、签名键名:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <openssl/hmac.h>
#include "cJSON.h"
char *sortJsonString(cJSON *json);
char *getSign(char *jsonString, char *key);
char *addSignToJson(char *jsonString, char *key, char *signKey);
char *sortJsonString(cJSON *json) {
int count = cJSON_GetArraySize(json);
char **keys = (char **) malloc(count * sizeof(char *));
int i = 0;
cJSON_ArrayForEach(json, json) {
keys[i++] = strdup(json->string);
}
qsort(keys, count, sizeof(char *), strcmp);
char *sortString = (char *) malloc(1);
sortString[0] = '\0';
for (int i = 0; i < count; i++) {
cJSON *item = cJSON_GetObjectItemCaseSensitive(json, keys[i]);
if (item->type == cJSON_Object) {
char *subSortString = sortJsonString(item);
sortString = (char *) realloc(sortString, strlen(sortString) + strlen(keys[i]) + strlen(subSortString) + 3);
sprintf(sortString + strlen(sortString), "%s=%s&", keys[i], subSortString);
free(subSortString);
} else {
sortString = (char *) realloc(sortString, strlen(sortString) + strlen(keys[i]) + strlen(item->valuestring) + 3);
sprintf(sortString + strlen(sortString), "%s=%s&", keys[i], item->valuestring);
}
}
sortString[strlen(sortString) - 1] = '\0';
cJSON_ArrayForEach(json, json) {
free(keys[--i]);
}
free(keys);
return sortString;
}
char *getSign(char *jsonString, char *key) {
char *sortString = sortJsonString(cJSON_Parse(jsonString));
unsigned char *hmac = HMAC(EVP_sha256(), key, strlen(key), (const unsigned char *) sortString, strlen(sortString), NULL, NULL);
char *sign = (char *) malloc(65);
for (int i = 0; i < 32; i++) {
sprintf(&sign[i * 2], "%02x", hmac[i]);
}
sign[64] = '\0';
free(sortString);
return sign;
}
char *addSignToJson(char *jsonString, char *key, char *signKey) {
char *sign = getSign(jsonString, key);
cJSON *json = cJSON_Parse(jsonString);
cJSON_AddStringToObject(json, signKey, sign);
char *result = cJSON_Print(json);
free(sign);
cJSON_Delete(json);
return result;
}
```
`addSignToJson` 函数将前面的代码封装起来,并将签名键名作为参数传入。函数返回一个新的 JSON 字符串指针,需要注意在使用后释放内存。
阅读全文