欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

python rc4

程序员文章站 2022-07-09 10:23:17
...

明明RC4没写错,就是连不上服务器,来回检查了十几次,晕死,贴测试用例吧

输入是key,需要编码的文字是plaintext,输出的HEX String 应该是out

# key = 'Key'
# plaintext = 'Plaintext'
# out = BBF316E8D940AF0AD3

# key = 'Wiki'
# plaintext = 'pedia'
# out = 1021BF0420

#key = 'Secret'
#plaintext = 'Attack at dawn'
#out 45A01F645FC35B383552544B9BF5

implement 1

class RC4(object):
    def __init__(self, key=bytearray(0)):
        self.S = bytearray(256)
        self.T = bytearray(256)
        self.key_length = 0
        self.i = 0
        self.j = 0
        self.k = 0
        self.t = 0
        self.tmp = bytes()
        if len(key) < 1 or len(key) > 256:
            raise ValueError('key len should not be %d' % len(key))
        else:
            self.key_length = len(key)
            for i in range(256):
                self.S[i] = i
                self.T[i] = key[i % self.key_length]
            j = 0
            for i in range(256):
                j = (j + self.S[i] + self.T[i]) & 0xFF
                tmp = self.S[j]
                self.S[j] = self.S[i]
                self.S[i] = tmp

    def flip(self, plaintext, offset, length):
        cipher = bytearray(length)
        for counter in range(length):
            self.i = (self.i + 1) & 0xFF
            self.j = (self.j + self.S[self.i]) & 0xFF
            self.tmp = self.S[self.j]
            self.S[self.j] = self.S[self.i]
            self.S[self.i] = self.tmp
            self.t = (self.S[self.i] + self.S[self.j]) & 0xFF
            self.k = self.S[self.t]
            cipher[counter] = plaintext[counter + offset] ^ self.k
        return cipher

implement 2

from Crypto.Cipher import ARC4
class RCC4(object):
    def __init__(self, rc4_key):
        self._rc4_cipher = ARC4.new(rc4_key)

    def flip(self, plaintext):
        return self._rc4_cipher.encrypt(plaintext)

test

if __name__ == "__main__":
    key = "Key"
    plaintext = 'Plaintext'

    te = RC4(bytearray(key))
    td = RC4(bytearray(key))
    # encode
    transfer = te.flip(bytearray(plaintext), 0, len(plaintext))
    # decode
    out = td.flip(transfer, 0, len(transfer))
    print "%s %s" % (plaintext[3], chr(out[3]))

    tte = RCC4(key)
    ttd = RCC4(key)
    # encode
    t_transfer = tte.flip(plaintext)
    # encode
    t_out = bytearray(ttd.flip(t_transfer))
    print "%s %s" % (plaintext[3], chr(t_out[3]))
相关标签: python