技术改变历史,决定无数人生死的典型案例。现在只用一点点python代码就实现了,不由得感叹上帝跌落凡间。该代码的原始出处不详。。。
from random import shuffle, randint, choice from copy import copy num_alphabet = list(range(26)) def en_shift(l, n): return l[n:] + l[:n] class Cog: """ 模拟转子 """ def __init__(self): self.shuf = copy(num_alphabet) shuffle(self.shuf) return def subs_in(self, i): return self.shuf[i] def subs_out(self, i): return self.shuf.index(i) def rotate(self): self.shuf = en_shift(self.shuf, 1) def setcog(self, a): self.shuf = a class Enigma: def __init__(self, numcogs, readability=True): self.readability = readability self.numcogs = numcogs self.cogs = [] self.oCogs = [] for i in range(0, self.numcogs): self.cogs.append(Cog()) self.oCogs.append(self.cogs[i].shuf) refabet = copy(num_alphabet) self.reflector = copy(num_alphabet) while len(refabet) > 0: a = choice(refabet) refabet.remove(a) b = choice(refabet) refabet.remove(b) self.reflector[a] = b self.reflector[b] = a def reset(self): for i in range(0, self.numcogs): self.cogs[i].setcog(self.oCogs[i]) def encode(self, text): t = 0 ciphertext = "" for l in text: c = ord(l) start_c = 65 if c >= 97: start_c = 97 num = c % start_c if num > 25 or num < 0: if self.readability: ciphertext += l else: pass else: # Pass through cogs, reflect, then return through cogs t += 1 for i in range(self.numcogs): num = self.cogs[i].subs_in(num) num = self.reflector[num] for i in range(self.numcogs): num = self.cogs[self.numcogs - i - 1].subs_out(num) ciphertext += "" + chr(start_c + num) # Rotate cogs for i in range(self.numcogs): if t % ((i * 6) + 1) == 0: self.cogs[i].rotate() return ciphertext # 初始化 x = Enigma(6) origin_msg = "Attack at nine o 'clock tomorrow morning" print("原始信息: {}".format(origin_msg)) secret_msg = x.encode(origin_msg) print("加密信息: {}".format(secret_msg)) x.reset() print("解密信息: {}".format(x.encode(secret_msg)))
# 运行结果
原始信息: Attack at nine o 'clock tomorrow morning
加密信息: Gpzlwo ub heck w 'ewrfo ufvpvlnj ergaaki
解密信息: Attack at nine o 'clock tomorrow morning
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://bianchenghao.cn/bian-cheng-ji-chu/102183.html