📄 rc4.cpp
字号:
//rc4.cpp
/*
* An implementation of the ARC4 algorithm
*
* Copyright (C) 2001-2003 Christophe Devine
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "rc4.h"
#include <stdlib.h>
#include <windows.h>
void rc4_makey( unsigned char *key, int keylength )
{
//由于RC4算法加密是采用的xor,所以,一旦子密钥序列出现了重复,
//密文就有可能被破解。RC4算法生成的子密钥序列是否会出现重复呢
//经过我的测试,存在部分弱密钥,使得子密钥序列在不到100万字节
//内就发生了完全的重复,如果是部分重复,则可能在不到10万字节
//内就能发生重复,因此,推荐在使用RC4算法时,必须对加密密钥进
//行测试,判断其是否为弱密钥。
//有办法让他不重复。但是也觉得没有必要
srand(GetTickCount());
//生成密钥
for (long i = 0 ;i<keylength;i++)
{
try
{
key[i] =rand()%256;//怕数组越界
}
catch (...)
{
break;
}
}
}
void rc4_setup( struct rc4_state *s, unsigned char *key, int length )
{
int i, j, k, *m, a;
s->x = 0;
s->y = 0;
m = s->m;
for( i = 0; i < 256; i++ )
{
m[i] = i;
}
j = k = 0;
for( i = 0; i < 256; i++ )
{
a = m[i];
j = (unsigned char) ( j + a + key[k] );
m[i] = m[j];
m[j] = a;
if( ++k >= length )
k = 0;
}
}
void rc4_crypt( struct rc4_state *s, unsigned char *data, int length )
{
int i, x, y, *m, a, b;
x = s->x;
y = s->y;
m = s->m;
for( i = 0; i < length; i++ )
{
x = (unsigned char)( x + 1 );
a = m[x];
y = (unsigned char)( y + a );
m[x] = b = m[y];
m[y] = a;
data[i] ^= m[(unsigned char) ( a + b )];
}
s->x = x;
s->y = y;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -