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 106 107 108 109 110 111 112 113 114 115 116 117 118 119
| #include<stdio.h> #include<string.h> #define SBOX_LEN 256 #define rc4_encrypt rc4_crypt #define rc4_decrypt rc4_crypt static inline void swap_uchar(unsigned char *puc_x, unsigned char *puc_y) { *puc_x = *puc_x ^ *puc_y; *puc_y = *puc_x ^ *puc_y; *puc_x = *puc_x ^ *puc_y; } void hexdump(unsigned char *puc_data, int length) { int i = 0; for (i = 0; i < length; i++) { printf("%02X", puc_data[i]); if (i && (i + 1) % 16 == 0) { putchar('\n'); } } printf("\n"); }
static void rc4_ksa(unsigned char *puc_sbox, unsigned char *puc_key, int key_length) { int i = 0; int j = 0; char tmp[SBOX_LEN] = {0}; for (i = 0; i < SBOX_LEN; i++) { puc_sbox[i] = i; tmp[i] = puc_key[i % key_length]; } for (i = 0; i < SBOX_LEN; i++) { j = (j + puc_sbox[i] + tmp[i]) % SBOX_LEN; swap_uchar(&puc_sbox[i], &puc_sbox[j]); } }
static void rc4_prga(unsigned char *puc_sbox, unsigned char *puc_key_stream, unsigned long ul_data_length) { int i = 0; int j = 0; int t = 0; unsigned long k = 0; for (k = 0; k < ul_data_length; k++) { i = (i + 1) % SBOX_LEN; j = (j + puc_sbox[i]) % SBOX_LEN; swap_uchar(&puc_sbox[i], &puc_sbox[j]); t = (puc_sbox[i] + puc_sbox[j]) % SBOX_LEN; puc_key_stream[k] = puc_sbox[t]; } }
void rc4_crypt(unsigned char *puc_data, unsigned char *puc_key_stream, unsigned long ul_data_length) { unsigned long i = 0; for (i = 0; i < ul_data_length; i++) { puc_data[i] ^= puc_key_stream[i]; } } int main(int argc, char *argv[]) { unsigned char sbox[SBOX_LEN] = {0}; char key[SBOX_LEN] = {"HeyGap"}; char data[512] = "HeyGap"; unsigned char puc_keystream[512] = {0}; unsigned long ul_data_length = strlen(data); printf("key=%s, length=%d\n\n", key, strlen(key)); printf("Raw data string:%s\n", data); printf("Raw data hex:\n"); hexdump(data, ul_data_length); rc4_ksa(sbox, (unsigned char *)key, strlen(key)); rc4_prga(sbox, puc_keystream, ul_data_length); printf("S-box final status:\n"); hexdump(sbox, sizeof(sbox)); printf("key stream:\n"); hexdump(puc_keystream, ul_data_length); rc4_encrypt((unsigned char*)data, puc_keystream, ul_data_length); printf("cipher hexdump:\n"); hexdump(data, ul_data_length); rc4_decrypt((unsigned char*)data, puc_keystream, ul_data_length); printf("decypt data:%s\n", data); return 0; }
|