python3 - RC4 算法

python3 - RC4 算法

max.bai

2019.07

 

工作中遇到的rc4 算法,记录一下

RC4,加密和解密是一样的再加密一次就等于解密了

代码实现:

# coding: utf-8

# import base64
import binascii


def rc4_crypt(PlainBytes:bytes, KeyBytes:bytes) -> str:
    '''[summary]
    rc4 crypt
    Arguments:
        PlainBytes {[bytes]} -- [plain bytes]
        KeyBytes {[bytes]} -- [key bytes]
    
    Returns:
        [string] -- [hex string]
    '''

    keystreamList = []
    cipherList = []

    keyLen = len(KeyBytes)
    plainLen = len(PlainBytes)
    S = list(range(256))

    j = 0
    for i in range(256):
        j = (j + S[i] + KeyBytes[i % keyLen]) % 256
        S[i], S[j] = S[j], S[i]

    i = 0
    j = 0
    for m in range(plainLen):
        i = (i + 1) % 256
        j = (j + S[i]) % 256
        S[i], S[j] = S[j], S[i]
        k = S[(S[i] + S[j]) % 256]
        cipherList.append(k ^ PlainBytes[m])

    result_hexstr = ''.join(['%02x' % i for i in cipherList])
    return result_hexstr.upper()


if __name__ == "__main__":
    data = '43C8B53E236C4756B8FF24E5AA08A549'
    key = '3C381919191918181818181817111111'
    rc4_result = 'BC9CD0200AB174B467956B4CAE2178BE'
    print('data:',data , 'key', key, 'rc4_result:',rc4_result)
    print("rc4 result:", rc4_crypt(binascii.a2b_hex(data), binascii.a2b_hex(key.upper())))
    

 

你可能感兴趣的:(Python)