1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105
| #include <stdio.h> #include <string.h> #include <stdlib.h>
void rc4_init(unsigned char* s, unsigned char* key, unsigned long Len_k) { int i = 0, j = 0; unsigned char k[256] = { 0 }; unsigned char tmp = 0; for (i = 0; i < 256; i++) { s[i] = i; k[i] = key[i % Len_k]; } for (i = 0; i < 256; i++) { j = (j + s[i] + k[i]) % 256; tmp = s[i]; s[i] = s[j]; s[j] = tmp; } }
void rc4_crypt(unsigned char* Data, unsigned long Len_D, unsigned char* key, unsigned long Len_k) { unsigned char s[256]; rc4_init(s, key, Len_k); int i = 0, j = 0, t = 0; unsigned long k_idx = 0; unsigned char tmp; for (k_idx = 0; k_idx < Len_D; k_idx++) { i = (i + 1) % 256; j = (j + s[i]) % 256; tmp = s[i]; s[i] = s[j]; s[j] = tmp; t = (s[i] + s[j]) % 256; Data[k_idx] = Data[k_idx] ^ s[t]; } }
int hex2bytes(const char* hex_str, unsigned char* byte_arr, int max_byte_len) { int hex_len = strlen(hex_str); if (hex_len % 2 != 0) { printf("错误:十六进制字符串长度为奇数!\n"); return -1; } int byte_len = hex_len / 2; if (byte_len > max_byte_len) { printf("错误:字节数组缓冲区不足!\n"); return -2; } for (int i = 0; i < byte_len; i++) { sscanf(hex_str + 2 * i, "%2hhx", &byte_arr[i]); } return byte_len; }
int main() { unsigned char key[] = "thisiskey"; unsigned long key_len = sizeof(key) - 1;
const char* hex_cipher = "c5e3effaeb2eca309a749cb8e5d3711909ceb5071b91"; unsigned char cipher_bytes[1024] = {0}; int cipher_len = hex2bytes(hex_cipher, cipher_bytes, sizeof(cipher_bytes)); if (cipher_len < 0) { return -1; }
rc4_crypt(cipher_bytes, cipher_len, key, key_len);
printf("=== 解密结果 ===\n"); printf("UTF-8字符串:"); for (int i = 0; i < cipher_len; i++) { printf("%c", cipher_bytes[i]); } printf("\n");
printf("十六进制形式:"); for (int i = 0; i < cipher_len; i++) { printf("%02x", cipher_bytes[i]); } printf("\n");
return 0; }
|