#!/usr/bin/env python
__doc__ = """Encoder/decoder for one-time pads. Run 'onetime --help' for usage.
The usual public-key encryption programs, such as GnuPG, are probably
secure for everyday purposes, but their implementations are too
complex for all but the most knowledgeable programmers to vet, and
anyway there are too many vulnerable steps in the supply chain between
GPG's authors and the end user.
Hence this script, OneTime, a simple encryption program that works with
one-time pads. If you don't know what one-time pads are, you probably
wouldn't be able to use them securely, so this program is not for you.
If you do know what they are and how to use them, OneTime will take care
of some of the pad-management bureacracy for you. It avoids re-using
pad data -- except when decrypting the same encrypted message twice, of
course -- by maintaining records of pad usage in ~/.onetime/pad-records.
And if you keep your ~/.onetime configuration area under version control
with Subversion or CVS, OneTime will automatically update it to get the
latest pad usage records before using a pad, and will commit new records
after using a pad. Thus, by sharing a single configuration area via
version control, you and your interlocutors can more easily avoid the
sin of pad range reuse. (The pads themselves are not stored in the
configuration area, just records about pad usage.)
See http://en.wikipedia.org/wiki/One-time_pad for more information
about one-time pads in general.
OneTime is written by Karl Fogel and is in the public domain. Its
home page is http://www.red-bean.com/onetime/.
"""
import os
import sys
import stat
import getopt
import bz2
import base64
import hashlib
import re
import xml
import xml.dom
import xml.dom.minidom
# Set up booleans that older Pythons didn't have, if necessary.
try:
True
except:
True = 1
False = 0
class Pad:
"""An encoder/decoder associated with a specific pad at a specific offset.
Feed bytes through convert() to XOR them against the pad."""
def __init__(self, pad_path):
"""Initialize a new pad, using padfile PAD_PATH. The pad cannot be
used for encoding or decoding until set_offset() is called."""
self.pad_path = pad_path
self.padfile = open(self.pad_path)
self.pad_size = os.stat(self.pad_path)[stat.ST_SIZE]
self._offset = 0 # where to start using pad bytes
self._length = 0 # number of pad bytes used this time
self._id = self._get_id(self.padfile)
class PadShort(Exception):
"""Exception raised if Pad doesn't have enough data for this encryption."""
pass
def set_offset(self, offset):
"""Set this pad's encoding/decoding offset to OFFSET."""
if offset >= self.pad_size:
raise Pad.PadShort("offset exceeds pad size, need more pad")
self._offset = offset
self.padfile.seek(self._offset)
def convert(self, string):
"""Return a new string that is STRING XORed against the pad."""
string_len = len(string)
pad_str = self.padfile.read(string_len)
if len(pad_str) < string_len:
raise Pad.PadShort("not enough pad data available to finish encryption")
result = ''
for i in range(string_len):
result = result + chr(ord(string[i]) ^ ord(pad_str[i]))
self._length += string_len
return result
def _get_id(self, padfile):
"""Get the ID (the SHA1 of its first kilobyte) for this pad."""
saved_posn = self.padfile.tell()
self.padfile.seek(0)
sha1 = hashlib.sha1()
string = self.padfile.read(1024)
sha1.update(string)
self.padfile.seek(saved_posn)
return sha1.hexdigest()
def id(self):
"""Return the pad's ID."""
return self._id
def path(self):
"""Return the pad's path."""
return self.pad_path
def offset(self):
"""Return offset from which encoding/decoding started."""
return self._offset
def length(self):
"""Return the number of pad bytes used so far."""
return self._length
def __str__(self):
"""Return a string representation of this pad."""
return "Pad '%s' (%s):\n Offset: %d\n Length: %d\n" \
% (self.path(), self.id(), self.offset(), self.length())
class PadEncoder:
"""Class for encoding raw data to OneTime output."""
class PadEncoderNotFinished(Exception):
"""Exception raised if the encoder is asked for information it
doesn't have yet, such as the final encoded length."""
pass
def __init__(self, pad, config):
"""Initialize an encoder for PAD with Configuration CONFIG."""
self.pad = pad
self.config = config
self.compressor = bz2.BZ2Compressor()
self.finished = 0
def _output(self, compressed_str):
"Return encoding of COMPRESSED_STR, or None if COMPRESSED_STR is empty."
if compressed_str:
return base64.encodestring(compressed_str)
else:
return None
def encode(self, string):
"""Return all available onetime-encoded data so far, including for STRING,
or return None if no encoded data is ready yet."""
return self._output(self.compressor.compress(self.pad.convert(string)))
def finish(self):
"Return last of encoding of COMPRESSED_STR, or None if none left."
self.finished = 1
last_bits = self._output(self.compressor.flush())
self.config.consume(self.pad, False)
return last_bits
class PadDecoder:
"""todo: write this doc string"""
def __init__(self, pad, config):
"""Initialize a decoder for PAD with Configuration CONFIG."""
self.pad = pad
self.config = config
self.decompressor = bz2.BZ2Decompressor()
self.unused_data = ""
def decode(self, string):
"""Return all available onetime-decoded data so far, including for STRING,
or return None if no decoded data is ready yet. Throw EOFError
exception if called past the end of decodable data. Store any
unused data in self.unused_data."""
### todo: we're not really doing that unused_data thing, are we?
return self.pad.convert((self.decompressor.decompress
(base64.decodestring(string))))
def finish(self):
"""Finalize pad usage with the configuration."""
self.config.consume(self.pad, True)
class Configuration:
"""A parsed representation of one user's ~/.onetime/ configuration area.
A .onetime/ directory contains just a 'pad-records' file right now."""
def __init__(self, path=None, no_vc=False):
"""Initialize a new configuration.
If PATH is None, try to find or create the config area in the
standard location in the user's home directory; otherwise, find or
create it at PATH.
Unless NO_VC, update and commit the pad-records file when appropriate."""
self.config_area = path
self.no_vc = no_vc
if self.config_area is None:
self.config_area = os.path.join(os.path.expanduser("~"), ".onetime")
self.pad_records_file = os.path.join(self.config_area, "pad-records")
# Create the configuration area if necessary.
if not os.path.isdir(self.config_area):
# Legacy data check: if they have a ~/.otp dir, that's probably
# from a previous incarnation of this program, when it was named
# "otp". If so, just rename the old config area.
old_config_area = os.path.join(os.path.expanduser("~"), ".otp")
old_pad_records_file = os.path.join(old_config_area, "pad-records")
if os.path.isfile(old_pad_records_file):
os.rename(old_config_area, self.config_area)
else:
os.mkdir(self.config_area)
if not os.path.isfile(self.pad_records_file):
open(self.pad_records_file, "w").close()
# Update the pad-records file before parsing, if possible.
self._maybe_update_pad_records()
# Parse the pad-records file (if any) in the configuration area.
self.pad_records = self._parse_pad_records_file()
class ConfigurationError(Exception):
"""Exception raised if we encounter an impossible state in a
Configuration."""
pass
class ConfigurationVCError(Exception):
"""Exception raised if something went wrong with a VC operation in
a Configuration."""
pass
def _consolidate_used_ranges(self, used, allow_reconsumption=False):
"""Return a consolidated version of USED. USED is a list of
tuples, indicating offsets and lengths:
[ (OFFSET1, LENGTH1), (OFFSET2, LENGTH2), ... ]
Consolidation means returning a list of equal or shorter length,
that marks exactly the same ranges as used, but expressed in the
most compact way possible. For example:
[ (0, 10), (10, 20), (20, 25) ]
would become
[ (0, 25) ]
If ALLOW_RECONSUMPTION is False, raise a ConfigurationError
exception if the input is incoherent, such as a range beginning
inside another range. But if ALLOW_RECONSUMPTION is True, allow
ranges to overlap. Typically, it will be False when encoding and
True when decoding, because it's legitimate to decode a message
multiple times, as long as no one re-uses that range for encoding."""
new_used = [ ]
last_offset = None
last_length = None
for tup in used:
(this_offset, this_length) = tup
if last_offset is not None:
if last_offset + last_length >= this_offset:
# It's only reconsumption if the end of the previous range
# extends past the next offset. So we error on that if
# we're not allowing reconsumption...
if (last_offset + last_length > this_offset
and not allow_reconsumption):
raise self.ConfigurationError, \
"pad's used ranges are incoherent:\n %s" % str(used)
# ...but otherwise we just extend the range from the
# original offset, whether it was a true overlap or a
# snuggle-right-up-against kind of thing:
else:
# All the possible cases are:
#
# 1) first tuple entirely precedes second
# 2) second tuple begins inside first but ends after it
# 3) second tuple begins and ends inside first
# 4) second tuple begins *before* first and ends in it
# 5) second tuple begins and ends before first
#
# However, due to the conditional above, we must be in (2)
# or (3), and we only need to adjust last_length if (2).
if (this_offset + this_length) > (last_offset + last_length):
last_length = (this_offset - last_offset) + this_length
else:
new_used.append((last_offset, last_length))
last_offset = this_offset
last_length = this_length
else:
last_offset = this_offset
last_length = this_length
if last_offset is not None:
new_used.append((last_offset, last_length))
return new_used
def _get_next_offset(self, used):
"""Get the next free offset from USED, which is assumed to be in
consolidated form."""
cur_offset = None
# We don't do anything fancy, just get the earliest available
# offset past the last used tuple. This means that any ranges in
# between tuples are wasted. See comment in main() about
# discontinuous ranges for why this is okay.
for tup in used:
(this_offset, this_length) = tup
cur_offset = this_offset + this_length
if cur_offset is None:
return 0
else:
return cur_offset
def _directory_vc(self, directory):
"""If DIRECTORY is under version control with SVN or CVS, return
the string 'svn' or 'cvs' accordingly, else return False."""
if os.path.isdir(os.path.join(directory, '.svn')):
return 'svn'
elif os.path.isdir(os.path.join(directory, 'CVS')):
return 'cvs'
else:
return False
def _maybe_do_vc_operation(self, action):
"""If the 'pad-records' file in the configuration area appears to
be under version control, then attempt to take ACTION on it.
ACTION can be 'update' or 'commit -mMSG'. Put MSG in quotes if it
is longer than one word. If ACTION fails, throw a
ConfigurationVCError exception."""
if self.no_vc:
return
vc = self._directory_vc(self.config_area)
if vc:
if os.system("%s -q %s %s" % (vc, action, self.pad_records_file)):
raise ConfigurationVCError
def _maybe_update_pad_records(self):
"""If the 'pad-records' file in the configuration area appears to
be under version control, then attempt to update it. If the
update fails, throw a ConfigurationVCError exception."""
self._maybe_do_vc_operation('update')
def _maybe_commit_pad_records(self):
"""If the 'pad-records' file in the configuration area appears to
be under version control, then attempt to commit it. If the
update fails, throw a ConfigurationVCError exception."""
self._maybe_do_vc_operation('commit -m"Record pad usage."')
def _parse_pad_records_file(self):
"""Return a dictionary representing this configuration's 'pad-records'
file (e.g., ~/.onetime/pad-records). If the file is empty, just
return an empty dictionary.
The returned dictionary is keyed on pad IDs, with sub-dictionaries
as values. Each sub-dictionary's keys are the remaining element
names inside a pad element, and the value of the 'used' element is
a list of tuples, each tuple of the form (OFFSET, LENGTH). So:
returned_dict[SHA1_SUM] ==> subdict
subdict['used'] ==> [(OFFSET1, LENGTH1), (OFFSET2, LENGTH2), ...]
subdict['some_elt_name'] ==> SOME_ELT_VALUE
subdict['another_elt_name'] ==> ANOTHER_ELT_VALUE
A 'pad-records' file is an XML document like this:
SHA1_HASH_OF_FIRST_KILOBYTE_OF_PAD
OFFSET_A
LENGTH_A
OFFSET_B
LENGTH_B
...
SHA1_HASH_OF_FIRST_KILOBYTE_OF_PAD
OFFSET_C
LENGTH_C
...
...
"""
dict = { }
try:
dom = xml.dom.minidom.parse(self.pad_records_file)
for pad in dom.firstChild.childNodes:
id = None
path = None
used = [ ]
if pad.nodeType == xml.dom.Node.ELEMENT_NODE:
subdict = { }
for pad_part in pad.childNodes:
if pad_part.nodeType == xml.dom.Node.ELEMENT_NODE:
if pad_part.nodeName == "id":
id = pad_part.childNodes[0].nodeValue
elif pad_part.nodeName == "used":
offset = None
length = None
for used_part in pad_part.childNodes:
if used_part.nodeName == "offset":
offset = int(used_part.childNodes[0].nodeValue)
if used_part.nodeName == "length":
length = int(used_part.childNodes[0].nodeValue)
used.append((offset, length))
subdict["used"] = self._consolidate_used_ranges(used)
else:
# Parse unknown elements transparently.
subdict[pad_part.nodeName] = pad_part.childNodes[0].nodeValue
if not subdict.has_key("used"):
# We don't require the "used" element to be present; if it's
# absent, it just means none of this pad has been used yet.
subdict["used"] = [ (0, 0) ]
dict[id] = subdict
except xml.parsers.expat.ExpatError:
pass
return dict
def save(self):
"""Save the pad-records file, and maybe commit it."""
tempfile = self.pad_records_file + ".tmp"
fp = open(tempfile, 'w')
fp.write("\n")
for pad_id in self.pad_records.keys():
fp.write(" \n")
fp.write(" %s\n" % pad_id)
for tuple in self._consolidate_used_ranges\
(self.pad_records[pad_id]["used"]):
fp.write(" %d\n" % tuple[0])
fp.write(" %d\n" % tuple[1])
for key in self.pad_records[pad_id].keys():
if key != "used":
fp.write(" <%s>%s%s>\n" % \
(key, self.pad_records[pad_id][key], key))
fp.write(" \n")
fp.write("\n")
fp.close()
os.rename(tempfile, self.pad_records_file)
self._maybe_commit_pad_records()
def register(self, pad):
"""Register PAD if it is not already registered, and set its
offset based on previously used regions for that pad, if any."""
if not self.pad_records.has_key(pad.id()):
self.pad_records[pad.id()] = { "used" : [ ] }
pad.set_offset(self._get_next_offset(self.pad_records[pad.id()]["used"]))
def consume(self, pad, allow_reconsumption):
"""Record that PAD has used PAD.length() bytes starting at PAD.offset().
If ALLOW_RECONSUMPTION is False, raise a ConfigurationError
if reconsuming any part of a range that has been consumed previously.
But if ALLOW_RECONSUMPTION is True, allow ranges to overlap.
Typically, it is be False when encoding and True when decoding,
because it's okay to decode a message multiple times, but not to
re-use a range for encoding."""
used = self.pad_records[pad.id()]["used"]
used.append((pad.offset(), pad.length()))
self.pad_records[pad.id()]["used"] = self._consolidate_used_ranges\
(used, allow_reconsumption)
pass
def show_pad_records(self):
"""Print pad records, presumably for debugging."""
for pad_id in self.pad_records.keys():
print "Pad %s:" % pad_id
print " used:", self.pad_records[pad_id]["used"]
def version():
"Return the version of OneTime as a string."
# OneTime used to be in Subversion, not Git, and this was a
# "$Revision$" keyword. Now we're in git and the 1.x line is in
# maintenance only, so we just maintain the number by hand here.
return "1.81"
def usage(outfile=sys.stdout):
"""Return a usage string."""
usage_str = """\
OneTime version %s, an encoder/decoder for one-time pads. Standard usage:
onetime -e -p PAD INPUT (encrypt; write output to 'INPUT.onetime')
onetime -d -p PAD INPUT.onetime (decrypt; output loses '.onetime' suffix)
Other usage modes:
onetime [-e|-d] -p PAD INPUT -o OUTPUT (both INPUT and OUTPUT are files)
onetime [-e|-d] -p PAD INPUT -o - (output goes to stdout)
onetime [-e|-d] -p PAD (input from stdin, output to stdout)
onetime [-e|-d] -p PAD -o OUTPUT (input from stdin, output to OUTPUT)
OneTime remembers what ranges of what pad files have been used, and avoids
re-using those ranges when encoding.
All options:
-e Encrypt
-d Decrypt
-p PAD | --pad=PAD Use PAD for pad data.
-o OUT | --output=OUT Output to file OUT ("-" for stdout)
--offset=N Control the pad data start offset
-n | --no-trace Leave no record of pad usage in your config
-C DIR | --config=DIR Specify DIR (instead of ~/.onetime) as config area
--no-vc Ignore SVN/CVS control of the config area
--intro Show an introduction to OneTime and one-time pads
-v | -V | --version Show version information
-? | -h | --help Show usage
""" % version()
outfile.write(usage_str)
def main():
encrypting = False
decrypting = False
pad_file = None
input = None
output = None
offset = 0
config_area = None
debug = False
error_exit = False
no_vc = False
no_trace = False
try:
opts, args = getopt.getopt(sys.argv[1:],
'edp:o:h?vVnC:',
[ "encrypt", "decrypt",
"pad=",
"output=",
"offset=",
"config=",
"no-vc",
"no-trace",
"debug",
"intro", "help", "version"])
except getopt.GetoptError:
sys.stderr.write("Error: problem processing options\n")
usage(sys.stderr)
sys.exit(1)
for opt, value in opts:
if opt == '--help' or opt == '-h' or opt == '-?':
usage()
sys.exit(0)
if opt == '--intro':
print __doc__,
sys.exit(0)
elif opt == '--version' or opt == '-v' or opt == '-V':
print "OneTime version %s" % version()
sys.exit(0)
elif opt == '--encrypt' or opt == '-e':
encrypting = True
elif opt == '--decrypt' or opt == '-d':
decrypting = True
elif opt == '--pad' or opt == '-p':
pad_file = value
elif opt == '--output' or opt == '-o':
if value == "-":
output = sys.stdout
else:
output = open(value, "w")
elif opt == '--offset':
offset = int(value)
elif opt == '--config' or opt == '-C':
config_area = value
elif opt == '--no-vc':
no_vc = True
elif opt == '--no-trace' or opt == '-n':
no_trace = True
elif opt == '--debug':
debug = 1
else:
sys.stderr.write("Error: unrecognized option: '%s'\n" % opt)
error_exit = True
if not encrypting and not decrypting:
sys.stderr.write("Error: must pass either '-e' or '-d'.\n")
error_exit = True
if encrypting and decrypting:
sys.stderr.write("Error: cannot pass both '-e' and '-d'.\n")
error_exit = True
if not pad_file:
sys.stderr.write("Error: must specify pad file with -p.\n")
error_exit = True
if len(args) == 0 or args[0] == "-":
input = sys.stdin
if output is None:
# If input is stdin, output defaults to stdout.
output = sys.stdout
elif len(args) == 1:
input = open(args[0])
if output is None:
if encrypting:
# If plaintext input is 'FILENAME', output defaults to
# 'FILENAME.onetime'.
output = open(args[0] + ".onetime", "w")
else:
# If crypttext input is 'FILENAME.onetime', output defaults to
# 'FILENAME'. But we also look for ".otp", for compatibility
# with older versions of this program.
if args[0].endswith(".onetime"):
output = open(args[0][:-8], "w")
elif args[0].endswith(".otp"):
output = open(args[0][:-4], "w")
else:
sys.stderr.write(
"Error: input filename does not end with '.onetime' or '.otp'.\n")
error_exit = True
elif len(args) > 1:
sys.stderr.write("Error: unexpected arguments: %s\n" % args[1:])
error_exit = True
if error_exit:
usage(sys.stderr)
sys.exit(1)
pad = Pad(pad_file)
config = Configuration(config_area, no_vc)
config.register(pad)
### todo: need to be less clumsy about offset handling
if offset > 0:
pad.set_offset(offset)
# The first line of OneTime format is the begin line.
# Then comes the header: a group of lines followed by a blank line.
# Then comes the encoded body.
# The last line indicates the end, and is distinguishable from
# encoded content by inspection
onetime_begin = "-----BEGIN OneTime MESSAGE-----\n"
old_onetime_begin = "-----BEGIN OTP MESSAGE-----\n" # compat
onetime_header = "%s" % onetime_begin \
+ "Version: OneTime %s\n" % version() \
+ "Pad ID: %s\n" % pad.id() \
+ "Offset: %s\n" % pad.offset() \
+ "\n"
onetime_end = "-----END OneTime MESSAGE-----\n"
old_onetime_end = "-----END OTP MESSAGE-----\n" # compat
# We could use pads more efficiently, by encoding with multiple
# discontinuous ranges to avoid the "sparse wasted space" problem.
# Instead of using a single 'Offset:' header at the beginning of the
# message, we'd embed pad range metadata into the stream as we
# encrypt. That way we could use up free pad space no matter where
# it's located:
#
# -----BEGIN OneTime MESSAGE-----
# Version: OneTime 1.59
# Pad ID: de61f169bce003a1189b3e6ebb8ddfc0ef007ac2
#
# Offset 0:
# fvPh7od4icPXB0M1fcARXIHRGl8MMSrbKlc6dTjiT7cu/9gGiwwoPFyI0muM73G
# G6cLE9+gipcEnMIO+Ec6t1iO7KrjnHmD931nU1ko9wtVNjvUaaWjVZmjqQp5Hr9
# JT6m/oYsrMN10/1NcmknSlzVrxV0RQ3bNl4zAck/9LX0XuVFz1KKvOga02LtsQG
# q2RKyB63bLlbUQBeUL1OITMjhn+vblI2XItPMiPplexm8tBjPkhEffvBZSSK2RH
# zDBVeHgOkm3PVD2R+kW6WmZidW+W6n0WMMCrRtyFLZzYFjoctTx5fOe9216bJOI
# ndXEbwO13j43zHAd52pI3GddBaRVpkXBu2e2rzMLCGyVCvsihvpQyAXnubR62u9
# Offset 114:
# 6Ftmk4uaNUojelW2weclXOyo9um5YBK+6cZXhOOnYVUgHvmHI/kz8WwxeTuJy0A
# il96oeP/Kk0uIfaGu81qYvPyBntEDdi8iKjs0kv2rj6F4mqjQUzfljId/UeOaTG
# a/W0l8ZD8eH+Wt+XH0tx57pFLZ8zzPj+KARuDK9XiRfkhrRseFIm2ylGmD3SY69
# yyGUDWYm3JGc0g+9b7AAWJy83xSJEywKGvs9RwhhSDz/Qe8610dJOLXLwyHGfwB
# mCXgYzi13sxYwYM1eYMg3xt/sot+w3V61ps1O7mnb+AA99k1Uxvwy4/8KZAKpAn
# AFPOnoL70mDoW9r8zxzWLA39Regfd3DChA8hNYd2zM6k72047pL50cKWwqsSoGQ
# Offset 570:
# gVL/aCtgYuXNph908Hk/rtdj1GUSLEzlxpBDgtYrj02m5oHLl64ZXs+VBQg2wtG
# qFSBj4zTQXQYrZPqYVqlAoQBGPZy110nbJWRq4clDx5LNiNeYEZAnqznXn2SO90
# AX+dllPISlrlca5gcK+KCUvJFPqe/KZ9WcjCJbi94GYFJdsxutLIaUQsZpc0+Pq
# UmO4VLD1ef8N6G8vrTUamDPc7+FBXZIUn0sEpJ6Al9jBRNxd56aiBkqwQe0Dboj
# d2Rxc56aVy7PS9yN1tcsuu/RwCDrOR/kGJ0CYU1G/XyTifUqQrPbzMdAgV8bBOg
# [...etc, etc...]
# -----END OneTime MESSAGE-----
#
# However, the common case is two people sharing a pad to exchange
# messages serially, and in that case there is no benefit to using
# this scheme, since they're already using the pad as efficiently as
# possible. IMHO, the extra complexity isn't worth the occasional
# space-savings. Random numbers aren't dirt cheap, but they're not
# terribly expensive either. Asking users to occasionally spend
# extra pad bits for the sake of code simplicity seems reasonable.
#
# We can always add this format in the future, though. If the
# 'Offset:' line appears in the headers, then we're using the old
# format, if not, then we're using the new format.
if encrypting:
encoder = PadEncoder(pad, config)
output.write(onetime_header)
while 1:
string = input.read()
if len(string) > 0:
result = encoder.encode(string)
if result:
output.write(result)
else:
result = encoder.finish()
if result:
output.write(result)
break
output.write(onetime_end)
elif decrypting:
decoder = PadDecoder(pad, config)
saw_end = None
maybe_header_line = input.readline()
if (maybe_header_line != onetime_begin
and maybe_header_line != old_onetime_begin):
sys.stderr.write("Error: malformed OneTime format: no begin line.\n")
sys.exit(1)
while maybe_header_line != "\n":
maybe_header_line = input.readline()
m = re.match("Offset: ([0-9]+)", maybe_header_line)
if m:
pad.set_offset(int(m.group(1)))
while 1:
string = input.readline()
if (string == onetime_end or string == old_onetime_end):
saw_end = 1
break
if len(string) > 0:
try:
result = decoder.decode(string)
except EOFError:
break
if result:
output.write(result)
else:
break
decoder.finish()
if not saw_end:
sys.stderr.write("Error: malformed OneTime format: no end line.\n")
sys.exit(1)
if (encrypting or decrypting) and not no_trace:
config.save()
if debug:
config.show_pad_records()
if __name__ == '__main__':
main()