# 1. 背景介绍

## 1.1 RC4算法

RC4由伪随机数生成器和异或运算组成。RC4的密钥长度可变，范围是[1,255]。RC4一个字节一个字节地加解密。给定一个密钥，伪随机数生成器接受密钥并产生一个S盒。S盒用来加密数据，而且在加密过程中S盒会变化。

## 1.2 环境

1. 操作系统：CentOS
2. 编程语言：python 2.7.5
3. python模块：标准库中的hashlib和base64；专门的密码学库Crypto

# 2. 伪代码

`````` for i from 0 to 255
S[i] := i
endfor
j := 0
for( i=0 ; i<256 ; i++)
j := (j + S[i] + key[i mod keylength]) % 256
swap values of S[i] and S[j]
endfor
``````

`````` i := 0
j := 0
while GeneratingOutput:
i := (i + 1) mod 256   //a
j := (j + S[i]) mod 256 //b
swap values of S[i] and S[j]  //c
k := inputByte ^ S[(S[i] + S[j]) % 256]
output K
endwhile
``````

# 3. Python实现

``````import hashlib, base64

def rc4(text, key = 'default-key', mode = "encode"):
key = hashlib.md5(key).hexdigest()#使用的不是原始密钥作为加密密钥，而是取长度固定为32的MD5摘要值作为密钥，从而方便处理
#python3中key需要先encode('utf-8')才能生成MD5
if mode == "decode":#加密得到的消息使用base64编码，则解密的时候需要先将base64编码去除
text = base64.b64decode(text)
result = ''
key_len = len(key)
#1. init S-box
box = list(range(256))#put 0-255 into S-box
j = 0
for i in range(256):#shuffle elements in S-box according to key
j = (j + box[i] + ord(key[i%key_len]))%256
box[i],box[j] = box[j],box[i]#swap elements
#2. make sure all elements in S-box swapped at least once
i = j = 0
for element in text:
i = (i+1)%256
j = (j+box[i])%256
box[i],box[j] = box[j],box[i]
k = chr(ord(element) ^ box[(box[i]+box[j])%256])
result += k
if mode == "encode":
result = base64.b64encode(result)
return result#python3在输出密文时需要result.encode('utf-8')，否则无法打印出来
``````

Github/zc12345

python学习