Created
April 25, 2018 15:05
-
-
Save Vinc0682/723f7995aca6931160469707c85312c4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python2 | |
#-*- coding:utf-8 -*- | |
from random import randint, shuffle | |
def invserse(wheel): | |
result = [ 0 for _ in range(26) ] | |
for i in range(26): | |
result[wheel[i]] = i | |
return result | |
def encrypt(data, s, wheels, u): | |
result = '' | |
for x in data: | |
c = ord(x) - 65 | |
c = s[c] | |
for wheel in wheels: | |
c = wheel[c] | |
c = u[c] | |
for wheel in reversed(wheels): | |
c = invserse(wheel)[c] | |
c = s[c] | |
result += chr(c + 65) | |
for i in range(len(wheels)): | |
if len(result) % 26**i == 0: | |
wheels[i] = wheels[i][1:] + [wheels[i][0]] | |
return result | |
def has_fix_point(permutation): | |
for i in range(len(permutation)): | |
if permutation[i] == i: | |
return True | |
return False | |
def generate_keys(): | |
tmp = range(26) | |
wheels = [] | |
for i in range(4): | |
shuffle(tmp) | |
wheels.append(list(tmp)) | |
while has_fix_point(tmp): | |
shuffle(tmp) | |
return (wheels, tmp) | |
def run(): | |
s = range(26) | |
# Proof that the Enigma-encryption is no longer it's own inverse when the "Steckbrett" contains a cycle of the length 3 | |
s[0] = 2 | |
s[1] = 0 | |
s[2] = 1 | |
wheels, u = generate_keys() | |
for pt in 'ABC': | |
enc = encrypt(pt, s, wheels, u) | |
dec = encrypt(enc, s, wheels, u) | |
print pt + ' encrypts to ' + enc + ' which decrypts to ' + dec + '.' | |
if __name__ == '__main__': | |
run() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment