implemented the creation of random one-time pads of specified length, defaulting to width of 72

This commit is contained in:
Dan Buch 2009-11-25 20:22:41 -05:00
parent a2ef4ba0b1
commit dca18ca022
2 changed files with 59 additions and 11 deletions

View File

@ -1,3 +1,4 @@
import random
def encode(msg, pad):
@ -6,3 +7,53 @@ def encode(msg, pad):
def decode(msg, pad):
return msg
def create_pad(length, width=72):
chars = _create_chars_for_pad(length)
lines = _chunk_chars_into_lines(chars, width=width)
return lines
def _create_chars_for_pad(length):
chars = []
for char in range(length):
chars.append(_AS_ALPHA[random.randint(1, 25)])
return ''.join(chars)
def _chunk_chars_into_lines(chars, width=72):
lines = []
for chunk in _as_line_chunks(chars, width=width):
lines.append(chunk)
return '\n\n\n'.join(lines)
def _as_line_chunks(chars, width=72):
chunk = []
for char in chars:
chunk.append(char)
if len(chunk) == width:
yield ''.join(chunk)
chunk = []
if len(chunk) < width:
chunk += (['.'] * (width - len(chunk)))
yield ''.join(chunk)
def _mk_as_alpha():
as_alpha = dict()
a_chr = ord('A')
past_j = False
for char in range(26):
letter = chr(a_chr + char)
if letter != 'J':
key = char + (1 if not past_j else 0)
as_alpha[key] = letter
else:
past_j = True
return as_alpha
_AS_ALPHA = _mk_as_alpha()

View File

@ -5,17 +5,14 @@ import onetimepad as OT
class TestOneTimePad(unittest.TestCase):
pad = 'THISISMYONETIMEPADANDITISNOTESPECIALLYBIG' \
'BUTITISBIGENOUGHFORMYUSESIFYOUDONTMINDTHX'
def test_encode(self):
enc = OT.encode(IN_MSG, self.pad)
self.assertEqual(EXPECTED_ENCODED, enc)
def test_mk_as_alpha_excludes_j(self):
self.assertTrue('J' not in OT._AS_ALPHA.values())
def test_decode(self):
dec = OT.decode(EXPECTED_ENCODED, self.pad)
self.assertEqual(IN_MSG, dec)
def test_mk_as_alpha_dict_has_25_members(self):
self.assertEqual(25, len(OT._AS_ALPHA.items()))
IN_MSG = 'TWOBYFOURBOARDSONEHUNDREDCOUNTLENGTHEIGHTFEET'
EXPECTED_ENCODED = 'huteshusoahutseohusoaeutoaehusoat'
def test_creates_pad_of_desired_length(self):
for width in (72, 33, 99, 111):
pad = OT.create_pad(2000, width=width)
self.assertEqual(2000, len((''.join(pad.split())).strip('.')))