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 = 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.encode('utf-8') s=list(range(256)) j=0 for i in range(256): j=(j+s[i]+key[i%len(key)])%256 s[i],s[j]=s[j],s[i] 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] 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'))
|
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'))
|
附带hex格式处理f’{x:02x}’
1 2 3
| hex_array=[] result=''.join([f'{x:02x}' for x in hex_array]) print(result)
|