Building PyCrypto with fastmath (gmp or mpir) via pip on Windows

pip, pycrypto, python, windows

Solution

The following one is a way to achieve your goal. There are other, probably better ways (e.g. based on Visual Studio), but this one has worked for me. Additionally, it does not use `pip`.

All operations are carried out on a command prompt.

- Install Mingw, including MSYS and the Development Toolkit. This will give you a fairly complete Unix-like development environment.

- Ensure that Mingw binaries are in PATH environment variable. You need `MinGW\bin` and `MingGW\msys\1.0\bin`.

- Download MPIR sources in a temporary directory. It is important you do not use 2.5.1 because of a bug that will break the build. 2.5.0 is fine.

- Build the MPIR library. This is fairly straightforward: execute `bash configure` followed by `make`.

- HACK #1 Copy `libmpir.a` from `mpir-2.5.0\.libs` into `C:\Python2.7.1\libs`. This is necessary because `distutils` is broken and I could not find a way to direct it to the correct library location.

- HACK #2 Edit `C:\Python2.7.1\Lib\distutils\cygwincompiler.py` and remove any occurrance of the string `-mno-cygwin`. The reason is explained here.

- Download PyCrypto sources and unpack them in another temporary directory.

- Set `CPPFLAGS` environment variable to the MPIR directory, which contains `mpir.h`.

HACK 3 Edit `setup.py` and add the following line in `build_extension` method:

self.__add_compiler_option(os.environ['CPPFLAGS'])

Run `bash configure`. You should see two lines saying:

checking for __gmpz_init in -lgmp... no checking for __gmpz_init in -lmpir... yes

- Execute `python setup.py build -c mingw32`. You should see no errors.

- Execute `python setup.py test` to verify that everything is fine.

- Execute `python setup.py install` to copy the files into your local Python repository.

- Alternatively, run `python setup.py bdist_wininst` to create an installer.

I really hate all the various hacks, and I'd love to hear if they can be avoided.

Problem

I installed PyCrypto on Windows via pip but i was not able to build Crypto.PublicKey._fastmath because GMP was not found. I know there is a binary version on voidspace but i would like to build the latest version of PyCrypto

Original source