File: onetime

package info (click to toggle)
onetime 1.122-1
  • links: PTS, VCS
  • area: main
  • in suites: buster, jessie, jessie-kfreebsd, stretch, wheezy
  • size: 1,852 kB
  • ctags: 42
  • sloc: python: 448; makefile: 113; sh: 61
file content (732 lines) | stat: -rwxr-xr-x 27,339 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
#!/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 PadBad(Exception):
    """Exception raised if the Pad is asked to do something Bad."""
    pass

  def set_offset(self, offset):
    """Set this pad's encoding/decoding offset to OFFSET."""
    if offset >= self.pad_size:
      raise Pad.PadBad("offset exceeds pad size, need more pad")
    self._offset = offset
    self.padfile.seek(self._offset)

  def convert(self, str):
    """Return a new string that is STR XORed against the pad."""
    pad_str = self.padfile.read(len(str))
    result = ''
    for i in range(len(str)):
      result = result + chr(ord(str[i]) ^ ord(pad_str[i]))
    self._length += len(str)
    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()
    str = self.padfile.read(1024)
    sha1.update(str)
    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, str):
    """Return all available onetime-encoded data so far, including for STR,
    or return None if no encoded data is ready yet."""
    return self._output(self.compressor.compress(self.pad.convert(str)))

  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, str):
    """Return all available onetime-decoded data so far, including for STR,
    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(str))))

  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:
            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       <!-- if any -->
       subdict['another_elt_name'] ==> ANOTHER_ELT_VALUE <!-- if any -->

    A 'pad-records' file is an XML document like this:

      <?xml version="1.0" encode="UTF-8"?>
      <!DOCTYPE TYPE_OF_DOC SYSTEM/PUBLIC "dtd-name">
      <onetime-pad-records>
         <pad-record>
           <id>SHA1_HASH_OF_FIRST_KILOBYTE_OF_PAD</id>
           <used><offset>OFFSET_A</offset>
                 <length>LENGTH_A</length></used>
           <used><offset>OFFSET_B</offset>
                 <length>LENGTH_B</length></used>
           ...
         </pad-record>
         <pad-record>
           <id>SHA1_HASH_OF_FIRST_KILOBYTE_OF_PAD</id>
           <used><offset>OFFSET_C</offset>
                 <length>LENGTH_C</length></used>
           ...
         </pad-record>
         ...
      </onetime-pad-records>
      """
    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("<onetime-pad-records>\n")
    for pad_id in self.pad_records.keys():
      fp.write("  <pad-record>\n")
      fp.write("    <id>%s</id>\n" % pad_id)
      for tuple in self._consolidate_used_ranges\
          (self.pad_records[pad_id]["used"]):
        fp.write("    <used><offset>%d</offset>\n" % tuple[0])
        fp.write("          <length>%d</length></used>\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("  </pad-record>\n")
    fp.write("</onetime-pad-records>\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 a version string."
  rev = "$Revision: 122 $"
  m = re.match(".*Revision: ([0-9]+)[^0-9]*", rev)
  if m:
    return "1.%s" % m.group(1)
  else:
    return "1.<need to fix the revision keyword parsing>"


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.  Because OneTime compresses plaintext
input to save pad, encoding and decoding are not symmetrical; thus,
OneTime needs to be told whether it is encoding or decoding (-e or -d).
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:
      str = input.read()
      if len(str) > 0:
        result = encoder.encode(str)
        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:
      str = input.readline()
      if (str == onetime_end or str == old_onetime_end):
        saw_end = 1
        break
      if len(str) > 0:
        try:
          result = decoder.decode(str)
        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()