Python - RC4 算法
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/max229max/article/details/87607302Python - RC4 算法Max.Bai2019-02 RC4 算法 python3实现:#!/usr/bin/env python"""a simple encryption script usin
·
版权声明:本文为博主原创文章,未经博主允许不得转载。 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))))
更多推荐
已为社区贡献1条内容
所有评论(0)