2025/5/15 整合激活/登录(解码错误,未关VC)
authorazao <821478748@qq.com>
Thu, 15 May 2025 10:48:52 +0000 (18:48 +0800)
committerazao <821478748@qq.com>
Thu, 15 May 2025 10:48:52 +0000 (18:48 +0800)
2.code/aicos/app/AI_AMP_2_5/dev_authentication.c

index d83f70c..341c8b9 100644 (file)
 #include "mbedtls/aes.h"
 #include "mbedtls/cipher.h"
 #include "dev_authentication.h"
+#include "aic_http_comm.h"
+
 #define kb_malloc aic_malloc
 #define bk_free aic_free
 // static char * dev_key = "uKLrChwrxA1LklgBc3VwawYjUkbT3BgX" ;
 // static char * dev_pid = "cqxJZi5CNgzjS3mX21Zw";
 static char aut_token[50] ={0};
-
+int str_count(char *data,char type)
+{
+    int ret = 0;
+    //int count = 0;
+    while(1)
+    {
+        if(data[ret] == type)
+            break;
+        ret++;
+        if(ret>65532)
+            return 0;
+    }
+    return ret;
+}
 void ase_encrypt_dome(void);
 //激活用的md5签名
-static int active_md5_sign(const char *dev_id,const char *pid,const char *timestamp,const char *productSecret,char*md5_str)
+int active_md5_sign(const char *dev_id,const char *pid,const char *timestamp,const char *productSecret,char*md5_str)
 {
     if(strlen(dev_id)>256)
         return -1;
@@ -91,7 +106,7 @@ void active_md5_sign_demo(void)
     char md5_buf[33]={0};
     active_md5_sign(dev_id,pid,timestamp,productSecret,md5_buf);
     bk_printf("md5_buf:%s",md5_buf);
-    ase_encrypt_dome();
+    ase_encrypt_demo();
 }
 #define AES_BLOCK_SIZE 16
 // PKCS5填充
@@ -123,7 +138,7 @@ int aes_cbc_pkcs5_encrypt(const char *input,int input_len,const char* str_key,co
     int ret;
     unsigned char *aes_data =NULL;
     unsigned char *padded_plaintext=NULL;
-    size_t aes_data_len = 0;
+    u32 aes_data_len = 0;
     // 初始化上下文
     mbedtls_cipher_init(&ctx);
 
@@ -148,7 +163,7 @@ int aes_cbc_pkcs5_encrypt(const char *input,int input_len,const char* str_key,co
     }
     //bk_printf("aes_cbc_pkcs5_encrypt2");
     // 计算填充后的长度
-    size_t padded_len = input_len;
+    u32 padded_len = input_len;
     if (padded_len % AES_BLOCK_SIZE != 0) {
         padded_len += AES_BLOCK_SIZE - (padded_len % AES_BLOCK_SIZE);
     }else
@@ -179,12 +194,12 @@ int aes_cbc_pkcs5_encrypt(const char *input,int input_len,const char* str_key,co
         
         goto exit;
     }
-    //bk_printf("aes_cbc_pkcs5_encrypt7");
+    bk_printf("aes_cbc_pkcs5_encrypt7");
     mbedtls_base64_encode(Base64_output, *Base64_output_len, Base64_output_len, aes_data, aes_data_len);
     Base64_output[*Base64_output_len] = 0;
-    //bk_printf("aes_cbc_pkcs5_encrypt8.");
+    bk_printf("aes_cbc_pkcs5_encrypt8.");
     bk_free(padded_plaintext);
-    //bk_printf("aes_cbc_pkcs5_encrypt9");
+    bk_printf("aes_cbc_pkcs5_encrypt9");
     bk_free(aes_data);
     
     // 清理上下文
@@ -206,19 +221,19 @@ int aes_cbc_pkcs5_decrypt(const char *Base64_str_input,const char* str_key,const
     // const unsigned char *ciphertext, size_t ciphertext_len,
     // unsigned char *plaintext, size_t *plaintext_len) 
 {
-    mbedtls_cipher_context_t ctx;
+    mbedtls_cipher_context_t ctx = {0};
     int ret;
     char *input_buf = NULL;
     // 初始化上下文
     mbedtls_cipher_init(&ctx);
-
+    bk_printf("aes_cbc_pkcs5_decrypt str_key:%s,str_iv:%s!!!!!!!!!!!!!!!!!!!!!!!!", str_key,str_iv);
     // 设置加密算法
     ret = mbedtls_cipher_setup(&ctx, mbedtls_cipher_info_from_type(MBEDTLS_CIPHER_AES_256_CBC));
     if (ret != 0) {
         bk_printf("mbedtls_cipher_setup failed: -0x%04x\n", -ret);
         goto exit;
     }
-
+    
     // 设置密钥和IV
     ret = mbedtls_cipher_setkey(&ctx, str_key, strlen(str_key) * 8, MBEDTLS_DECRYPT);
     if (ret != 0) {
@@ -234,7 +249,10 @@ int aes_cbc_pkcs5_decrypt(const char *Base64_str_input,const char* str_key,const
     size_t input_buf_len = strlen(Base64_str_input)+1;
     input_buf = kb_malloc(input_buf_len);
     memset(input_buf,0,input_buf_len);
+    bk_printf("mbedtls_base64_decode1:input_buf_len:%d,Base64_str_input:%s",input_buf_len,Base64_str_input);
     mbedtls_base64_decode(input_buf, input_buf_len, &input_buf_len, Base64_str_input, strlen(Base64_str_input));
+    bk_printf("mbedtls_base64_decode2:input_buf_len:%d,output_len:%d",input_buf_len,*output_len);
+    bk_print_hex(input_buf,input_buf_len);
     // 解密
     ret = mbedtls_cipher_update(&ctx, input_buf, input_buf_len, output, output_len);
     if (ret != 0) {
@@ -244,7 +262,7 @@ int aes_cbc_pkcs5_decrypt(const char *Base64_str_input,const char* str_key,const
 
     // 清理上下文
     mbedtls_cipher_free(&ctx);
-
+    bk_printf("aes_cbc_pkcs5_decrypt output_len:%d output:%s",*output_len,output);
     // 移除填充
     *output_len = pkcs5_unpadding(output, *output_len,AES_BLOCK_SIZE);
     output[*output_len] = 0;
@@ -259,7 +277,7 @@ int aes_cbc_pkcs5_decrypt(const char *Base64_str_input,const char* str_key,const
     return ret;
 }
 
-void ase_encrypt_dome(void)
+void ase_encrypt_demo(void)
 {
     const char *data = "11111111222222223333333344444444";
     size_t  Base64_data_len = strlen(data)*3+32;
@@ -297,18 +315,343 @@ int get_token(char *token)
     return 0;
         
 }
+int32_t SHA1_BLOCK_SIZE = 64;
+int32_t PAD_BLOCK_SIZE = 16;
+int32_t dev_res_timerCount = 0;
+int32_t ud_token_timer_Count = 0;
+int32_t res_error_count = 0;
+int32_t ntptime_flag = 0;
+//激活
+u8 aut_buf[1024];
+// http创建客户端句柄
+u32 http_demo_handle;
+// 设备激活
+char dev_pass_base64[100] ={0};
+char dev_pass[100] ={0};
+char enc_iv[100] = {0};
+char *dev_token = NULL; // token令牌
+char buff[1024];
+//激活->登录的密钥
+const char * key = "uKLrChwrxA1LklgBc3VwawYjUkbT3BgX" ;
+//每小时更新登录一次的更新定时器
+static aos_timer_ptr LOGIN_1H_timer = NULL;
+
 void aut_active(void)//设备激活
 {
+    int ret;
+    bk_printf("aut_active");
+    AIC_HTTPS_CLIENT_INSTANCE *http_client;
+    char deviceId[20] = {0};
+    aic_srv_tele_radio_get_current_slot_imei_sync(deviceId);
+        time_t timestamp;
+        timestamp = time(NULL);
+        bk_printf("2时间戳: %ld\n", (long)timestamp);
+        long long timestamp_ms = (long long)timestamp * 1000;
+    char timestamp_str[20] ={0};
+
+    // 使用 sprintf 将 long long 类型的时间戳转换为字符串
+    ret = sprintf(timestamp_str, "%lld", timestamp_ms);
+    timestamp_str[ret] =0;
+    // 打印转换后的字符串形式的时间戳
+    bk_printf("2时间戳(ms 转换为字符串): %s\n", timestamp_str);
+    const char *dev_pid = "cqxJZi5CNgzjS3mX21Zw";//PID
+    const char *dev_key = "uKLrChwrxA1LklgBc3VwawYjUkbT3BgX";//密钥
 
+    char md5_buf[33]={0};
+    active_md5_sign(deviceId,dev_pid,timestamp_str,dev_key,md5_buf);
+    bk_printf("md5_buf:%s",md5_buf);
+
+    const char *signMethod ="MD5";
+
+    //创建客户端实例
+    http_demo_handle = aic_https_client_create("HTTP_DEMO_CLIENT_NAME");
+    if (http_demo_handle == 0) {
+        bk_printf("Failed to create HTTP client instance\n");
+        return;
+    }
+    alog_info("http demo start");
+    //登陆数据
+    ulong total_bytes = 100;
+    bk_printf("dev_id:%s timestamp:%s ",deviceId,timestamp_str);
+    char *sign_url = "http://dmp.raisound.com/bz-api/dev/auth/active";
+
+    int response_result = 1;
+    u32 response = 0;
+    http_demo_handle = aic_http_client_create("HTTP_DEMO_CLIENT_NAME");
+    int url_value = aic_process_https_url(http_demo_handle,sign_url,AIC_HTTP_HEAD);               
+    bk_printf("url_value:%d",url_value);      
+    http_client = (AIC_HTTPS_CLIENT_INSTANCE *)http_demo_handle;
+    http_client->login_info.server_port = 80;
+    aic_http_client_connect(http_demo_handle, 5000);
+        
+     // 创建JSON对象
+     cJSON *root = cJSON_CreateObject();
+     if (root == NULL) {
+        bk_printf(stderr, "Failed to create JSON object\n");
+         return ;
+     }
+ 
+     // 添加字段
+     cJSON_AddStringToObject(root, "deviceId", deviceId);
+     cJSON_AddStringToObject(root, "pid", dev_pid);
+     cJSON_AddStringToObject(root, "sign", md5_buf);
+     cJSON_AddStringToObject(root, "timeStamp", timestamp_str);
+     cJSON_AddStringToObject(root, "signMethod", signMethod);
+ 
+     // 生成JSON字符串
+     char *json_string = cJSON_Print(root);
+     if (json_string == NULL) {
+        bk_printf(stderr, "Failed to print JSON\n");
+         cJSON_Delete(root);
+         return ;
+     }
+ 
+     // 输出JSON
+     bk_printf("JSON output: %s\n", json_string);
+     aic_https_client_request_initialize(http_demo_handle,AIC_HTTPS_METHOD_PUT, strlen(json_string),
+        0, NULL,NULL, 10000);
+    aic_https_client_request_header_add(http_demo_handle,"Content-Type",strlen("Content-Type"),"application/json",strlen("application/json"),10000);//添加头
+    bk_printf("aic_https_client_request_header_add");
+    response = nx_web_http_client_request_send(http_client->https_client,10 * 1000);
+    http_client->https_client->nx_web_http_client_state = NX_WEB_HTTP_CLIENT_STATE_PUT;
+      ret = aic_https_client_put_data(http_demo_handle, json_string, strlen(json_string),
+        1000);
+        if (ret == 0) {
+            bk_printf("数据发送成功\n");
+
+        } else {
+            // 处理错误
+            bk_printf("数据发送失败,错误码: %d\n", ret);
+        }
+        memset(aut_buf , 0,sizeof(aut_buf));
+        aic_https_client_response_data_get(http_demo_handle,aut_buf,sizeof(aut_buf),1000);
+      
+        bk_printf("http put data :%s",aut_buf);
+        char *str_tmp = NULL;
+        str_tmp = strstr(aut_buf,"\"password\":\"");
+        //bk_printf("str_tmp:%p",str_tmp);
+        if(str_tmp)//解析password
+        {
+            str_tmp += strlen("\"password\":\"");
+            int count = str_count(str_tmp,'\"');
+            bk_printf("count:%d",count);
+            if(count < sizeof(dev_pass_base64))
+            {
+                memcpy(dev_pass_base64,str_tmp,count);
+                dev_pass_base64[count] = 0;
+                bk_printf("dev_pass_base64:%s",dev_pass_base64);
+                
+            }else
+            {
+                bk_printf("激活获取base64失败");
+            }
+        }
+        str_tmp = NULL;
+        str_tmp = strstr(aut_buf,"\"nonce\":\"");
+        if(str_tmp)//nonce
+        {
+            str_tmp += strlen("\"nonce\":\"");
+            int count = str_count(str_tmp,'\"');
+            if(count < sizeof(enc_iv))
+            {
+                memcpy(enc_iv,str_tmp,count);
+                enc_iv[count] = 0;
+                bk_printf("nonce:%s",enc_iv);
+                
+            }else
+            {
+                bk_printf("激活获取base64失败");
+            }
+        }
+        int dev_pass_len = sizeof(dev_pass);
+        if(strlen(enc_iv)>8 && strlen(dev_pass_base64)>8)
+        {
+            aes_cbc_pkcs5_decrypt(dev_pass_base64, key, enc_iv,dev_pass,&dev_pass_len);//解密
+            dev_pass[dev_pass_len] = 0;
+            bk_printf("dev_pass:%s dev_pass_len:%d",dev_pass,dev_pass_len);
+        }
+        
+     // 释放内存
+     free(json_string);
+     cJSON_Delete(root);
+     aic_http_client_delete(http_demo_handle);
 }
 void aut_login(void)//登录
 {
+    bk_printf("dev_sign_in 1");
+    char *token = dev_token; // 中间变量 处理变化的token值
+    AIC_HTTPS_CLIENT_INSTANCE *http_client;
+    bk_printf("dev_sign_in 2");
+    // int read = fmd_read(password_handle, 0, 1024, dev_pass); // 将密码读到dev_pass
+    // fmd_close(password_handle);//关闭
+    // if (read == 0)
+    //     bk_printf("read OK");
+    // else
+    //     bk_printf("read worse");
+
+    if (token == NULL)
+        token = "";
+    if (sizeof(dev_pass) == 0) // 没有密码
+        return;
+    bk_printf("sign_in PASSWORD OK");
+    // 随机生成16个字符串 设备生成做加密使用
+    //char *random_string= generate_random_string(); // 随机的16个字符串
+    // 设备端进行密码加密
+    /**
+     * password, productSecret, nonce utJMIAPRN1E81DzSDVigh/f0ZmHQdBgdAGZ/DhkPJ/s=   uKLrChwrxA1LklgBc3VwawYjUkbT3BgX   qgofeplofqeoadha
+     */
+    char encrypt_data[400] = {0};
+    int encrypt_data_len = sizeof(encrypt_data);
+    
+
+
+    // 登录数据
+    char deviceId[20] = {0};
+    aic_srv_tele_radio_get_current_slot_imei_sync(deviceId);
+    time_t timestamp;
+        timestamp = time(NULL);
+        bk_printf("2时间戳: %ld\n", (long)timestamp);
+        long long timestamp_ms = (long long)timestamp * 1000;
+    char timestamp_str[20] ={0};
+
+    // 使用 sprintf 将 long long 类型的时间戳转换为字符串
+    sprintf(timestamp_str, "%lld", timestamp_ms);
+    memset(enc_iv,'1',16);
+    memcpy(enc_iv,timestamp_str,strlen(timestamp_str));
+    enc_iv[16] = 0;
+    aes_cbc_pkcs5_encrypt(dev_pass, strlen(dev_pass), key, enc_iv,encrypt_data,&encrypt_data_len);//加密
+    
+    bk_printf("deviceId:%s password:%s nonce:%s,dev_pass:%s", deviceId, encrypt_data, enc_iv,dev_pass);
+    char *sign_url = "http://dmp.raisound.com/bz-api/dev/auth/sign_in"; // 登录地址
+    char *headers_T = "\"Content-Type\":\"application/json\"";
+    int response_result = 1;
+    u32 response = 0;
+    http_demo_handle = aic_http_client_create("HTTP_DEMO_CLIENT_NAME");
+    int url_value = aic_process_https_url(http_demo_handle,sign_url,AIC_HTTP_HEAD);               
+    bk_printf("url_value:%d",url_value);      
+    http_client = (AIC_HTTPS_CLIENT_INSTANCE *)http_demo_handle;
+    http_client->login_info.server_port = 80;
+    aic_http_client_connect(http_demo_handle,5000);
+        //这里需要发送数据
+    // 创建JSON对象
+    cJSON *root = cJSON_CreateObject();
+    if (root == NULL) 
+    {
+      bk_printf("Failed to create JSON object\n");
+      return ;
+    }
+    // 添加字段
+    cJSON_AddStringToObject(root, "deviceId", deviceId);
+    cJSON_AddStringToObject(root, "password", encrypt_data);
+    cJSON_AddStringToObject(root, "nonce", enc_iv);
+    // 生成JSON字符串
+    char *json_string = cJSON_Print(root);
+    if (json_string == NULL) 
+    {
+        bk_printf( "Failed to print JSON\n");
+        cJSON_Delete(root);
+        return ;
+    }
+    bk_printf("json_string:%s",json_string);
+    aic_https_client_request_initialize(http_demo_handle,AIC_HTTPS_METHOD_POST, strlen(json_string),
+        0, NULL,NULL, 10000);
+    aic_https_client_request_header_add(http_demo_handle,"Content-Type",strlen("Content-Type"),"application/json",strlen("application/json"),10000);//添加头
+    bk_printf("aic_https_client_request_header_add");
+    // response = aic_http_client_post_start(http_demo_handle, sign_url,
+    //                                       NULL, NULL, 80, NULL,10 * 1000);
+    response = nx_web_http_client_request_send(http_client->https_client,10 * 1000);
+    http_client->https_client->nx_web_http_client_state = NX_WEB_HTTP_CLIENT_STATE_POST;
+    int flag = aic_https_client_put_data(http_demo_handle,json_string,strlen(json_string),1000);
+    if (flag == 0)
+        bk_printf( "Put_data_OKK");
+    else 
+        bk_printf( "Put_data_FAIL");
+    if (response == 1) // 出现异常
+        response_result = 0;
+    if (response_result == 1)
+    {
+        u32 lbytes = aic_https_client_response_data_get(http_demo_handle, buff, 1024*2,
+            10 * 1024);
+        bk_printf("LOGIN:%s",buff);
+        //[2025-05-13 11:28:45.371] LOGIN:{"success":false,"msg":".","code":50021,"data":null}":"2025-05-13 11:28:44","timestamp":1747106924796}}
+        //接下来需要解析buff
+        // const char *delimiter = "{";
+        // const char *start = strstr(buff, delimiter) + strlen(delimiter);//从buff中截取
+        // if (start == NULL) {
+        //     bk_printf("未找到起始标记\n");
+        //     return ;
+        // }
+        // else
+        //     bk_printf("已找到起始标记\n");
+        // const char *stop = strstr(buff, "}") - strlen("}"); // 截取{}里面的部分
+        // if (stop == NULL) {
+        //     bk_printf("未找到结束标记\n");
+        //     return ;
+        // }
+        // else
+        //     bk_printf("已找到结束标记\n");
+        // if (start != NULL && stop != NULL)
+        // {
+        //     bk_printf("start AND stop is OK!");
+        //     size_t length = stop - start;
+        //     char *data = (char *)malloc(length + 1);
+        //     if (data == NULL)
+        //     {
+        //         bk_printf("data == NULL");
+        //         return NULL;
+        //     }
+        //     strncpy(data, start, length);
+        //     data[length] = '\0';
+        //     bk_printf("data:%s",data);
+        //     if(data != "")
+        //     {      
+        //         if(strstr(data,"status_code")+strlen("status_code\":") == "200")
+        //         {
+        //             if(strstr(data,"success")!= NULL)///在前者里面找后者
+        //             {
+        //                 if(strstr(data,"success")+strlen("success\":") == "True")
+        //                 {
+        //                     if(strstr(data,"data")!= NULL)
+        //                     {
+        //                         char * data_tmp = strstr(data,"data")+strlen("data\":");
+        //                         bk_printf("data_tmp == %s",data_tmp);
+        //                         if(strstr(data_tmp,"token")!= NULL)
+        //                             dev_token = strstr(data_tmp,"token")+strlen("token\":");
+        //                         //释放data内存
+        //                         free(data);
+        //                     }
+        //                 }
 
+        //             }
+                    
+        //             if(strstr(data,"code")+strlen("code") == "50003")
+        //                 ntptime_flag = 0;
+        //         }
+        //     }
+        // }  
+    }
+    // 释放内存
+    free(json_string);
+    cJSON_Delete(root);
+    if (response != NX_SUCCESS)
+    {
+        aic_http_client_delete(http_demo_handle);
+        return;
+    }
 }
 void aut_chack_token(void)//检查token
 {
 
 }
+
+//每小时更新一次登录
+static void LOGIN_1H_timeout(void *param)
+{
+    if (sizeof(dev_pass) == 0)
+        aut_active();//没有密钥走激活
+    //每小时登录一次
+    aut_login();
+}
 static aos_thread_id dev_authentication_id = 0;
 static aos_queue_ptr dev_authentication_task_queue = NULL;
 //鉴权消息发送
@@ -342,6 +685,21 @@ aos_status dev_authentication_MSG_put(const char *data,u32 len,dev_authenticatio
 static void dev_authentication_task(void *thread_input)//鉴权逻辑线程
 {
     dev_authentication_MSG_queue_t dev_authentication_msg = {0};
+    //dev_NTP();//获取时间
+    aut_active();//激活
+    aut_login();//登录
+    if(LOGIN_1H_timeout == NULL)
+    {
+        LOGIN_1H_timer = aos_create_timer("AI_VC_1S_timer",
+            LOGIN_1H_timeout, &LOGIN_1H_timer,
+            1000*60,
+            AOS_AUTO_ACTIVATE, AOS_BE_PERIOD);
+        aic_assert(LOGIN_1H_timer);
+    }
+
+    /**
+     * 原来已激活过了...AuthVo(password=rPbSCNTIVYWKso6I5+6l0KIbSiIembg3p10IEny2UVg=, deviceId=860132061481751, nonce=xiRqXDqkqGFodIiw)
+     */
     while (1) {
         if(dev_authentication_task_queue)
         {