1、加密原理
基于按位异或(^),对字符串进行简单的加密算法原理:
ord('A')^ord('P') #加密,运算结果:17
chr(17^ord('p')) #解密,运算结果:‘A’
2、例题
给定字符串text作为明文(要加密的原文,同上述A)和key作为密钥(同上述P),使用按位异或循环处理text的每一个字符达到加密效果,结果就是加密后的密文(同上述加密运算结果17);解密需将密文转为明文。
from itertools import cycle
def crypt(text,key):
result = [] #定义一个空的列表用来存放密语
keys = cycle(key) #迭代器,用于迭代密钥的每一个字符
for ch in text:
result.append(chr(ord(ch)^ord(next(keys))))
#逐字加密并将结果添加到result列表中
return ''.join(result) #return在循环体外
#test
if __name__ == '__main__':
plain = 'The quick brown fox jumps over the lazy dog' #明文
key = 'Python_1' #密钥
print('加密前明文:{}'.format(plain))
encrypted = crypt(plain,key) #加密
print('加密后的密文:{}'.format(encrypted))
decrypted = crypt(encrypted,key) #解密
print('解密后的明文:{}'.format(decrypted))
3、详解
(1)


6270

被折叠的 条评论
为什么被折叠?



