Installing PyCrypto on Windows (or how to build installers for libraries with C-modules)

Saturday 05 December 2009, 16:49:00 | python

PyCrypto is a Python Cryptography Toolkit, providing various cryptological things such as hashes, encryption, and random number utilities.

It contains various files that need to be compiled as a C-module.

On Linux and Mac OS this is no problem at all because they provide a working C compiler (gcc) but on Windows you're stuck. I've found that the easiest way to get this going is by installing the MingW gcc compiler. I don't think Cygwin wil work because that will introduce a dependency on the cygwin dlls, while MingW doesn't (it produces stand-alone binaries).

More to the point: I installed the GCC/MingW compiler using the bundled installer from TDM. It contains a very up to date set of gcc and companion tools, and installs with just a few clicks.

Add the MingW bin directory to your PATH and check if you have gcc available:

F:\> set PATH=C:\MingW\bin;%PATH%

F:\> gcc --version
gcc (TDM-2 mingw32) 4.4.1
Copyright (C) 2009 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

That's it. Python's distutils is smart enough nowadays to be able to work with the MingW compiler (if you tell it to), so I can now simply type

F:\pycrypto-2.1.0b1> python setup.py build -c mingw32
F:\pycrypto-2.1.0b1> python setup.py bdist_wininst
F:\pycrypto-2.1.0b1> dir /b dist
pycrypto-2.1.0b1.win32-py2.6.exe

There you go, a windows installation package. You can either use that to install PyCrypto or just type python setup.py install at the prompt.

You can also tell distutils to always use mingw32 as a compiler by creating the file distutils.cfg in the distutils package directory in the Python standard lib, with the following contents:

[build]
compiler = mingw32

You no longer have to manually perform the build step and provide the -c mingw32 argument because distutils can now build automatically.

I think you need at least Python 2.5 to get all this to work as described above. I am using 2.6 and it's working flawlessly so far. Haven't tried it with older versions.

Note: the above still works with Pycrypto-2.1.0 (little update since beta). Also I am on 64 bits windows but I'm using 32 bit Python and 32 bit mingw.

People have replied:

Gutest

2010-04-24 00:11:00

Nice write up. Thank you!

Irmen de Jong

2010-04-24 00:28:00

You're welcome. I heard of some gotchas when you use mingw to compile extensions for Python, it seems that obscure conflicts can occur if you're passing stuff around that depends on the c stdlib (such as FILE handles) because mingw has a different clib than Visual C. I haven't encountered any problems myself yet, thankfully.