使用Python实现RC4算法

Python代码:

'''
Created on 2011-6-21
 
@author: shanks
'''
 
def rc4(data, key):
    '''
        data:    data that to be encrypted or decrypted.
        key:     key to encrypt or decrypt. 
    '''
    
    #some parameters check here ...
    
    #if the data is a string, convert to hex format.
    if(type(data) is type("string")):
        tmpData=data
        data=[]
        for tmp in tmpData:
            data.append(ord(tmp))
            
    #if the key is a string, convert to hex format.
    if(type(key) is type("string")):
        tmpKey=key
        key=[]
        for tmp in tmpKey:
            key.append(ord(tmp))
            
    #the Key-Scheduling Algorithm
    x = 0
    box= list(range(256))
    for i in range(256):
        x = (x + box[i] + key[i % len(key)]) % 256
        box[i], box[x] = box[x], box[i]
        
    #the Pseudo-Random Generation Algorithm
    x = 0
    y = 0
    out = []
    for c in data:
        x = (x + 1) % 256
        y = (y + box[x]) % 256
        box[x], box[y] = box[y], box[x]
        out.append(c ^ box[(box[x] + box[y]) % 256])
 
    result=""
    printable=True
    for tmp in out:
        if(tmp<;0x21 or tmp>0x7e):
            # there is non-printable character
            printable=False
            break
        result += chr(tmp)
        
    if(printable==False):
        result=""
        #convert to hex string   
        for tmp in out:
            result += "{0:02X}".format(tmp)
        
    return result
测试代码:
out=rc4("shanks", "vulnhunt")
print("shanks encryption:{}".format(out))
out=rc4([0xA0,0xD8,0x56,0x83,0xF0,0x9D], "vulnhunt")
print("[0xA0,0xD8,0x56,0x83,0xF0,0x9D] decryption:{}".format(out))
 
out=rc4("shanks", [0xA0,0xD8,0x56,0x83,0xF0,0x9D])
print("shanks encryption:{}".format(out))
out=rc4([0x3C,0x51,0x8F,0x52,0xA1,0x91], [0xA0,0xD8,0x56,0x83,0xF0,0x9D])
print("[0x3C,0x51,0x8F,0x52,0xA1,0x91] decryption:{}".format(out))
 
out=rc4([0xA0,0xD8,0x56,0x83,0xF0,0x9D], [0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09])
print("[0xA0,0xD8,0x56,0x83,0xF0,0x9D] encryption:{}".format(out))
out=rc4([0x18,0x48,0x33,0xc8,0x50,0xB3], [0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,0x09])
print("[0x18,0x48,0x33,0xc8,0x50,0xB3] decryption:{}".format(out))
执行结果:
使用Python实现RC4算法_第1张图片

你可能感兴趣的:(Algorithm,算法,python,String,encryption,hex)