// // Created by xajhuang on 2022/12/2. // #include #include #include "config.h" #include "misc.h" #include "proto.h" #include "crypto.h" #include "user_errno.h" #define CURRENT_PROTOCOL_VERSION (1) typedef struct { unsigned int ver; unsigned int cryptoType; unsigned long long timeStamp; unsigned int code; cJSON *msgContend; } PROTOCOL_WARP, *PPROTOCOL_WARP; const char *proto_create_new(cJSON *pMsgCtx, int rspCode) { const char *pStrProto; cJSON *pRoot; PROTOCOL_WARP pro = {.ver = CURRENT_PROTOCOL_VERSION, .cryptoType = config_get_proto_crypto_type(), .timeStamp = get_current_time_ms(), .code = rspCode}; pRoot = cJSON_CreateObject(); if (pRoot == NULL) { return NULL; } cJSON_AddNumberToObject(pRoot, "ver", pro.ver); cJSON_AddNumberToObject(pRoot, "cryptoType", pro.cryptoType); cJSON_AddNumberToObject(pRoot, "timeStamp", (double)pro.timeStamp); cJSON_AddNumberToObject(pRoot, "code", pro.code); if (pMsgCtx == NULL) { pro.msgContend = cJSON_CreateObject(); } else { pro.msgContend = pMsgCtx; } switch (pro.cryptoType) { case CRYPTO_NONE: cJSON_AddItemToObject(pRoot, "msgContent", pro.msgContend); break; case CRYPTO_BASE64: { const char *pStrMsg = cJSON_Print(pro.msgContend); const char *base64 = base64_encode((unsigned char *)pStrMsg, strlen(pStrMsg)); cJSON_AddStringToObject(pRoot, "msgContent", base64); free((void *)base64); cJSON_free(pro.msgContend); } break; case CRYPTO_AES128: case CRYPTO_AES256: case CRYPTO_3DES: { int cryptoType; const char *pKey = config_get_proto_crypto_key(); const char *base64; const char *pStrMsg = cJSON_Print(pro.msgContend); if (pro.cryptoType == CRYPTO_AES128) { cryptoType = AES128_ECB_PKCS7PADDING; } else if (pro.cryptoType == CRYPTO_AES256) { cryptoType = AES256_ECB_PKCS7PADDING; } else { cryptoType = DES3_ECB_PKCS7PADDING; } if (pKey == NULL || strlen(pKey) == 0) { dzlog_error("Cryptography key empty of algorithm %d, Used default algorithm BASE64\n", cryptoType); base64 = base64_encode((unsigned char *)pStrMsg, strlen(pStrMsg)); pro.cryptoType = CRYPTO_BASE64; } else { int ret; unsigned char *buf; int outSize = 0; ret = symmetric_encrypto(cryptoType, (unsigned char *)pStrMsg, strlen(pStrMsg), &buf, &outSize, pKey); if (ret != ERR_SUCCESS) { dzlog_error("Unsupported protocol crypto : %d, Used default algorithm BASE64\n", cryptoType); base64 = base64_encode((unsigned char *)pStrMsg, strlen(pStrMsg)); pro.cryptoType = CRYPTO_BASE64; } else { base64 = base64_encode((unsigned char *)buf, outSize); } } cJSON_AddStringToObject(pRoot, "msgContent", base64); free((void *)base64); cJSON_free(pro.msgContend); } break; default: dzlog_error("Unsupported protocol crypto algorithms: %d, Used default algorithm BASE64\n", pro.cryptoType); cJSON_free(pro.msgContend); cJSON_Delete(pRoot); return NULL; } pStrProto = cJSON_Print(pRoot); dzlog_debug("Create: %s\n", pStrProto); cJSON_Delete(pRoot); return pStrProto; }