Building PyCrypto with fastmath (gmp or mpir) via

2020-06-18 04:27发布

问题:

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

回答1:

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.

  1. Install Mingw, including MSYS and the Development Toolkit. This will give you a fairly complete Unix-like development environment.
  2. Ensure that Mingw binaries are in PATH environment variable. You need MinGW\bin and MingGW\msys\1.0\bin.
  3. 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.
  4. Build the MPIR library. This is fairly straightforward: execute bash configure followed by make.
  5. 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.
  6. 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.
  7. Download PyCrypto sources and unpack them in another temporary directory.
  8. Set CPPFLAGS environment variable to the MPIR directory, which contains mpir.h.
  9. HACK 3 Edit setup.py and add the following line in build_extension method:

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

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

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

  11. Execute python setup.py build -c mingw32. You should see no errors.
  12. Execute python setup.py test to verify that everything is fine.
  13. Execute python setup.py install to copy the files into your local Python repository.
  14. 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.