main.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  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. // printf("str_run_add %s\n", str_run_add);
  104. unsigned int run_add = strtoull(str_run_add, NULL, 16);
  105. printf("input_file_path %s\n", input_file_path);
  106. printf("symmetric_enc_typ %u\n", symmetric_enc_typ);
  107. printf("asymmetric_enc_typ %u\n", asymmetric_enc_typ);
  108. printf("comp_typ %u\n", comp_typ);
  109. printf("output_file_path %s\n", output_file_path);
  110. printf("protect type %u\n", protect_type);
  111. printf("puf_path %s\n", puf_path);
  112. printf("mac_enable %u\n", mac_enable);
  113. printf("mac_path %s\n", mac_path);
  114. input_file = fopen(input_file_path, "rb");
  115. if (input_file == NULL) {
  116. printf("unable to open file.\n");
  117. return 1;
  118. }
  119. // 获取文件大小
  120. fseek(input_file, 0, SEEK_END);
  121. uint32_t initial_file_size = ftell(input_file);
  122. printf("initial file size:%u\n", initial_file_size);
  123. rewind(input_file);
  124. /**
  125. * DES: 64bit 1 key_length 8
  126. * AES: 128bit 2 key_length 32
  127. * 3DES: 64bit 3 key_length 24
  128. * RC4: 256bit 4 key_length 32
  129. */
  130. int symmetric_map[5] = {0, 4, 1, 3, 2};
  131. symmetric_enc_typ = symmetric_map[symmetric_enc_typ];
  132. uint8_t input_length, key_length;
  133. if (symmetric_enc_typ == 1) input_length = 8, key_length = 8;
  134. else if (symmetric_enc_typ == 2) input_length = 16, key_length = 32;
  135. else if (symmetric_enc_typ == 3) input_length = 8, key_length = 24;
  136. else if (symmetric_enc_typ == 4) input_length = 1, key_length = 32;
  137. else input_length = 0, key_length = 0;
  138. // 分配足够的内存来存储文件内容
  139. uint8_t *byte_array = (uint8_t *) malloc(initial_file_size * sizeof(uint8_t));
  140. if (byte_array == NULL) {
  141. printf("unable to allocate memory.\n");
  142. return 0;
  143. }
  144. // 读取文件内容到字节数组
  145. int num_elements = fread(byte_array, sizeof(uint8_t), initial_file_size, input_file);
  146. if (num_elements != initial_file_size) {
  147. printf("an error occurred while reading the file.\n");
  148. return 0;
  149. }
  150. fclose(input_file);
  151. const int serial_length = 39;
  152. unsigned char puf_key[serial_length];
  153. memset(puf_key, 0, serial_length);
  154. unsigned char puf_value[serial_length+2];
  155. memset(puf_value, 0, serial_length);
  156. if (protect_type == 1) {
  157. printf("[STATE] node:1 ; message:PUF交互\n");
  158. FILE *file = fopen(puf_path, "r");
  159. if (file == NULL) {
  160. perror("Failed to open file");
  161. return EXIT_FAILURE;
  162. }
  163. char line1[256];
  164. char line2[256];
  165. char line3[256];
  166. // 读取第一行
  167. if (fgets(line1, sizeof(line1), file) == NULL) {
  168. perror("Failed to read line 1");
  169. fclose(file);
  170. return EXIT_FAILURE;
  171. }
  172. // 读取第二行
  173. if (fgets(line2, sizeof(line2), file) == NULL) {
  174. perror("Failed to read line 2");
  175. fclose(file);
  176. return EXIT_FAILURE;
  177. }
  178. // 读取第三行
  179. if (fgets(line3, sizeof(line3), file) == NULL) {
  180. perror("Failed to read line 3");
  181. fclose(file);
  182. return EXIT_FAILURE;
  183. }
  184. // 打印读取的内容
  185. printf("Line 1: %s", line1);
  186. printf("Line 2: %s", line2);
  187. printf("Line 3: %s\n", line3);
  188. // 关闭文件
  189. fclose(file);
  190. // 转换字符串为字节数组
  191. int convertedCount2 = hexStringToByteArray(line2, puf_key, serial_length);
  192. int convertedCount3 = hexStringToByteArray(line3, puf_value, serial_length);
  193. for (int i = 0; i < 39; i++) {
  194. printf("0x%02x,", puf_value[i]);
  195. }
  196. printf("\n");
  197. // 检查转换的结果
  198. if (convertedCount2 != serial_length || convertedCount3 != serial_length) {
  199. printf("Conversion error\n");
  200. return EXIT_FAILURE;
  201. }
  202. }
  203. printf("[STATE] node:2 ; message:获取密钥\n");
  204. uint8_t module_key[32] = {0};
  205. if (protect_type == 1){
  206. replaceWithMiddleEight(puf_value, 41);
  207. memcpy(module_key, puf_value + 4, 32);
  208. }
  209. else {
  210. get_random_bytes(module_key, 32);
  211. }
  212. printf("module key:\n");
  213. for (int i = 0; i < 32; i++) {
  214. printf("%02x ", module_key[i]);
  215. }
  216. printf("\n");
  217. uint8_t mac_nums = 0;
  218. unsigned char mac_array[10][18];
  219. memset(mac_array, 0, 180);
  220. if (mac_enable == 1) {
  221. // 从本地文件中读取MAC地址
  222. int mac_fd = open(mac_path, O_RDONLY);
  223. if (mac_fd <= 0) {
  224. printf("mac_fd : %d\n", mac_fd);
  225. printf("本地未找到MAC地址列表文件\n");
  226. return -1;
  227. }
  228. while (mac_nums < 10 && (read(mac_fd, mac_array[mac_nums], 18) > 0)) {
  229. mac_nums++;
  230. }
  231. close(mac_fd);
  232. } else {
  233. mac_array[0][0] = 'P';
  234. }
  235. int comp_map[6] = {0, 3, 1, 2, 4, 5};
  236. comp_typ = comp_map[comp_typ];
  237. unsigned long compressed_file_size;
  238. uint8_t *compress_out = (uint8_t *) calloc(initial_file_size, sizeof(uint8_t));
  239. int r = -1;
  240. if (comp_typ == 1) {
  241. printf("compress with lzo...\n");
  242. r = lzo1x_1_compress(byte_array, initial_file_size, compress_out, reinterpret_cast<lzo_uint *>(&compressed_file_size), wrkmem);
  243. } else if (comp_typ == 2) {
  244. printf("compress with ucl...\n");
  245. int level = 2;
  246. r = ucl_nrv2b_99_compress(byte_array, initial_file_size, compress_out,
  247. reinterpret_cast<ucl_uint *>(&compressed_file_size), NULL, level, NULL, NULL);
  248. compressed_file_size = reinterpret_cast<unsigned long>(compressed_file_size);
  249. } else if (comp_typ == 3) {
  250. printf("compress with lzma...\n");
  251. compressed_file_size = initial_file_size;
  252. r = tinyLzmaCompress(byte_array, initial_file_size, compress_out,
  253. reinterpret_cast<size_t *>(&compressed_file_size));
  254. compressed_file_size = reinterpret_cast<unsigned long>(compressed_file_size);
  255. } else if (comp_typ == 4) {
  256. printf("compress with zstd...\n");
  257. compressed_file_size = ZSTD_compressBound(initial_file_size);
  258. printf("%d\n", compressed_file_size);
  259. compressed_file_size = ZSTD_compress(compress_out, compressed_file_size, byte_array, initial_file_size, 2);
  260. } else if (comp_typ == 5) {
  261. printf("compress with lz4...\n");
  262. int max_dst_size = LZ4_compressBound(initial_file_size);
  263. compressed_file_size = LZ4_compress_default(byte_array, compress_out, initial_file_size, max_dst_size);
  264. }
  265. if (r == 0 || r == -1) {
  266. printf("compressed %u bytes into %u bytes\n", initial_file_size, compressed_file_size);
  267. printf("[STATE] node: 6 ; message:整体压缩\n");
  268. } else {
  269. /* this should NEVER happen */
  270. printf("internal error - compression failed: %d\n", r);
  271. return 2;
  272. }
  273. /* check for an incompressible block */
  274. if ((unsigned int) compressed_file_size >= initial_file_size) {
  275. printf("This block contains incompressible data.\n");
  276. return 0;
  277. }
  278. uint8_t *new_compress_out = (uint8_t *) realloc(compress_out, compressed_file_size);
  279. if (new_compress_out != NULL) {
  280. compress_out = new_compress_out;
  281. }
  282. uint8_t key[key_length];
  283. for (int i = 0; i < key_length; i++) key[i] = module_key[i];
  284. printf("key:\n");
  285. for (int i = 0; i < key_length; i++) {
  286. printf("%02x ", key[i]);
  287. }
  288. printf("\n");
  289. uint32_t encrypted_file_size = (compressed_file_size + input_length - 1) / input_length * input_length;
  290. printf("encrypted_file_size %u\n", encrypted_file_size);
  291. printf("compress bytes:\n");
  292. for (int i = 0; i < 8; i++) {
  293. printf("%02x ", compress_out[i]);
  294. }
  295. printf("\n");
  296. uint8_t *buff = (uint8_t *) malloc(encrypted_file_size * sizeof(uint8_t));
  297. if (symmetric_enc_typ == 1) {
  298. printf("enc_typ = 1\n");
  299. DesContext des_context;
  300. desInit(&des_context, key, key_length);
  301. for (int i = 0; i < encrypted_file_size; i += input_length)
  302. desEncryptBlock(&des_context, compress_out + i, buff + i);
  303. }
  304. if (symmetric_enc_typ == 2) {
  305. printf("enc_typ = 2\n");
  306. AesContext aes_context;
  307. aesInit(&aes_context, key, key_length);
  308. for (int i = 0; i < encrypted_file_size; i += input_length)
  309. aesEncryptBlock(&aes_context, compress_out + i, buff + i);
  310. }
  311. if (symmetric_enc_typ == 3) {
  312. printf("enc_typ = 3\n");
  313. Des3Context des3_context;
  314. des3Init(&des3_context, key, key_length);
  315. for (int i = 0; i < encrypted_file_size; i += input_length)
  316. des3EncryptBlock(&des3_context, compress_out + i, buff + i);
  317. }
  318. if (symmetric_enc_typ == 4) {
  319. printf("enc_typ = 4\n");
  320. rc4_encryption(compress_out, encrypted_file_size, key, key_length);
  321. memcpy(buff, compress_out, encrypted_file_size);
  322. }
  323. printf("final bytes:\n");
  324. for (int i = 0; i < 8; i++) {
  325. printf("%02x ", buff[i]);
  326. }
  327. printf("\n");
  328. for (int i = encrypted_file_size - 8; i < encrypted_file_size; i++) {
  329. printf("%02x ", buff[i]);
  330. }
  331. printf("\n");
  332. printf("[STATE] node: 4 ; message:整体加密\n");
  333. // uint8_t *tmp_encrypted = NULL;
  334. uint8_t *encrypted = NULL;
  335. // uint32_t encrypted_key_size = sizeof key * sizeof(long long);
  336. uint32_t encrypted_key_size = key_length;
  337. // 如果是软硬结合,加密的key为PUF激励长度39字节
  338. if (protect_type == 1) encrypted_key_size = 39;
  339. /**
  340. * rsa key
  341. */
  342. struct public_key_class pub[1];
  343. struct private_key_class priv[1];
  344. /**
  345. * ecc key
  346. */
  347. uint8_t pub_key[ECC_KEYSIZE];
  348. uint8_t prv_key[ECC_KEYSIZE];
  349. if (asymmetric_enc_typ != 0) {
  350. if (asymmetric_enc_typ == 5) {
  351. rsa_gen_keys(pub, priv);
  352. encrypted_key_size *= 8;
  353. printf("Private Key:\n Modulus: %lld\n Exponent: %lld\n", (long long) priv->modulus, (long long) priv->exponent);
  354. printf("Public Key:\n Modulus: %lld\n Exponent: %lld\n", (long long) pub->modulus, (long long) pub->exponent);
  355. // 1是软硬结合,加密的是激励
  356. // 0是软加密,加密的是秘钥
  357. if (protect_type == 1) encrypted = rsa_encrypt(puf_key, 39, pub);
  358. else if (protect_type == 0) encrypted = rsa_encrypt(key, key_length, pub);
  359. // encrypted = (uint8_t *) tmp_encrypted;
  360. if (encrypted == NULL) {
  361. fprintf(stderr, "error in encryption!\n");
  362. return 1;
  363. }
  364. } else if (asymmetric_enc_typ == 6) {
  365. printf("enc with ecc\n");
  366. ecc_init_keys(pub_key, prv_key);
  367. printf("ecc init end\n");
  368. // 1是软硬结合,加密的是激励,申请的空间是39
  369. // 0是软加密,加密的是秘钥,申请的空间是sizeof key
  370. if (protect_type == 0) {
  371. encrypted = (uint8_t *) realloc(encrypted, sizeof key);
  372. ecc_encrypt(pub_key, key, key_length, encrypted, &encrypted_key_size);
  373. } else if (protect_type == 1) {
  374. encrypted = (uint8_t *) realloc(encrypted, 39);
  375. ecc_encrypt(pub_key, puf_key, 39, encrypted, &encrypted_key_size);
  376. }
  377. printf("encrypted_key_size is %u with ecc\n", encrypted_key_size);
  378. }
  379. }
  380. printf("enc key\n");
  381. for (int i = 0; i < encrypted_key_size; i++) {
  382. printf("0x%02x, ", encrypted[i]);
  383. }
  384. printf("\n");
  385. /**
  386. * enc_typ 1B
  387. * comp_typ 1B
  388. * initial_file_size 4B
  389. * compressed_file_size 4B
  390. * encrypted_file_size 4B
  391. */
  392. printf("uint8_t symmetric_enc_typ: %u\n", symmetric_enc_typ);
  393. printf("uint8_t asymmetric_enc_typ: %u\n", asymmetric_enc_typ);
  394. printf("uint8_t comp_typ: %u\n", comp_typ);
  395. printf("uint32_t file_size: %u\n", initial_file_size);
  396. printf("uint32_t compressed_file_size: %u\n", compressed_file_size);
  397. printf("uint32_t encrypted_file_size: %u\n", encrypted_file_size);
  398. printf("uint8_t input_length: %u\n", input_length);
  399. printf("uint8_t key_length: %u\n", key_length);
  400. uint8_t magic[MAGIC_LENGTH];
  401. // 将各个字段的值存入 magic 数组
  402. magic[SYMMETRIC_ENC_TYP_OFFSET] = symmetric_enc_typ;
  403. magic[ASYMMETRIC_ENC_TYP_OFFSET] = asymmetric_enc_typ;
  404. magic[COMP_TYP_OFFSET] = comp_typ;
  405. memcpy(magic + INITIAL_FILE_SIZE_OFFSET, &initial_file_size, sizeof(uint32_t));
  406. memcpy(magic + COMPRESSED_FILE_SIZE_OFFSET, &compressed_file_size, sizeof(uint32_t));
  407. memcpy(magic + ENCRYPTED_FILE_SIZE_OFFSET, &encrypted_file_size, sizeof(uint32_t));
  408. memcpy(magic + ENCRYPTED_KEY_SIZE_OFFSET, &encrypted_key_size, sizeof(uint32_t));
  409. // 保护类型
  410. memcpy(magic + PROTECT_TYPE_OFFSET, &protect_type, sizeof(uint8_t));
  411. // MAC地址绑定的数量
  412. memcpy(magic + MAC_NUMS_OFFSET, &mac_nums, sizeof(uint8_t));
  413. // 运行地址
  414. printf("str_run_add %x\n", run_add);
  415. memcpy(magic + RUN_ADD_OFFSET, &run_add, 4);
  416. FILE *p = fopen(output_file_path, "wb");
  417. if (p == NULL) {
  418. printf("open filed\n");
  419. }
  420. fwrite(magic, sizeof(uint8_t), MAGIC_LENGTH, p);
  421. fwrite(buff, sizeof(uint8_t), encrypted_file_size, p);
  422. fwrite(encrypted, sizeof(uint8_t), encrypted_key_size, p);
  423. if (asymmetric_enc_typ == 5) {
  424. fwrite(pub, sizeof(struct public_key_class), 1, p);
  425. fwrite(priv, sizeof(struct private_key_class), 1, p);
  426. } else if (asymmetric_enc_typ == 6) {
  427. fwrite(pub_key, sizeof(uint8_t), ECC_KEYSIZE, p);
  428. fwrite(prv_key, sizeof(uint8_t), ECC_KEYSIZE, p);
  429. }
  430. for (int i = 0; i < mac_nums; i++) {
  431. for (int j = 0; j < 18; j++) {
  432. printf("%02x ", mac_array[i][j]);
  433. }
  434. printf("\n");
  435. }
  436. for (int i = 0; i < mac_nums; i++) fwrite(mac_array[i], sizeof(uint8_t), 18, p);
  437. printf("[STATE] node: 7 ; message:加壳\n");
  438. fclose(p);
  439. free(byte_array);
  440. free(buff);
  441. printf("[STATE] node: 8 ; message:成功\n");
  442. printf("成功\n");
  443. return 0;
  444. }
  445. /**
  446. * magic
  447. * encrypted_file
  448. * enc_key/enc serial_challenge
  449. * pub_key
  450. * prv_key
  451. * mac_info[0-10]
  452. */