Python 实现RC4流密码

RC4流密码
Python3.7


#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File    :   rc4.py    
@Contact :   nickdlk@outlook.com

@Modify Time            @Author    @Version    @Desciption
------------            -------    --------    -----------
2021/3/28 17:14         Nick      1.0         RC4流密码

'''

import  hashlib,base64


class rc4:
    def __init__(self, public_key=None):
        self.public_key = public_key or 'none_public_key'

    def encode(self, string):
        """
        加密
        :param string: 输入utf-8
        :return:
        """
        bData = [ord(i) for i in string]
        result = self.__docrypt(bData)
        result = base64.b64encode(result.encode())#编码成可见的字符
        return str(result,encoding='utf-8')

    def decode(self, string):
        """
        解密
        :param string:输入utf-8
        :return:
        """
        message = base64.b64decode(string).decode()
        bData = [ord(i) for i in message]
        deresult = self.__docrypt(bData)
        return deresult

    def __rc4_init(self, K):
        """
        :param K: 密钥
        :return:
        """
        j = 0
        K = hashlib.md5(K.encode("utf8")).hexdigest()
        k = []  # 临时数组
        SBox = []  # S盒
        for i in range(256):
            SBox.append(i)
            k.append(K[i % len(K)])  # T[i] = K[ i mod keylen ];
        for i in range(256):
            j = (j + SBox[i] + ord(k[i])) % 256
            SBox[i], SBox[j] = SBox[j], SBox[i]  # 交换S[i],S[j]
        return SBox

    def __docrypt(self,string):
        i = j = 0
        result = ''
        SBox = self.__rc4_init(self.public_key)
        for _str in string:
            i = (i + 1) % 256
            j = (j + SBox[i]) % 256
            SBox[i], SBox[j] = SBox[j], SBox[i]
            k = chr(_str ^ SBox[(SBox[i] + SBox[j]) % 256])
            result += k
        return result


_rc4 = rc4('testkey')
tempcode = _rc4.encode('HelloWorldNick')
print("加密结果",tempcode)
tempdecode = _rc4.decode(tempcode)
print("解密结果",tempdecode)
#加密结果 wqsgMcKIw4DDt8OIQMO2ahTCgMOocQ==
#解密结果 HelloWorldNick
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

nickdlk

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值