1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
| # coding:utf-8 # RC4 python实现代码 # 仅支持128位ASCII码字符文本加解密,要支持任意输入需要更换编码方式 # 秋风木叶 2019-3-27
from FrankTools import ItoB, XOR, StoB, BtoS, swap
def KeyGenerator(K, n):
# RSA(The Key-Scheduling Algorithm) # 秘钥调度算法 S = [i for i in range(0, 256)] R = [] for i in range(0,256): R.append(ord(K[i % len(K)])) j = 0 for i in range(0,256): j = (j + S[i] + R[i]) % 256 S[i], S[j] = swap(S[i], S[j]) #print('随机化后的S {}'.format(S)) # PRGA(The Pseudo-Random Generating Algorithm) # 伪随机子密码生成算法 i = 0 j = 0 K_list = [] while(n): i = (i+1)%256 j = (j+S[i])%256 S[i],S[j] = swap(S[i],S[j]) t = (S[i]+S[j])%256 K_list.append(S[i]) # K_list存储生成的秘钥 n -= 1
# 秘钥转换为二进制序列 k='' for i in K_list: k += ItoB(i) #print('秘钥序列为:{}'.format(BtoS(k))) return k
def Encrypt(M, K): M_list = StoB(M) K_list = KeyGenerator(K, len(M)) #print('------------{0},{1}'.format(len(M_list),len(K_list))) #print(M_list,K_list) return XOR(M_list,K_list)
def Decrypt(C, K): C_list = C K_list = KeyGenerator(K, len(C)/8) #print('----------------{0},{1}'.format(len(C_list),len(K_list))) #print(C_list,K_list) return BtoS(XOR(C_list, K_list))
if __name__=='__main__': #print('\n>>>Test!') M = 'MING CHEN WU DIAN FA DONG FAN GONG' K = 'XING CHUI PING YE KUO YUE YONG DA JIANG LIU' C = Encrypt(M, K) M1 = Decrypt(C, K) print('明文加密之后产生的密文是: {}'.format(C)) print('解密出的明文是: {}'.format(M1))
|