我想让代码只有一个函数 比如getSign函数可以去掉
时间: 2023-12-08 17:02:52 浏览: 96
ABAP常用函数
4星 · 用户满意度95%
好的,下面是只有一个函数的代码:
```
char *addSignToJson(char *jsonString, char *key, char *signKey) {
cJSON *json = cJSON_Parse(jsonString);
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';
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';
cJSON_AddStringToObject(json, signKey, sign);
char *result = cJSON_Print(json);
for (int i = 0; i < count; i++) {
free(keys[i]);
}
free(keys);
free(sortString);
cJSON_Delete(json);
free(sign);
return result;
}
```
这个函数整合了原来的三个函数,使用了相同的内部逻辑。同时,为了方便内存的释放,我们使用了和原来相同的变量名。
阅读全文