Dec-14-2018, 07:23 PM
(This post was last modified: Dec-14-2018, 07:23 PM by Gribouillis.)
A small training session in my favorite language
#!/usr/bin/env python3 import itertools as itt import os def iranduint(): yield from itt.chain.from_iterable(os.urandom(1024) for k in itt.count()) iranduint = iranduint() def irandrange(n): sz = n.bit_length() if sz > 8: raise ValueError('Expected value < 256, got', n) m = 2 ** sz assert((m/2) <= n < m) for x in iranduint: x %= m if x < n: yield x def irandchoice(n): s = set() while True: x = next(irandrange(n)) if x in s: continue s.add(x) yield x def make_key(): rotor = [x for x in range(1, 9)] alpha = [x for x in "ABCDEFGHIJKL"] chx = irandchoice(len(alpha)) core = [alpha[next(chx)] for i in range(8)] g36 = irandrange(36) ring = [1 + next(g36) for i in range(8)] g11 = irandchoice(11) notchring = [1 + next(g11) for i in range(7)] notchring.insert(3, '') beta = ("A, B, B+, C, D, E, E+, F, G, G+, " "H, I, J, J+, K, L, M, M+ N, O, O+, " "P, Q, R, R+, S, T, T+, U, V, W, W+, " "X, Y, Z, Z+").replace(",", "").split() val = irandrange(len(beta)) ringset = [beta[next(val)] for i in range(7)] ringset.insert(3, '') return rotor, core, ring, notchring, ringset if __name__ == '__main__': for row in make_key(): print(''.join('{:<3}'.format(x) for x in row))
Output:
1 2 3 4 5 6 7 8
G D A F J L H E
34 31 36 29 4 19 11 3
6 9 7 1 8 5 10
S B+ D X Z+ A M
Starting with 3.6, one can use the secrets module instead of os.urandom