Python - Our key to Efficiency

mxCrypto - Wrapping OpenSSL's cryptographic algorithms


Interface : Ciphers : Hashes : Utils : Examples : Structure : Download & Installation : Copyright & License : History : Home Version 0.2.0

Introduction


    Please note that you can get a more up-to-date version of the newly merged code of mxCrypto and Andrew Kuchling's pycrypt lib from Andrew's site as "amkCrypto". mxCrypto will revive, once I find time for it again...

    A while ago I started getting interested in Andrew Kuchling's pycrypt package. This was mainly because I had some plans for implementing secure channels from a clients local server to the webserver. The connection going via HTTP through the firewalls to the server. Unfortunately, Andrew's package falls under the US ITAR export restrictions and he can only make the non-encrypting parts of the package available for export.

    Since I wanted to use his package which I find very well structured, I had to find a way to fill in the blanks. Basically these three options were available:

    1. Print the missing parts in the US, ship them to somewhere outside the US and scan them in again (this is how PGP gets exported). I tried that approach and it failed horribly.
    2. Gather all the bits and pieces from different sources and reassemble them to work with his package structure. This would have caused serious support headaches.
    3. Take an existing crypto lib and wrap it, e.g. OpenSSL (the OpenSSL project took over the SSLeay development after Eric was hired by RSA Inc. Australia).

    I decided to take the third approach. OpenSSL is well supported, distributed world-wide and has a set of very fast implementations for most of the parts missing in Andrew's export version of pycrypt. So here goes: a wrapper for the ciphers and hash functions in the fantastic OpenSSL library.

Interface

    The package is called mx.Crypto and includes these subpackages:

    It currently does not define an interface on its own.

    Note that you can also access the ciphers and hash functions through Andrew's package if you have installed the package following the instructions given below. The documentation given here is merely provided to point out minor differences between pycrypt's interface and mxCrypto's.

Ciphers submodule

    This subpackage wraps the cipher algorithms available in OpenSSL in a way that is nearly 100% compatible with what Andrew has implemented in his package.

    All ciphers are provided as objects with a common interface:

    Cipher Constructors

      These constructors are available in the Ciphers subpackage (DEFAULT_MODE and DEFAULT_IV are explained below):

      RC2(key, mode=DEFAULT_MODE, IV=DEFAULT_IV)
      Implements the RC2 block cipher. See RFC 2268 for details.

      RC4(key, mode=DEFAULT_MODE)
      Implements the RC4 stream cipher. For details see Andrew's documentation.

      RC5(key, mode=DEFAULT_MODE, IV=DEFAULT_IV, rounds=16, version=0x10, wordsize=32)
      Implements the RC5 block cipher. version and wordsize are dummy arguments. See RFC 2040 for details.

      Blowfish(key, mode=DEFAULT_MODE, IV=DEFAULT_IV)
      Implements the free unpatented Blowfish block cipher. For details see Andrew's documentation.

      IDEA(key, mode=DEFAULT_MODE, IV=DEFAULT_IV)
      Implements the IDEA block cipher. For details see Andrew's documentation.

      DES(key, mode=DEFAULT_MODE, IV=DEFAULT_IV)
      Implements the DES block cipher. For details see Andrew's documentation.

      DES3(key, mode=DEFAULT_MODE, IV=DEFAULT_IV)
      Implements the TripleDES block cipher. For details see Andrew's documentation.

      CAST(key, mode=DEFAULT_MODE, IV=DEFAULT_IV)
      Implements the free unpatented CAST block cipher. See RFC 2144 for details.
      Note: The OpenSSL implementation of CAST in versions prior to 0.9.1c only supports keysizes of 11-16 bytes. It also works with smaller keys, but uses 16 rounds instead of 12 as defined in the RFC. The package will raise an error if you use keys of size 5-10 bytes. OpenSSL 0.9.1c fixes this bug.

    Cipher Instance Methods

      All cipher objects provide a similar interface. They define at least these methods:

      encrypt(string)
      Returns the encrypted string. Block ciphers will generally expect the string to have a multiple of their blocksize as length while stream ciphers can handle arbitrary length strings. The internal state of the cipher object is updated according to the mode set at creation time.

      decrypt(string)
      Returns the decrypted string. This is the inverse of the encrypt method.

      The DES and DES3 objects also define this method:

      isWeak()
      Returns 1 iff the key given to the constructor falls into the class of weak (meaning more easily breakable) keys, 0 otherwise. The chances of picking a weak key are very low, so you might as well not check for them.

    Cipher Instance Variables

      Ciphers define these instance variables:

      blocksize (readonly)
      Is 1 for stream ciphers and gives the blocksize for block ciphers (usually 8 bytes).

      keysize (readonly)
      Is 0 for stream ciphers and gives the keysize for block ciphers (usually between 8 and 16 bytes).

      mode (readonly)
      Mode the cipher operates in.

      IV
      Gives access to the initial vector used for the encryption. This may be written to while performing encryption to reset the cipher to a new initial state.

    Constants

      These constants are available:

      ECB, CBC, CFB
      Mode constants. See Andrew's documentation for more details.

      DEFAULT_MODE = ECB
      Default mode used when no mode is given on the constructors.

      DEFAULT_IV
      Default initial vector used when no IV is given on the constructors; it is set to '\0'*cipher.blocksize.

Hashes submodule

Utils submodule

    This subpackage provides some handy helper functions:

    str2hex(string)
    Takes a string and converts each byte to a 2-byte lowercase HEX representation. The resulting string is twice as long as the original one.

    hex2str(hexstring)
    Inverse of str2hex(). This function expects a HEX encoded string (2 HEX characters / byte). Case is not important. The result is returned as string.

Examples of Use

    Here is a very simple one:

    from mx.Crypto.Ciphers import RC4
    from mx.Crypto.Utils import str2hex
    
    c = RC4('MyKey123')
    e = c.encrypt('Hello World!')
    print 'Less readable:',str2hex(e)
    c = RC4('MyKey123')
    print 'More readable:',c.decrypt(e)
    

    This should the following output:

    Less readable: f166e053dd40552b97a9bc23
    More readable: Hello World!
    

    For more elaborate examples of how to use the ciphers and hash functions, have a look at the Examples/ subdirectory of the package.

    Small highlight: It includes a script which let's you en/decrypt files of any size. (Use with care though: the script is not well tested yet.) To see all options run 'python cipher.py -h'. The script shows how to deal with blocksizes, padding and writing cipher independant code.

Package Structure

    [mx.Crypto]
           Doc/
           [Examples]
                  CommandLine.py
                  cipher.py
           [mxCrypto]
                  test.py
           Ciphers.py
           Hashes.py
           Utils.py
    	

    Entries enclosed in brackets are packages (i.e. they are directories that include a __init__.py file). Ones without brackets are just simple subdirectories that are not accessible via import.

    The package imports all symbols from the extension module mxCrypto, so you only need to 'import mx.Crypto' to start working.

Installation

    The package needs two other packages to be compiled and installed first:

    1. Andrew Kuchling's export version of the pycrypt package version 1.1a2 or above and

    2. OpenSSL version 0.9.3 or above.

    Next, download the archive (located on a US server, but doesn't contain any cryptographic code itself, only hooks to OpenSSL) and then follow these steps (assuming you have already installed Python):

    1. Unzip the archive in a directory on your Python path e.g. /usr/local/lib/python1.5/site-packages/ on Unix or C:\Python\Lib\ under Windows

    2. Change to the mxCrypto subdirectory of the package and run make -f Makefile.pre.in boot

    3. Edit Setup and fix the paths to OpenSSL if necessary.

    4. Run make. This is likely to produce some warnings that are related to SWIG. You can safely ignore them.

    5. Unzip the included file pycrypt.zip in the Crypto installation directory of Andrew's export package (the package has to be compiled and tested for this to work; answer yes when asked to overwrite existing files) and follow the instructions in Hash/README.mxCrypto and Cipher/README.mxCrypto

    6. Get Python 1.5 or above running and execute mx/Crypto/mxCrypto/test.py; it should not report any errors

    7. Give me feedback :-)

    Choosing a C++ compiler:

    Since the wrapping code is written in C++ and uses exceptions you may run into trouble compiling it. Be sure to use the latest versions of your compiler (e.g. gcc 2.8.1 was reported to have no problems; the sparcworks CC fails to handle member constructors and gcc 2.7.2 doesn't handle exceptions). I'm using the latest egcs release without any difficulties. You can set the compiler by editing the Setup file.

    Getting unresolved symbols while linking mxCrypto:

    Some compilers fail to automatically link C++ object files with the standard C++ lib. If you run into problems with the linker reporting undefined symbols, edit the Setup file and enable those libs by hand; then try to run the make command again. If this still doesn't help, I suggest using the latest egcs compiler (egcs is an improved gcc compiler which solves several problems gcc has with C++) which is what I am using.

    Bug reports:

    Please report any bugs or quirks, etc. directly to me.

What I'd like to hear from you...

    • Does the package compile out of the box for you ?

Copyrights, Disclaimer and Credits

    © 1998-2000, Copyright by Marc-André Lemburg; All Rights Reserved. mailto: mal@lemburg.com

    © 2000, Copyright by eGenix.com Software GmbH, Langenfeld, Germany; All Rights Reserved. mailto: info@egenix.com

    Note that your country's laws may restrict usage, copying and distribution of software that provides interfaces to data encryption algorithms.

    This software is covered by the eGenix.com Public License Agreement. The text of the license is also included as file "LICENSE" in the package's main directory.

    By downloading, copying, installing or otherwise using the software, you agree to be bound by the terms and conditions of the eGenix.com Public License Agreement.


    To give you a quick overview of what the copyright conditions of the involved packages are I've copied the notices from latest versions I could find (they may be subject to change):

    Andrew's pycrypt package (export version 1.1a2):

    Distribute and use freely; there are no restrictions on further dissemination and usage except those imposed by the laws of your country of residence. This software is provided "as is" without warranty of fitness for use or suitability for any purpose, express or implied. Use at your own risk or not at all.

    Note: The package also includes software written by third parties. See the included docs for credits and further copyright information. AFAIK, mxCrypto replaces most (if not all) code included in the export version that was not written or modified by Andrew Kuchling with versions provided by OpenSSL.

    OpenSSL License:

    OpenSSL uses a dual license since it inherited the code base from Eric Young's SSLeay. Both licenses are BSD-style Open Source licenses.

    OpenSSL License:

    Copyright (c) 1998-1999 The OpenSSL Project. All rights reserved.

    Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

    1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.

    2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

    3. All advertising materials mentioning features or use of this software must display the following acknowledgment: "This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit. (http://www.openssl.org/)"

    4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to endorse or promote products derived from this software without prior written permission. For written permission, please contact openssl-core@openssl.org.

    5. Products derived from this software may not be called "OpenSSL" nor may "OpenSSL" appear in their names without prior written permission of the OpenSSL Project.

    6. Redistributions of any form whatsoever must retain the following acknowledgment: "This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/)"

    THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE OpenSSL PROJECT OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ====================================================================

    This product includes cryptographic software written by Eric Young (eay@cryptsoft.com). This product includes software written by Tim Hudson (tjh@cryptsoft.com).

    Original SSLeay License:

    Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com) All rights reserved.

    This package is an SSL implementation written by Eric Young (eay@cryptsoft.com). The implementation was written so as to conform with Netscapes SSL.

    This library is free for commercial and non-commercial use as long as the following conditions are aheared to. The following conditions apply to all code found in this distribution, be it the RC4, RSA, lhash, DES, etc., code; not just the SSL code. The SSL documentation included with this distribution is covered by the same copyright terms except that the holder is Tim Hudson (tjh@cryptsoft.com).

    Copyright remains Eric Young's, and as such any Copyright notices in the code are not to be removed. If this package is used in a product, Eric Young should be given attribution as the author of the parts of the library used. This can be in the form of a textual message at program startup or in documentation (online or textual) provided with the package.

    Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

    1. Redistributions of source code must retain the copyright notice, this list of conditions and the following disclaimer.

    2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

    3. All advertising materials mentioning features or use of this software must display the following acknowledgement: "This product includes cryptographic software written by Eric Young (eay@cryptsoft.com)" The word 'cryptographic' can be left out if the rouines from the library being used are not cryptographic related :-).

    4. If you include any Windows specific code (or a derivative thereof) from the apps directory (application code) you must include an acknowledgement: "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"

    THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

    The licence and distribution terms for any publically available version or derivative of this code cannot be changed. i.e. this code cannot simply be copied and put under another distribution licence [including the GNU Public Licence.]

History & Future


© 1998-2000, Copyright by Marc-André Lemburg; All Rights Reserved. mailto: mal@lemburg.com

© 2000, Copyright by eGenix.com Software GmbH; All Rights Reserved. mailto: info@egenix.com