[問題] 請教這個RC4 加密程式的解釋
起源是我在寫一個無線網路連線的程式
但是在Profile的加密部分,我查到WEP是以RC4下去加密的
所以就去找演算法,網站如下
http://120.118.165.46/tsnien/Teach_Manu/F8745/programs/RC4/RC4.c
但很不幸的,小弟是用C#開發的,所以對C的語法很生疏
才來請教鄉民,這個程式的解說
感謝解答
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct {
unsigned int x;
unsigned int y;
unsigned char state[256];
}RC4_CTX;
void RC4_init(RC4_CTX *ctx, const unsigned char *key,
unsigned int key_len);
unsigned int RC4_byte(RC4_CTX *ctx);
void RC4_encrypt(RC4_CTX *ctx, unsigned char *dest,
const unsigned char *src, unsigned int len);
int main(int argc, char **argv) {
int i;
char input[128];
unsigned int key_len, data_len;
unsigned char dest[500], mykey[128], src[500], last[500];
RC4_CTX mycontext;
printf("請輸入 RC4 鑰匙 = ");
scanf("%s", &mykey);
key_len=strlen(mykey);
printf("請輸入明文 =>");
scanf("%s", &src);
data_len=strlen(src);
/* RC4 加密處理程序 */
printf("**** RC4 加密處理 ***\n");
/* Initializate the algorithm */
RC4_init(&mycontext, mykey, key_len);
/* Encrypt 13 bytes of the src string */
RC4_encrypt(&mycontext, dest, src, data_len);
printf("RC4(明文)=");
for(i=0; i<data_len; i++)
printf("%02x ", dest[i]);
printf("\n");
/* RC4 解密處理程序 */
printf("**** RC4 解密處理 ***\n");
/* Initializate the algorithm */
RC4_init(&mycontext, mykey, key_len);
/* Encrypt 13 bytes of the src string */
RC4_encrypt(&mycontext, last, dest, data_len);
printf("RC4(密文)=");
for(i=0; i<data_len; i++)
printf("%c", last[i]);
printf("\n");
return 0;
}
void RC4_init(RC4_CTX *ctx, const unsigned char *key,
unsigned int key_len) {
unsigned int t, u;
unsigned int keyindex;
unsigned int stateindex;
unsigned char *state;
unsigned int counter;
state = ctx->state;
ctx->x = 0;
ctx->y = 0;
for(counter =0; counter<256; counter++)
state[counter] = counter;
keyindex = 0;
stateindex = 0;
for(counter=0; counter<256; counter++) {
t = state[counter];
stateindex = (stateindex + key[keyindex] + t) & 0xff;
u = state[stateindex];
state[stateindex] = t;
state[counter] = u;
if(++keyindex >= key_len)
keyindex = 0;
}
}
unsigned int RC4_byte(RC4_CTX *ctx) {
unsigned int x;
unsigned int y;
unsigned int sx, sy;
unsigned char *state;
state = ctx->state;
x = (ctx->x + 1) &0xff;
sx = state[x];
y = (sx + ctx->y) & 0xff;
sy = state[y];
ctx->x = x;
ctx->y = y;
state[y] = sx;
state[x] = sy;
return state[(sx + sy) & 0xff];
}
void RC4_encrypt(RC4_CTX *ctx, unsigned char *dest,
const unsigned char *src, unsigned int len) {
unsigned int i;
for(i=0; i<len; i++)
dest[i] = src[i]^RC4_byte(ctx);
}
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 114.43.108.175
→
05/16 17:53, , 1F
05/16 17:53, 1F
→
05/16 20:27, , 2F
05/16 20:27, 2F
→
05/16 20:28, , 3F
05/16 20:28, 3F
→
05/16 20:30, , 4F
05/16 20:30, 4F
→
05/16 20:32, , 5F
05/16 20:32, 5F
→
05/16 20:33, , 6F
05/16 20:33, 6F
→
05/16 21:33, , 7F
05/16 21:33, 7F
→
05/16 21:36, , 8F
05/16 21:36, 8F
→
05/16 22:45, , 9F
05/16 22:45, 9F
→
05/16 22:46, , 10F
05/16 22:46, 10F
→
05/16 22:46, , 11F
05/16 22:46, 11F