RC4篇

python实现

库调用

pip install pycryptodome

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
from Crypto.Cipher import ARC4
def rc4_encrypt(text, key):
cipher=ARC4.new(key)
enc=cipher.encrypt(text)
return enc

def rc4_decrypt(text, key):
cipher=ARC4.new(key)
dec=cipher.decrypt(text)
return dec

if __name__ == '__main__':
# m='re100dayzhuji'
# key='jibengong'
# m=m.encode('utf-8')
# key=key.encode('utf-8')
m = b're100dayzhuji'
key = b'jibengong'
enc=rc4_encrypt(m, key)
dec=rc4_decrypt(enc, key)
print('加密后:',enc.hex(),'\n解密后:',dec.decode('utf-8'))

字符串

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
def rc4(key,data):
if isinstance(key,str): #判断key数据类型,如果密钥是字符串,转换为字节串
key=key.encode('utf-8')
#1.初始化S盒
s=list(range(256))
j=0
#2.KSA(密钥调度算法)
for i in range(256):
j=(j+s[i]+key[i%len(key)])%256
s[i],s[j]=s[j],s[i]
#3.PRGA(伪随机生成算法)加密
i=j=0
result=bytearray()
for char in data:
i=(i+1)%256
j=(j+s[i])%256
s[i],s[j]=s[j],s[i]
k=s[(s[i]+s[j])%256]
# print(type(char)) int类型
result.append(char^k)
return bytes(result)

if __name__ == '__main__':
m='re100dayzhuji'
key='jibengong'
enc=rc4(key,m.encode('utf-8'))
dec=rc4(key,enc)
print('加密后: ',enc)
print('解密后: ',dec.decode('utf-8'))

# 加密后: b'9\x87\xf3\x86?&w#\xa7\xe7qd\x81'
# 解密后: re100dayzhuji

Hex

import binascii
binascii.unhexlify()和binascii.hexlify()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
from Crypto.Cipher import ARC4
import binascii
def rc4_encrypt(key,data):
m=data.encode('utf-8')
cipher = ARC4.new(key)
enc=cipher.encrypt(m)
enc=binascii.hexlify(enc).decode('utf-8')
return enc
def rc4_decrypt(key,data):
m=binascii.unhexlify(data) #十六进制明文转换为字节
cipher = ARC4.new(key)
return cipher.decrypt(m)

key=b'jibengong'
m='re100dayzhuji'
enc=rc4_encrypt(key,m)
dec=rc4_decrypt(key,enc)
print(enc)
print(dec.decode('utf-8'))

# 3987f3863f267723a7e7716481
# re100dayzhuji

附带hex格式处理f’{x:02x}’

1
2
3
hex_array=[]
result=''.join([f'{x:02x}' for x in hex_array])
print(result)

RC4篇
https://alenirving.github.io/2025/09/21/RC4篇/
作者
Ma5k
许可协议
CC-BY-NC-SA