Skip to content

Instantly share code, notes, and snippets.

@maxcountryman
Created December 18, 2010 01:42
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save maxcountryman/746025 to your computer and use it in GitHub Desktop.
Save maxcountryman/746025 to your computer and use it in GitHub Desktop.
Generates a string from a randomly generated tabula recta that is hopefully secure.
#! /usr/bin/env python
import sys
import json
import argparse
from string import uppercase, digits, letters, punctuation
from random import SystemRandom
FULL_MAP = letters + digits + punctuation
ALPHA_MAP = letters + digits
parser = argparse.ArgumentParser(description='Generate a string, 16 chars, from a tabula recta.')
parser.add_argument('-r', '--row', help='The row to use, select `A`-`Z`')
parser.add_argument('-c', '--col', help='The column to use, select `A`-`Z`')
parser.add_argument('-s', '--show', default=False, help='Set `True` to display current table.')
parser.add_argument('-a', '--alpha', default=False, help='Set `True` to use an alphanumeric table.')
args = parser.parse_args()
r = SystemRandom()
if args.row:
row = args.row.upper()
if row in uppercase and len(row) == 1:
row = uppercase.index(row)
else:
print('Invalid row.')
sys.exit()
if args.col:
col = args.col.upper()
if col in uppercase and len(col) == 1:
col = uppercase.index(col)
else:
print('Invalid column.')
sys.exit()
if not args.alpha:
try:
table = json.load(open('tabula.json'))
except IOError:
table = [[r.choice(FULL_MAP) for i in xrange(len(uppercase))] for i in xrange(len(uppercase))]
json.dump(table, open('tabula.json', 'w'))
else:
try:
table = json.load(open('alpha_tabula.json'))
except IOError:
table = [[r.choice(ALPHA_MAP) for i in xrange(len(uppercase))] for i in xrange(len(uppercase))]
json.dump(table, open('alpha_tabula.json', 'w'))
def traverse(row,col):
s = ''
LEN = 16
WIDTH = 25
edge = False
while len(s) < LEN:
if not edge:
s += table[row][col]
if row == WIDTH and col == WIDTH and len(s) < LEN:
edge = True
continue
if row < WIDTH:
row += 1
if col < WIDTH:
col += 1
else:
if row == 0 and col == 0 and len(s) < LEN:
edge = False
continue
if row > (WIDTH / 2):
col -= 1
s += table[row][col]
return s
def display():
printr = [' '.join(row) for row in [[c for c in uppercase]] + table]
output = ''
i = 0
for row in printr:
add = ''
if i == 1:
add += ' ' + '+' + ''.join(['-' for c in xrange(len(uppercase + uppercase))]) + '\n' + uppercase[i-1] + ' | '
if i == 0:
add += ' ' + row + '\n'
elif i != len(uppercase):
add += row + '\n' + uppercase[i] + ' | '
else:
add += row
output += add
i += 1
return output
if __name__ == '__main__':
if args.row and args.col:
print('\n' + 'Row `{0}` and Column `{1}` returned: '.format(args.row.upper(), args.col.upper()) + traverse(row,col) + '\n')
if args.show:
print(display())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment