main.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532
  1. #include <stdlib.h>
  2. #include <time.h>
  3. #include <cstring>
  4. #include <stdio.h>
  5. #include <cstdint>
  6. #include <fcntl.h>
  7. #include <unistd.h>
  8. #include <string>
  9. #include "lzo/minilzo.h"
  10. #include "zstd/zstd.h"
  11. #include "ucl/ucl.h"
  12. #include "lz4/lz4.h"
  13. #include "cipher/aes.h"
  14. #include "cipher/des.h"
  15. #include "cipher/des3.h"
  16. #include "cipher/rc4.h"
  17. #include "cipher/rsa.h"
  18. #include "cipher/ecc.h"
  19. using namespace std;
  20. #ifdef __cplusplus
  21. extern "C" {
  22. #endif
  23. #include "lzma/FileIO.h"
  24. #include "lzma/TinyLzmaCompress.h"
  25. #include "lzma/TinyLzmaDecompress.h"
  26. #ifdef __cplusplus
  27. }
  28. #endif
  29. #define HEAP_ALLOC(var, size) \
  30. lzo_align_t __LZO_MMODEL var [ ((size) + (sizeof(lzo_align_t) - 1)) / sizeof(lzo_align_t) ]
  31. // 定义各个字段的偏移量
  32. #define SYMMETRIC_ENC_TYP_OFFSET 0
  33. #define ASYMMETRIC_ENC_TYP_OFFSET 1
  34. #define COMP_TYP_OFFSET 2
  35. #define INITIAL_FILE_SIZE_OFFSET 3
  36. #define COMPRESSED_FILE_SIZE_OFFSET 7
  37. #define ENCRYPTED_FILE_SIZE_OFFSET 11
  38. #define ENCRYPTED_KEY_SIZE_OFFSET 15
  39. #define PROTECT_TYPE_OFFSET 19
  40. #define MAC_NUMS_OFFSET 20
  41. #define RUN_ADD_OFFSET 21
  42. /**
  43. *
  44. * 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
  45. */
  46. static HEAP_ALLOC(wrkmem, LZO1X_1_MEM_COMPRESS);
  47. const int MAGIC_LENGTH = 32;
  48. static int get_random_bytes(unsigned char *buf, size_t len) {
  49. // FILE *f;
  50. // f = fopen("/dev/urandom", "r");
  51. // fread(buf, len, 1, f);
  52. // fclose(f);
  53. srand((unsigned)time(NULL));
  54. for(int i = 0; i < len; i++) {
  55. buf[i] = rand() % 255;
  56. }
  57. return 0;
  58. }
  59. int hexStringToByteArray(const char *hexString, unsigned char *byteArray, int byteArraySize) {
  60. int count = 0;
  61. const char *pos = hexString;
  62. // 转换16进制字符串为字节数组
  63. while (count < byteArraySize && sscanf(pos, "%2hhx", &byteArray[count]) == 1) {
  64. pos += 2;
  65. count++;
  66. }
  67. return count; // 返回转换的字节数
  68. }
  69. void replaceWithMiddleEight(unsigned char arr[], int length) {
  70. if (length < 8) {
  71. printf("数组长度不足8位\n");
  72. return;
  73. }
  74. // 计算中间8位的起始索引
  75. int start = (length - 8) / 2;
  76. // 提取中间的8个元素
  77. int middleEight[8];
  78. for (int i = 0; i < 8; i++) {
  79. middleEight[i] = arr[start + i];
  80. }
  81. // 用中间的8位替换源数组的内容
  82. for (int i = 0; i < length; i++) {
  83. arr[i] = middleEight[i % 8]; // 循环使用中间的8位
  84. }
  85. }
  86. int main(int argc, char *argv[]) {
  87. FILE *input_file;
  88. char *input_file_path = argv[1];
  89. uint8_t symmetric_enc_typ = (uint8_t) atoi(argv[2]);
  90. uint8_t asymmetric_enc_typ = (uint8_t) atoi(argv[3]);
  91. uint8_t comp_typ = (uint8_t) atoi(argv[4]);
  92. uint8_t cp_symmetric_enc_typ = symmetric_enc_typ;
  93. uint8_t cp_asymmetric_enc_typ = asymmetric_enc_typ;
  94. uint8_t cp_comp_typ = comp_typ;
  95. char *output_file_path = argv[5];
  96. // 保护模式
  97. uint8_t protect_type = (uint8_t) atoi(argv[6]);
  98. char *puf_path = argv[7];
  99. uint8_t mac_enable = (uint8_t) atoi(argv[8]);
  100. char *mac_path = argv[9];
  101. // 运行地址 0xb0000000
  102. char *str_run_add = argv[10];
  103. //如果 arg[10] 为空,则使用默认值0xb0000000
  104. if (str_run_add == NULL) {
  105. str_run_add = "0xb0000000";
  106. }
  107. // printf("str_run_add %s\n", str_run_add);
  108. unsigned int run_add = strtoull(str_run_add, NULL, 16);
  109. printf("input_file_path %s\n", input_file_path);
  110. printf("symmetric_enc_typ %u\n", symmetric_enc_typ);
  111. printf("asymmetric_enc_typ %u\n", asymmetric_enc_typ);
  112. printf("comp_typ %u\n", comp_typ);
  113. printf("output_file_path %s\n", output_file_path);
  114. printf("protect type %u\n", protect_type);
  115. printf("puf_path %s\n", puf_path);
  116. printf("mac_enable %u\n", mac_enable);
  117. printf("mac_path %s\n", mac_path);
  118. printf("run_add %x\n", run_add);
  119. input_file = fopen(input_file_path, "rb");
  120. if (input_file == NULL) {
  121. printf("unable to open file.\n");
  122. return 1;
  123. }
  124. // 获取文件大小
  125. fseek(input_file, 0, SEEK_END);
  126. uint32_t initial_file_size = ftell(input_file);
  127. printf("initial file size:%u\n", initial_file_size);
  128. rewind(input_file);
  129. /**
  130. * DES: 64bit 1 key_length 8
  131. * AES: 128bit 2 key_length 32
  132. * 3DES: 64bit 3 key_length 24
  133. * RC4: 256bit 4 key_length 32
  134. */
  135. int symmetric_map[5] = {0, 4, 1, 3, 2};
  136. symmetric_enc_typ = symmetric_map[symmetric_enc_typ];
  137. uint8_t input_length, key_length;
  138. if (symmetric_enc_typ == 1) input_length = 8, key_length = 8;
  139. else if (symmetric_enc_typ == 2) input_length = 16, key_length = 32;
  140. else if (symmetric_enc_typ == 3) input_length = 8, key_length = 24;
  141. else if (symmetric_enc_typ == 4) input_length = 1, key_length = 32;
  142. else input_length = 0, key_length = 0;
  143. // 分配足够的内存来存储文件内容
  144. uint8_t *byte_array = (uint8_t *) malloc(initial_file_size * sizeof(uint8_t));
  145. if (byte_array == NULL) {
  146. printf("unable to allocate memory.\n");
  147. return 0;
  148. }
  149. // 读取文件内容到字节数组
  150. int num_elements = fread(byte_array, sizeof(uint8_t), initial_file_size, input_file);
  151. if (num_elements != initial_file_size) {
  152. printf("an error occurred while reading the file.\n");
  153. return 0;
  154. }
  155. fclose(input_file);
  156. const int serial_length = 39;
  157. unsigned char puf_key[serial_length];
  158. memset(puf_key, 0, serial_length);
  159. unsigned char puf_value[serial_length+2];
  160. memset(puf_value, 0, serial_length);
  161. if (protect_type == 1) {
  162. printf("[STATE] node:1 ; message:PUF交互\n");
  163. FILE *file = fopen(puf_path, "r");
  164. if (file == NULL) {
  165. perror("Failed to open file");
  166. return EXIT_FAILURE;
  167. }
  168. char line1[256];
  169. char line2[256];
  170. char line3[256];
  171. // 读取第一行
  172. if (fgets(line1, sizeof(line1), file) == NULL) {
  173. perror("Failed to read line 1");
  174. fclose(file);
  175. return EXIT_FAILURE;
  176. }
  177. // 读取第二行
  178. if (fgets(line2, sizeof(line2), file) == NULL) {
  179. perror("Failed to read line 2");
  180. fclose(file);
  181. return EXIT_FAILURE;
  182. }
  183. // 读取第三行
  184. if (fgets(line3, sizeof(line3), file) == NULL) {
  185. perror("Failed to read line 3");
  186. fclose(file);
  187. return EXIT_FAILURE;
  188. }
  189. // 打印读取的内容
  190. printf("Line 1: %s", line1);
  191. printf("Line 2: %s", line2);
  192. printf("Line 3: %s\n", line3);
  193. // 关闭文件
  194. fclose(file);
  195. // 转换字符串为字节数组
  196. int convertedCount2 = hexStringToByteArray(line2, puf_key, serial_length);
  197. int convertedCount3 = hexStringToByteArray(line3, puf_value, serial_length);
  198. for (int i = 0; i < 39; i++) {
  199. printf("0x%02x,", puf_value[i]);
  200. }
  201. printf("\n");
  202. // 检查转换的结果
  203. if (convertedCount2 != serial_length || convertedCount3 != serial_length) {
  204. printf("Conversion error\n");
  205. return EXIT_FAILURE;
  206. }
  207. }
  208. printf("[STATE] node:2 ; message:获取密钥\n");
  209. uint8_t module_key[32] = {0};
  210. if (protect_type == 1){
  211. replaceWithMiddleEight(puf_value, 41);
  212. memcpy(module_key, puf_value + 4, 32);
  213. }
  214. else {
  215. get_random_bytes(module_key, 32);
  216. }
  217. printf("module key:\n");
  218. for (int i = 0; i < 32; i++) {
  219. printf("%02x ", module_key[i]);
  220. }
  221. printf("\n");
  222. uint8_t mac_nums = 0;
  223. unsigned char mac_array[10][18];
  224. memset(mac_array, 0, 180);
  225. if (mac_enable == 1) {
  226. // 从本地文件中读取MAC地址
  227. int mac_fd = open(mac_path, O_RDONLY);
  228. if (mac_fd <= 0) {
  229. printf("mac_fd : %d\n", mac_fd);
  230. printf("本地未找到MAC地址列表文件\n");
  231. return -1;
  232. }
  233. while (mac_nums < 10 && (read(mac_fd, mac_array[mac_nums], 18) > 0)) {
  234. mac_nums++;
  235. }
  236. close(mac_fd);
  237. } else {
  238. mac_array[0][0] = 'P';
  239. }
  240. int comp_map[6] = {0, 3, 1, 2, 4, 5};
  241. comp_typ = comp_map[comp_typ];
  242. unsigned long compressed_file_size;
  243. uint8_t *compress_out = (uint8_t *) calloc(initial_file_size, sizeof(uint8_t));
  244. int r = -1;
  245. if (comp_typ == 1) {
  246. printf("compress with lzo...\n");
  247. r = lzo1x_1_compress(byte_array, initial_file_size, compress_out, reinterpret_cast<lzo_uint *>(&compressed_file_size), wrkmem);
  248. } else if (comp_typ == 2) {
  249. printf("compress with ucl...\n");
  250. int level = 2;
  251. r = ucl_nrv2b_99_compress(byte_array, initial_file_size, compress_out,
  252. reinterpret_cast<ucl_uint *>(&compressed_file_size), NULL, level, NULL, NULL);
  253. compressed_file_size = reinterpret_cast<unsigned long>(compressed_file_size);
  254. } else if (comp_typ == 3) {
  255. printf("compress with lzma...\n");
  256. compressed_file_size = initial_file_size;
  257. r = tinyLzmaCompress(byte_array, initial_file_size, compress_out,
  258. reinterpret_cast<size_t *>(&compressed_file_size));
  259. compressed_file_size = reinterpret_cast<unsigned long>(compressed_file_size);
  260. } else if (comp_typ == 4) {
  261. printf("compress with zstd...\n");
  262. compressed_file_size = ZSTD_compressBound(initial_file_size);
  263. printf("%d\n", compressed_file_size);
  264. compressed_file_size = ZSTD_compress(compress_out, compressed_file_size, byte_array, initial_file_size, 2);
  265. } else if (comp_typ == 5) {
  266. printf("compress with lz4...\n");
  267. int max_dst_size = LZ4_compressBound(initial_file_size);
  268. compressed_file_size = LZ4_compress_default(byte_array, compress_out, initial_file_size, max_dst_size);
  269. }
  270. if (r == 0 || r == -1) {
  271. printf("compressed %u bytes into %u bytes\n", initial_file_size, compressed_file_size);
  272. printf("[STATE] node: 6 ; message:整体压缩\n");
  273. } else {
  274. /* this should NEVER happen */
  275. printf("internal error - compression failed: %d\n", r);
  276. return 2;
  277. }
  278. /* check for an incompressible block */
  279. if ((unsigned int) compressed_file_size >= initial_file_size) {
  280. printf("This block contains incompressible data.\n");
  281. return 0;
  282. }
  283. uint8_t *new_compress_out = (uint8_t *) realloc(compress_out, compressed_file_size);
  284. if (new_compress_out != NULL) {
  285. compress_out = new_compress_out;
  286. }
  287. uint8_t key[key_length];
  288. for (int i = 0; i < key_length; i++) key[i] = module_key[i];
  289. printf("key:\n");
  290. for (int i = 0; i < key_length; i++) {
  291. printf("%02x ", key[i]);
  292. }
  293. printf("\n");
  294. uint32_t encrypted_file_size = (compressed_file_size + input_length - 1) / input_length * input_length;
  295. printf("encrypted_file_size %u\n", encrypted_file_size);
  296. printf("compress bytes:\n");
  297. for (int i = 0; i < 8; i++) {
  298. printf("%02x ", compress_out[i]);
  299. }
  300. printf("\n");
  301. uint8_t *buff = (uint8_t *) malloc(encrypted_file_size * sizeof(uint8_t));
  302. if (symmetric_enc_typ == 1) {
  303. printf("enc_typ = 1\n");
  304. DesContext des_context;
  305. desInit(&des_context, key, key_length);
  306. for (int i = 0; i < encrypted_file_size; i += input_length)
  307. desEncryptBlock(&des_context, compress_out + i, buff + i);
  308. }
  309. if (symmetric_enc_typ == 2) {
  310. printf("enc_typ = 2\n");
  311. AesContext aes_context;
  312. aesInit(&aes_context, key, key_length);
  313. for (int i = 0; i < encrypted_file_size; i += input_length)
  314. aesEncryptBlock(&aes_context, compress_out + i, buff + i);
  315. }
  316. if (symmetric_enc_typ == 3) {
  317. printf("enc_typ = 3\n");
  318. Des3Context des3_context;
  319. des3Init(&des3_context, key, key_length);
  320. for (int i = 0; i < encrypted_file_size; i += input_length)
  321. des3EncryptBlock(&des3_context, compress_out + i, buff + i);
  322. }
  323. if (symmetric_enc_typ == 4) {
  324. printf("enc_typ = 4\n");
  325. rc4_encryption(compress_out, encrypted_file_size, key, key_length);
  326. memcpy(buff, compress_out, encrypted_file_size);
  327. }
  328. printf("final bytes:\n");
  329. for (int i = 0; i < 8; i++) {
  330. printf("%02x ", buff[i]);
  331. }
  332. printf("\n");
  333. for (int i = encrypted_file_size - 8; i < encrypted_file_size; i++) {
  334. printf("%02x ", buff[i]);
  335. }
  336. printf("\n");
  337. printf("[STATE] node: 4 ; message:整体加密\n");
  338. // uint8_t *tmp_encrypted = NULL;
  339. uint8_t *encrypted = NULL;
  340. // uint32_t encrypted_key_size = sizeof key * sizeof(long long);
  341. uint32_t encrypted_key_size = key_length;
  342. // 如果是软硬结合,加密的key为PUF激励长度39字节
  343. if (protect_type == 1) encrypted_key_size = 39;
  344. /**
  345. * rsa key
  346. */
  347. struct public_key_class pub[1];
  348. struct private_key_class priv[1];
  349. /**
  350. * ecc key
  351. */
  352. uint8_t pub_key[ECC_KEYSIZE];
  353. uint8_t prv_key[ECC_KEYSIZE];
  354. if (asymmetric_enc_typ != 0) {
  355. if (asymmetric_enc_typ == 5) {
  356. rsa_gen_keys(pub, priv);
  357. encrypted_key_size *= 8;
  358. printf("Private Key:\n Modulus: %lld\n Exponent: %lld\n", (long long) priv->modulus, (long long) priv->exponent);
  359. printf("Public Key:\n Modulus: %lld\n Exponent: %lld\n", (long long) pub->modulus, (long long) pub->exponent);
  360. // 1是软硬结合,加密的是激励
  361. // 0是软加密,加密的是秘钥
  362. if (protect_type == 1) encrypted = rsa_encrypt(puf_key, 39, pub);
  363. else if (protect_type == 0) encrypted = rsa_encrypt(key, key_length, pub);
  364. // encrypted = (uint8_t *) tmp_encrypted;
  365. if (encrypted == NULL) {
  366. fprintf(stderr, "error in encryption!\n");
  367. return 1;
  368. }
  369. } else if (asymmetric_enc_typ == 6) {
  370. printf("enc with ecc\n");
  371. ecc_init_keys(pub_key, prv_key);
  372. printf("ecc init end\n");
  373. // 1是软硬结合,加密的是激励,申请的空间是39
  374. // 0是软加密,加密的是秘钥,申请的空间是sizeof key
  375. if (protect_type == 0) {
  376. encrypted = (uint8_t *) realloc(encrypted, sizeof key);
  377. ecc_encrypt(pub_key, key, key_length, encrypted, &encrypted_key_size);
  378. } else if (protect_type == 1) {
  379. encrypted = (uint8_t *) realloc(encrypted, 39);
  380. ecc_encrypt(pub_key, puf_key, 39, encrypted, &encrypted_key_size);
  381. }
  382. printf("encrypted_key_size is %u with ecc\n", encrypted_key_size);
  383. }
  384. }
  385. printf("enc key\n");
  386. for (int i = 0; i < encrypted_key_size; i++) {
  387. printf("0x%02x, ", encrypted[i]);
  388. }
  389. printf("\n");
  390. /**
  391. * enc_typ 1B
  392. * comp_typ 1B
  393. * initial_file_size 4B
  394. * compressed_file_size 4B
  395. * encrypted_file_size 4B
  396. */
  397. printf("uint8_t symmetric_enc_typ: %u\n", symmetric_enc_typ);
  398. printf("uint8_t asymmetric_enc_typ: %u\n", asymmetric_enc_typ);
  399. printf("uint8_t comp_typ: %u\n", comp_typ);
  400. printf("uint32_t file_size: %u\n", initial_file_size);
  401. printf("uint32_t compressed_file_size: %u\n", compressed_file_size);
  402. printf("uint32_t encrypted_file_size: %u\n", encrypted_file_size);
  403. printf("uint8_t input_length: %u\n", input_length);
  404. printf("uint8_t key_length: %u\n", key_length);
  405. uint8_t magic[MAGIC_LENGTH];
  406. // 将各个字段的值存入 magic 数组
  407. magic[SYMMETRIC_ENC_TYP_OFFSET] = symmetric_enc_typ;
  408. magic[ASYMMETRIC_ENC_TYP_OFFSET] = asymmetric_enc_typ;
  409. magic[COMP_TYP_OFFSET] = comp_typ;
  410. memcpy(magic + INITIAL_FILE_SIZE_OFFSET, &initial_file_size, sizeof(uint32_t));
  411. memcpy(magic + COMPRESSED_FILE_SIZE_OFFSET, &compressed_file_size, sizeof(uint32_t));
  412. memcpy(magic + ENCRYPTED_FILE_SIZE_OFFSET, &encrypted_file_size, sizeof(uint32_t));
  413. memcpy(magic + ENCRYPTED_KEY_SIZE_OFFSET, &encrypted_key_size, sizeof(uint32_t));
  414. // 保护类型
  415. memcpy(magic + PROTECT_TYPE_OFFSET, &protect_type, sizeof(uint8_t));
  416. // MAC地址绑定的数量
  417. memcpy(magic + MAC_NUMS_OFFSET, &mac_nums, sizeof(uint8_t));
  418. // 运行地址
  419. printf("str_run_add %x\n", run_add);
  420. memcpy(magic + RUN_ADD_OFFSET, &run_add, 4);
  421. FILE *p = fopen(output_file_path, "wb");
  422. if (p == NULL) {
  423. printf("open filed\n");
  424. }
  425. fwrite(magic, sizeof(uint8_t), MAGIC_LENGTH, p);
  426. fwrite(buff, sizeof(uint8_t), encrypted_file_size, p);
  427. fwrite(encrypted, sizeof(uint8_t), encrypted_key_size, p);
  428. if (asymmetric_enc_typ == 5) {
  429. fwrite(pub, sizeof(struct public_key_class), 1, p);
  430. fwrite(priv, sizeof(struct private_key_class), 1, p);
  431. } else if (asymmetric_enc_typ == 6) {
  432. fwrite(pub_key, sizeof(uint8_t), ECC_KEYSIZE, p);
  433. fwrite(prv_key, sizeof(uint8_t), ECC_KEYSIZE, p);
  434. }
  435. for (int i = 0; i < mac_nums; i++) {
  436. for (int j = 0; j < 18; j++) {
  437. printf("%02x ", mac_array[i][j]);
  438. }
  439. printf("\n");
  440. }
  441. for (int i = 0; i < mac_nums; i++) fwrite(mac_array[i], sizeof(uint8_t), 18, p);
  442. printf("[STATE] node: 7 ; message:加壳\n");
  443. fclose(p);
  444. free(byte_array);
  445. free(buff);
  446. printf("[STATE] node: 8 ; message:成功\n");
  447. printf("成功\n");
  448. return 0;
  449. }
  450. /**
  451. * magic
  452. * encrypted_file
  453. * enc_key/enc serial_challenge
  454. * pub_key
  455. * prv_key
  456. * mac_info[0-10]
  457. */