[Python编程(第4版)].(Programming.Python.4th.Edition).Mark.Lutz.文字版

(yzsuai) #1
port has been made). Moreover, the Python web server classes used by the locally
running server deployed for this book still does not support HTTPS in Python 3.1—
the ultimate solution to web security, which I’ll say more about in a moment.


  • Because of all the foregoing, this fourth edition has legacy support for both rotor
    and PyCrypto if they are installed, but falls back on a simplistic password obfus-
    cator which may be different at each PyMailCGI installation. Since this release is
    something of a prototype in general, further refinement of this model, including
    support for HTTPS under more robust web servers, is left as exercise.


In general, there are a variety of approaches to encrypting information transferred back
and forth between client and server. Unfortunately again, none is easily implemented
for this chapter’s example, none is universally applicable, and most involve tools or
techniques that are well beyond the scope and size constraints of this text. To sample
some of the available options, though, the sections that follow contain a brief rundown
of some of the common techniques in this domain.


Manual data encryption: rotor (defunct)


In principle, CGI scripts can manually encrypt any sensitive data they insert into reply
streams, as PyMailCGI did in this book’s second edition. With the removal of the
rotor module, though, Python 2.4’s standard library has no encryption tools for this
task. Moreover, using the original rotor module’s code is not advisable from a main-
tenance perspective and would not be straightforward, since it was coded in the C
language (it’s not a simple matter of copying a .py file from a prior release). Unless you
are using an older version of Python, rotor is not a real option.


Mostly for historical interest and comparison today, this module was used as follows.
It was based on an Enigma-style encryption scheme: we make a new rotor object with
a key (and optionally, a rotor count) and call methods to encrypt and decrypt:


>>> import rotor
>>> r = rotor.newrotor('pymailcgi') # (key, [,numrotors])
>>> r.encrypt('abc123') # may return nonprintable chars
' \323an\021\224'

>>> x = r.encrypt('spam123') # result is same len as input
>>> x
'* _\344\011pY'
>>> len(x)
7
>>> r.decrypt(x)
'spam123'

Notice that the same rotor object can encrypt multiple strings, that the result may
contain nonprintable characters (printed as \ascii escape codes when displayed), and
that the result is always the same length as the original string. Most important, a string
encrypted with rotor can be decrypted in a different process (e.g., in a later CGI script)
if we re-create the rotor object:


Utility Modules | 1279
Free download pdf