Python - RC4 算法

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/max229max/article/details/87607302

Python - RC4 算法

Max.Bai

2019-02

 

RC4 算法 python3实现:

#!/usr/bin/env python

"""a simple encryption script using RC4"""

import binascii


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

    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])

    return cipherList

def bytes2hexstr(bytes_data):
    return ''.join(['%02x' % i for i in bytes_data]).upper()


if __name__ == '__main__':
    # ciphertext should be BBF316E8D940AF0AD3
    key = 'Key'
    plaintext = 'Plaintext'
    print('rc4 test', bytes2hexstr(rc4_crypt(plaintext.encode(), key.encode())))

    # ciphertext should be BC9CD0200AB174B467956B4CAE2178BE
    key = '3C381919191918181818181817111111'
    plaintext = '43C8B53E236C4756B8FF24E5AA08A549'
    result = 'BC9CD0200AB174B467956B4CAE2178BE'
    print("rc4 encode is", bytes2hexstr(rc4_crypt(binascii.a2b_hex(plaintext), binascii.a2b_hex(key))))
    print("rc4 decode is", bytes2hexstr(rc4_crypt(binascii.a2b_hex(result), binascii.a2b_hex(key))))


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值