How to install pycrypto on windows

I've read every other google source and SO thread, with nothing working. Python 2.7.3 32bit installed on Windows 7 64bit. Download, extracting, and then trying to install PyCrypto results in "Unab...

I’ve read every other google source and SO thread, with nothing working.

Python 2.7.3 32bit installed on Windows 7 64bit. Download, extracting, and then trying to install PyCrypto results in "Unable to find vcvarsall.bat".

So I install MinGW and tack that on the install line as the compiler of choice. But then I get the error "RuntimeError: chmod error".

How in the world do I get around this? I’ve tried using pip, which gives the same result. I found a prebuilt PyCrypto 2.3 binary and installed that, but it’s nowhere to be found on the system (not working).

Any ideas?

asked Jul 10, 2012 at 1:44

Coldblackice's user avatar

ColdblackiceColdblackice

3,4304 gold badges20 silver badges22 bronze badges

8

If you don’t already have a C/C++ development environment installed that is compatible with the Visual Studio binaries distributed by Python.org, then you should stick to installing only pure Python packages or packages for which a Windows binary is available.

Fortunately, there are PyCrypto binaries available for Windows:
http://www.voidspace.org.uk/python/modules.shtml#pycrypto

UPDATE:
As @Udi suggests in the comment below, the following command also installs pycrypto and can be used in virtualenv as well:

easy_install http://www.voidspace.org.uk/python/pycrypto-2.6.1/pycrypto-2.6.1.win32-py2.7.exe

Notice to choose the relevant link for your setup from this list

If you’re looking for builds for Python 3.5, see PyCrypto on python 3.5

Community's user avatar

answered Jul 10, 2012 at 2:19

Michael Dillon's user avatar

Michael DillonMichael Dillon

31.7k5 gold badges70 silver badges105 bronze badges

9

After years and years, python finally agreed for a binary disribution called wheel which allows to install even binary extensions on Windows without having a compiler with simple pip install packagename. There is a list of popular packages with their status. Pycrypto is not there yet, but lxml, PySide and Scrapy for example.

Edited Nov 2015: pip uninstall pycrypto & pip install pycryptodome. It is a pycrypto fork with new features and it supports wheel. It replaces pycrypto, so existing code will continue to work (see https://pycryptodome.readthedocs.org/en/latest/src/examples.html)

answered Dec 7, 2014 at 5:21

Smit Johnth's user avatar

Smit JohnthSmit Johnth

2,0811 gold badge21 silver badges15 bronze badges

Microsoft has recently recently released a standalone, dedicated Microsoft Visual C++ Compiler for Python 2.7. If you’re using Python 2.7, simply install that compiler and Setuptools 6.0 or later, and most packages with C extensions will now compile readily.

answered Dec 6, 2014 at 1:22

Jason R. Coombs's user avatar

Jason R. CoombsJason R. Coombs

40.3k10 gold badges80 silver badges88 bronze badges

3

For VS2010:

SET VS90COMNTOOLS=%VS100COMNTOOLS%

For VS2012:

SET VS90COMNTOOLS=%VS110COMNTOOLS%

then Call:

pip install pyCrypto 

answered Jun 6, 2013 at 7:09

Chandan's user avatar

ChandanChandan

7466 silver badges8 bronze badges

4

In general

vcvarsall.bat is part of the Visual C++ compiler, you need that to install what you are trying to install. Don’t even try to deal with MingGW if your Python was compiled with Visual Studio toolchain and vice versa. Even the version of the Microsoft tool chain is important. Python compiled with VS 2008 won’t work with extensions compiled with VS 2010!

You have to compile PyCrypto with the same compiler that the version of Python was compiled with. Google for «Unable to find vcvarsall.bat» because that is the root of your problem, it is a very common problem with compiling Python extensions on Windows.

There is a lot of information and a lot to read to get this right on whatever system you are on with this link.

Beware using Visual Studio 2010 or not using Visual Studio 2008

As far as I know the following is still true. This was posted in the link above in June, 2010 referring to trying to build extensions with VS 2010 Express against the Python installers available on python.org.

Be careful if you do this. Python 2.6 and 2.7 from python.org are
built with Visual Studio 2008 compilers. You will need to link with
the same CRT (msvcr90.dll) as Python.

Visual Studio 2010 Express links with the wrong CRT version:
msvcr100.dll.

If you do this, you must also re-build Python with Visual Studio 2010
Express. You cannot use the standard Python binary installer for
Windows. Nor can you use any C/C++ extensions built with a different
compiler than Visual Studio 2010 (Express).

Opinion: This is one reason I abandoned Windows for all serious development work for OSX!

Community's user avatar

answered Jul 10, 2012 at 1:54

3

PyCryptodome is an almost-compatible fork of PyCrypto with Windows wheels available on pypi.

You can install it with a simple:

pip install pycryptodome

The website includes instructions to build it from sources with the Microsoft compilers too.

answered Sep 20, 2015 at 7:25

SquareRootOfTwentyThree's user avatar

0

I have managed to get pycrypto to compile by using MinGW32 and MSYS. This presumes that you have pip or easy_install installed.

Here’s how I did it:

1) Install MinGW32. For the sake of this explanation, let’s assume it’s installed in C:MinGW. When using the installer, which I recommend, select the C++ compiler. MSYS should install with MinGW

2) Add c:mingwbin,c:mingwmingw32bin,C:MinGWmsys1.0, c:mingwmsys1.0bin and c:mingwmsys1.0sbin to your %PATH%. If you aren’t familiar, this article is very helpful.

3) From the search bar, run msys and the MSYS terminal will open. For those familiar with Cygwin, it works in a similar fashion.

4) From within the MSYS terminal pip install pycrypto should run without error after this.

Community's user avatar

answered Jan 22, 2014 at 19:17

darnold0714's user avatar

1

For Windows 7:

To install Pycrypto in Windows,

Try this in Command Prompt,

Set path=C:Python27Scripts (i.e path where easy_install is located)

Then execute the following,

easy_install pycrypto

For Ubuntu:

Try this,

Download Pycrypto from «https://pypi.python.org/pypi/pycrypto»

Then change your current path to downloaded path using your terminal and user should be root:

Eg: root@xyz-virtual-machine:~/pycrypto-2.6.1#

Then execute the following using the terminal:

python setup.py install

It’s worked for me. Hope works for all..

answered Apr 12, 2015 at 9:46

JayaPrakash's user avatar

1

For those of you looking for python 3.4 I found a git repo with an installer that just works. Here are the direct links for x64 and x32

answered Jul 13, 2015 at 14:50

user25064's user avatar

user25064user25064

1,9502 gold badges15 silver badges27 bronze badges

If you are on Windows and struggling with installing Pycrypcto just use the:
pip install pycryptodome.
It works like a miracle and it will make your life much easier than trying to do a lot of configurations and tweaks.

answered May 22, 2019 at 8:30

John's user avatar

JohnJohn

1932 silver badges7 bronze badges

It’s possible to build PyCrypto using the Windows 7 SDK toolkits. There are two versions of the Windows 7 SDK. The original version (for .Net 3.5) includes the VS 2008 command-line compilers. Both 32- and 64-bit compilers can be installed.

The first step is to compile mpir to provide fast arithmetic. I’ve documented the process I use in the gmpy library. Detailed instructions for building mpir using the SDK compiler can be found at sdk_build

The key steps to use the SDK compilers from a DOS prompt are:

1) Run either vcvars32.bat or vcvars64.bat as appropriate.

2) At the prompt, execute «set MSSdk=1»

3) At the prompt, execute «set DISTUTILS_USE_SDK=1»

This should allow «python setup.py install» to succeed assuming there are no other issues with the C code. But I vaaguely remember that I had to edit a couple of PyCrypto files to enable mpir and to find the mpir libraries but I don’t have my Windows system up at the moment. It will be a couple of days before I’ll have time to recreate the steps. If you haven’t reported success by then, I’ll post the PyCrypto steps. The steps will assume you were able to compile mpir.

I hope this helps.

answered Jul 10, 2012 at 7:21

casevh's user avatar

casevhcasevh

11k1 gold badge24 silver badges34 bronze badges

So I install MinGW and tack that on the install line as the compiler
of choice. But then I get the error «RuntimeError: chmod error».

This error "RuntimeError: chmod error" occurs because the install script didn’t find the chmod command.

How in the world do I get around this?

Solution

You only need to add the MSYS binaries to the PATH and re-run the install script.

(N.B: Note that MinGW comes with MSYS so )

Example

For example, if we are in folder C:<..>pycrypto-2.6.1distpycrypto-2.6.1>

C:.....>set PATH=C:MinGWmsys1.0bin;%PATH%
C:.....>python setup.py install

Optional: you might need to clean before you re-run the script:

`C:<..>pycrypto-2.6.1distpycrypto-2.6.1> python setup.py clean`

answered Sep 24, 2014 at 10:11

Bludzee's user avatar

BludzeeBludzee

2,7035 gold badges37 silver badges46 bronze badges

  1. Go to «Microsoft Visual C++ Compiler for Python 2.7» and continue based on «System Requirements» (this is what I did to put below steps together).

  2. Install setuptools (setuptools 6.0 or later is required for Python to automatically detect this compiler package)
    either by: pip install setuptools
    or download «Setuptools bootstrapping installer» source from, save this file somwhere on your filestystem as «ez_python.py» and install with: python ez_python.py

  3. Install wheel (wheel is recommended for producing pre-built binary packages). You can install it with: pip install wheel

  4. Open Windows elevated Command Prompt cmd.exe (with «Run as administrator») to install «Microsoft Visual C++ Compiler for Python 2.7» for all users. You can use following command to do so: msiexec /i C:usersjozkodownloadVCForPython27.msi ALLUSERS=1 just use your own path to file: msiexec /i <path to MSI> ALLUSERS=1

  5. Now you should be able to install pycrypto with: pip install pycrypto

answered Jul 30, 2016 at 22:02

damian1baran's user avatar

damian1barandamian1baran

1,2871 gold badge14 silver badges13 bronze badges

My answer might not be related to problem mention here, but I had same problem with Python 3.4 where Crypto.Cipher wasn’t a valid import. So I tried installing PyCrypto and went into problems.

After some research I found with 3.4 you should use pycryptodome.

I install pycryptodome using pycharm and I was good.

from Crypto.Cipher import AES

answered Aug 18, 2017 at 17:01

Virendra Patel's user avatar

0

This probably isn’t the optimal solution but you might download and install the free Visual C++ Express package from MS. This will give you the C++ compiler you need to compile the PyCrypto code.

answered Jul 10, 2012 at 1:51

sizzzzlerz's user avatar

sizzzzlerzsizzzzlerz

4,2153 gold badges26 silver badges35 bronze badges

So I install MinGW and tack that on the install line as the compiler of choice. But then I get the error «RuntimeError: chmod error».

You need to install msys package under MinGW

enter image description here

and add following entries in your PATH env variable.

  • C:MinGWbin
  • C:MinGWmsys1.0bin [This is where you will find chmod executable]

Then run your command from normal windows command prompt.

answered Apr 26, 2015 at 17:47

Aniket Thakur's user avatar

Aniket ThakurAniket Thakur

65.5k37 gold badges276 silver badges288 bronze badges

Step 1: Install Visual C++ 2010 Express from
here.

(Do not install Microsoft Visual Studio 2010 Service Pack 1 )

Step 2: Remove all the Microsoft Visual C++ 2010 Redistributable packages from Control PanelPrograms and Features. If you don’t do those then the install is going to fail with an obscure «Fatal error during installation» error.

Step 3: Install offline version of Windows SDK for Visual Studio 2010 (v7.1) from here.
This is required for 64bit extensions. Windows has builtin mounting for ISOs like Pismo.

Step 4: You need to install the ISO file with Pismo File Mount Audit Package. Download Pismo from here

Step 5: Right click the downloaded ISO file and choose mount with Pismo. Thereafter, install the SetupSDKSetup.exe instead of setup.exe.

Step 6a: Create a vcvars64.bat file in C:Program Files (x86)Microsoft Visual Studio 10.0VCbinamd64 by changing directory to C:Program Files (x86)Microsoft Visual Studio versionVC on the command prompt.
Type command on the command prompt:
cd C:Program Files (x86)Microsoft Visual Studio versionVCr

Step 6b:
To configure this Command Prompt window for 64-bit command-line builds that target x86 platforms, at the command prompt, enter:
vcvarsall x86 Click here for more options.

Step 7: At the command prompt, install the PyCrypto by typing:
C:Python3X>pip install -U your_wh_file

answered Feb 8, 2018 at 4:45

Asubiaro Toluwase Victor's user avatar

I had Pycharm for python.

  1. Go to pycharm -> file -> setting -> project interpreter

  2. Click on +

  3. Search for "pycrypto" and install the package

Note: If you don’t have «Microsoft Visual C++ Compiler for Python 2.7» installed then it will prompt for installation, once installation finished try the above steps it should work fine.

Ivan's user avatar

Ivan

31.1k7 gold badges50 silver badges92 bronze badges

answered Jul 4, 2018 at 14:32

RAKESH's user avatar

⚠️ WARNING
PyCrypto 2.x is unmaintained, obsolete, and contains security vulnerabilities.
See https://www.pycrypto.org/ for details. The following is provided for historical/reference purposes only.

Python Cryptography Toolkit (pycrypto)

This is a collection of both secure hash functions (such as SHA256 and
RIPEMD160), and various encryption algorithms (AES, DES, RSA, ElGamal,
etc.). The package is structured to make adding new modules easy.
This section is essentially complete, and the software interface will
almost certainly not change in an incompatible way in the future; all
that remains to be done is to fix any bugs that show up. If you
encounter a bug, please report it in the GitHub issue tracker at
https://github.com/dlitz/pycrypto/issues

An example usage of the SHA256 module is:

>>> from Crypto.Hash import SHA256
>>> hash = SHA256.new()
>>> hash.update('message')
>>> hash.digest()
'xabSnx13xe4Yx14x98+yxf9xb7xe3xfbxa9x94xcfxd1xf3xfb"xf7x1cxeax1axfbxf0+Fx0cmx1d'

An example usage of an encryption algorithm (AES, in this case) is:

>>> from Crypto.Cipher import AES
>>> obj = AES.new('This is a key123', AES.MODE_CBC, 'This is an IV456')
>>> message = "The answer is no"
>>> ciphertext = obj.encrypt(message)
>>> ciphertext
'xd6x83x8dd!VTx92xaa`Ax05xe0x9bx8bxf1'
>>> obj2 = AES.new('This is a key123', AES.MODE_CBC, 'This is an IV456')
>>> obj2.decrypt(ciphertext)
'The answer is no'

One possible application of the modules is writing secure
administration tools. Another application is in writing daemons and
servers. Clients and servers can encrypt the data being exchanged and
mutually authenticate themselves; daemons can encrypt private data for
added security. Python also provides a pleasant framework for
prototyping and experimentation with cryptographic algorithms; thanks
to its arbitrary-length integers, public key algorithms are easily
implemented.

As of PyCrypto 2.1.0, PyCrypto provides an easy-to-use random number
generator:

>>> from Crypto import Random
>>> rndfile = Random.new()
>>> rndfile.read(16)
'xf7.x838{x85xa0xd3>#}xc6xc2jJU'

A stronger version of Python’s standard «random» module is also
provided:

>>> from Crypto.Random import random
>>> random.choice(['dogs', 'cats', 'bears'])
'bears'

Caveat: For the random number generator to work correctly, you must
call Random.atfork() in both the parent and child processes after
using os.fork()

Installation

PyCrypto is written and tested using Python version 2.1 through 3.3. Python
1.5.2 is not supported.

The modules are packaged using the Distutils, so you can simply run
python setup.py build to build the package, and «python setup.py
install» to install it.

Linux installation requires the Python developer tools to be installed. These
can be found in the python-dev package on Debian/Ubuntu and the
python2-devel package on Red Hat/Fedora. If you are using a non-standard
Python version for your distribution, you may require a different package.
Consult your package manager’s documentation for instructions on how to
install these packages. Other distributions may have different package names.

To verify that everything is in order, run python setup.py test. It
will test all the cryptographic modules, skipping ones that aren’t
available. If the test script reports an error on your machine,
please report the bug using the bug tracker (URL given above). If
possible, track down the bug and include a patch that fixes it,
provided that you are able to meet the eligibility requirements at
https://www.pycrypto.org/submission-requirements/.

It is possible to test a single sub-package or a single module only, for instance
when you investigate why certain tests fail and don’t want to run the whole
suite each time. Use python setup.py test --module=name, where ‘name’
is either a sub-package (Cipher, PublicKey, etc) or a module (Cipher.DES,
PublicKey.RSA, etc).
To further cut test coverage, pass also the option --skip-slow-tests.

To install the package under the site-packages directory of
your Python installation, run python setup.py install.

If you have any comments, corrections, or improvements for this
package, please report them to our mailing list, accessible via the
PyCrypto website:

https://www.pycrypto.org/
https://www.dlitz.net/software/pycrypto/

Python Cryptography Toolkit (pycrypto)

This is a collection of both secure hash functions (such as SHA256 and
RIPEMD160), and various encryption algorithms (AES, DES, RSA, ElGamal,
etc.). The package is structured to make adding new modules easy.
This section is essentially complete, and the software interface will
almost certainly not change in an incompatible way in the future; all
that remains to be done is to fix any bugs that show up. If you
encounter a bug, please report it in the Launchpad bug tracker at

https://launchpad.net/products/pycrypto/+bugs

An example usage of the SHA256 module is:

>>> from Crypto.Hash import SHA256
>>> hash = SHA256.new()
>>> hash.update('message')
>>> hash.digest()
'xabSnx13xe4Yx14x98+yxf9xb7xe3xfbxa9x94xcfxd1xf3xfb"xf7x1cxeax1axfbxf0+Fx0cmx1d'

An example usage of an encryption algorithm (AES, in this case) is:

>>> from Crypto.Cipher import AES
>>> obj = AES.new('This is a key123', AES.MODE_CBC, 'This is an IV456')
>>> message = "The answer is no"
>>> ciphertext = obj.encrypt(message)
>>> ciphertext
'xd6x83x8dd!VTx92xaa`Ax05xe0x9bx8bxf1'
>>> obj2 = AES.new('This is a key123', AES.MODE_CBC, 'This is an IV456')
>>> obj2.decrypt(ciphertext)
'The answer is no'

One possible application of the modules is writing secure
administration tools. Another application is in writing daemons and
servers. Clients and servers can encrypt the data being exchanged and
mutually authenticate themselves; daemons can encrypt private data for
added security. Python also provides a pleasant framework for
prototyping and experimentation with cryptographic algorithms; thanks
to its arbitrary-length integers, public key algorithms are easily
implemented.

As of PyCrypto 2.1.0, PyCrypto provides an easy-to-use random number
generator:

>>> from Crypto import Random
>>> rndfile = Random.new()
>>> rndfile.read(16)
'xf7.x838{x85xa0xd3>#}xc6xc2jJU'

A stronger version of Python’s standard “random” module is also
provided:

>>> from Crypto.Random import random
>>> random.choice(['dogs', 'cats', 'bears'])
'bears'

Caveat: For the random number generator to work correctly, you must
call Random.atfork() in both the parent and child processes after
using os.fork()

Installation

PyCrypto is written and tested using Python version 2.1 through 3.3. Python
1.5.2 is not supported.

The modules are packaged using the Distutils, so you can simply run
“python setup.py build” to build the package, and “python setup.py
install” to install it.

If the setup.py script crashes with a DistutilsPlatformError
complaining that the file /usr/lib/python2.2/config/Makefile doesn’t
exist, this means that the files needed for compiling new Python
modules aren’t installed on your system. Red Hat users often run into
this because they don’t have the python2-devel RPM installed. The fix
is to simply install the requisite RPM. On Debian/Ubuntu, you need the
python-dev package.

To verify that everything is in order, run “python setup.py test”. It
will test all the cryptographic modules, skipping ones that aren’t
available. If the test script reports an error on your machine,
please report the bug using the bug tracker (URL given above). If
possible, track down the bug and include a patch that fixes it,
provided that you are able to meet the eligibility requirements at
http://www.pycrypto.org/submission-requirements/.

It is possible to test a single sub-package or a single module only, for instance
when you investigate why certain tests fail and don’t want to run the whole
suite each time. Use “python setup.py test –module=name”, where ‘name’
is either a sub-package (Cipher, PublicKey, etc) or a module (Cipher.DES,
PublicKey.RSA, etc).
To further cut test coverage, pass also the option “–skip-slow-tests”.

To install the package under the site-packages directory of
your Python installation, run “python setup.py install”.

If you have any comments, corrections, or improvements for this
package, please report them to our mailing list, accessible via the
PyCrypto website:

http://www.pycrypto.org/
https://www.dlitz.net/software/pycrypto/

I’m using Python 3.7 and Windows 10. ‘pip install pycrypto‘ doesn’t work with the following error:

(pyramid) C:ProjectsPyramid>pip install pycrypto
Collecting pycrypto
  Downloading https://files.pythonhosted.org/packages/60/db/645aa9af249f059cc3a368b118de33889219e0362141e75d4eaf6f80f163/pycrypto-2.6.1.tar.gz (446kB)
    100% |████████████████████████████████| 450kB 5.7MB/s
Installing collected packages: pycrypto
  Running setup.py install for pycrypto ... error

...
... purposely truncated
...    

    C:Program Files (x86)Windows Kits10include10.0.10240.0ucrtinttypes.h(26): error C2061: syntax error: identifier 'intmax_t'
    C:Program Files (x86)Windows Kits10include10.0.10240.0ucrtinttypes.h(27): error C2061: syntax error: identifier 'rem'
    C:Program Files (x86)Windows Kits10include10.0.10240.0ucrtinttypes.h(27): error C2059: syntax error: ';'
    C:Program Files (x86)Windows Kits10include10.0.10240.0ucrtinttypes.h(28): error C2059: syntax error: '}'
    C:Program Files (x86)Windows Kits10include10.0.10240.0ucrtinttypes.h(30): error C2061: syntax error: identifier 'imaxdiv_t'
    C:Program Files (x86)Windows Kits10include10.0.10240.0ucrtinttypes.h(30): error C2059: syntax error: ';'
    C:Program Files (x86)Windows Kits10include10.0.10240.0ucrtinttypes.h(40): error C2143: syntax error: missing '{' before '__cdecl'
    C:Program Files (x86)Windows Kits10include10.0.10240.0ucrtinttypes.h(41): error C2146: syntax error: missing ')' before identifier '_Number'
    C:Program Files (x86)Windows Kits10include10.0.10240.0ucrtinttypes.h(41): error C2061: syntax error: identifier '_Number'
    C:Program Files (x86)Windows Kits10include10.0.10240.0ucrtinttypes.h(41): error C2059: syntax error: ';'
    C:Program Files (x86)Windows Kits10include10.0.10240.0ucrtinttypes.h(42): error C2059: syntax error: ')'
    C:Program Files (x86)Windows Kits10include10.0.10240.0ucrtinttypes.h(45): error C2143: syntax error: missing '{' before '__cdecl'
    C:Program Files (x86)Windows Kits10include10.0.10240.0ucrtinttypes.h(46): error C2146: syntax error: missing ')' before identifier '_Numerator'
    C:Program Files (x86)Windows Kits10include10.0.10240.0ucrtinttypes.h(46): error C2061: syntax error: identifier '_Numerator'
    C:Program Files (x86)Windows Kits10include10.0.10240.0ucrtinttypes.h(46): error C2059: syntax error: ';'
    C:Program Files (x86)Windows Kits10include10.0.10240.0ucrtinttypes.h(46): error C2059: syntax error: ','
    C:Program Files (x86)Windows Kits10include10.0.10240.0ucrtinttypes.h(48): error C2059: syntax error: ')'
    C:Program Files (x86)Windows Kits10include10.0.10240.0ucrtinttypes.h(50): error C2143: syntax error: missing '{' before '__cdecl'
    C:Program Files (x86)Windows Kits10include10.0.10240.0ucrtinttypes.h(56): error C2143: syntax error: missing '{' before '__cdecl'
    C:Program Files (x86)Windows Kits10include10.0.10240.0ucrtinttypes.h(63): error C2143: syntax error: missing '{' before '__cdecl'
    C:Program Files (x86)Windows Kits10include10.0.10240.0ucrtinttypes.h(69): error C2143: syntax error: missing '{' before '__cdecl'
    C:Program Files (x86)Windows Kits10include10.0.10240.0ucrtinttypes.h(76): error C2143: syntax error: missing '{' before '__cdecl'
    C:Program Files (x86)Windows Kits10include10.0.10240.0ucrtinttypes.h(82): error C2143: syntax error: missing '{' before '__cdecl'
    C:Program Files (x86)Windows Kits10include10.0.10240.0ucrtinttypes.h(89): error C2143: syntax error: missing '{' before '__cdecl'
    C:Program Files (x86)Windows Kits10include10.0.10240.0ucrtinttypes.h(95): error C2143: syntax error: missing '{' before '__cdecl'
    error: command 'C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\BIN\x86_amd64\cl.exe' failed with exit status 2

    ----------------------------------------
Command "c:pythonvenvpyramidscriptspython.exe -u -c "import setuptools, tokenize;__file__='C:\Users\dariawan\AppData\Local\Temp\pip-install-wwb9aboq\pycrypto\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('rn', 'n');f.close();exec(compile(code, __file__, 'exec'))" install --record C:UsersdariawanAppDataLocalTemppip-record-x5wxv2qginstall-record.txt --single-version-externally-managed --compile --install-headers c:pythonvenvpyramidincludesitepython3.7pycrypto" failed with error code 1 in C:UsersdariawanAppDataLocalTemppip-install-wwb9aboqpycrypto

The file includepyport.h in Python installation directory does not have #include < stdint.h > anymore. This leaves intmax_t undefined.

A workaround for Microsoft VC compiler is to force include stdint.h via OS environment variable CL:

  • Open command prompt, and Setup VC environment by runing vcvars*.bat (choose file name depending on VC version and architecture)
C:Program Files (x86)Microsoft Visual Studio 14.0VC>vcvarsall.bat

  • set CL=-FI»Full-Pathstdint.h» (use real value for Full-Path for the environment)
C:Program Files (x86)Microsoft Visual Studio 14.0VC>set CL=-FI"%VCINSTALLDIR%INCLUDEstdint.h"

  • then, try to install pycrypto again:
(pyramid) C:ProjectsPyramid>pip install pycrypto
Collecting pycrypto
  Using cached https://files.pythonhosted.org/packages/60/db/645aa9af249f059cc3a368b118de33889219e0362141e75d4eaf6f80f163/pycrypto-2.6.1.tar.gz
Installing collected packages: pycrypto
  Running setup.py install for pycrypto ... done
Successfully installed pycrypto-2.6.1

Another option that I’ll try in future is to use PyCryptodome instead of pycrypto. pycrypto is discontinued and is no longer actively supported. PyCryptodome exposes almost the same API as pycrypto (source).

Reference: Microsoft Windows Python-3.6 PyCrypto installation error

The installation procedure depends on the package you want the library to be in.
PyCryptodome can be used as:

  1. An almost drop-in replacement for the old PyCrypto library.
    You install it with:

    In this case, all modules are installed under the Crypto package.
    You can test everything is right with:

    pip install pycryptodome-test-vectors
    python -m Crypto.SelfTest
    

    One must avoid having both PyCrypto and PyCryptodome installed
    at the same time, as they will interfere with each other.
    This option is therefore recommended only when you are sure that
    the whole application is deployed in a virtualenv.

  2. A library independent of the old PyCrypto.
    You install it with:

    pip install pycryptodomex
    

    You can test everything is right with:

    pip install pycryptodome-test-vectors
    python -m Cryptodome.SelfTest
    

    In this case, all modules are installed under the Cryptodome package.
    The old PyCrypto and PyCryptodome can coexist.

The procedures below go a bit more in detail, by explaining
how to setup the environment for compiling the C extensions
for each OS, and how to install the GMP library.

Compiling in Linux Ubuntu¶

Note

If you want to install under the Crypto package, replace
below pycryptodomex with pycryptodome.

For Python 2.x:

$ sudo apt-get install build-essential python-dev
$ pip install pycryptodomex
$ pip install pycryptodome-test-vectors
$ python -m Cryptodome.SelfTest

For Python 3.x:

$ sudo apt-get install build-essential python3-dev
$ pip install pycryptodomex
$ pip install pycryptodome-test-vectors
$ python3 -m Cryptodome.SelfTest

For PyPy:

$ sudo apt-get install build-essential pypy-dev
$ pip install pycryptodomex
$ pip install pycryptodome-test-vectors
$ pypy -m Cryptodome.SelfTest

Compiling in Linux Fedora¶

Note

If you want to install under the Crypto package, replace
below pycryptodomex with pycryptodome.

For Python 2.x:

$ sudo yum install gcc gmp python-devel
$ pip install pycryptodomex
$ pip install pycryptodome-test-vectors
$ python -m Cryptodome.SelfTest

For Python 3.x:

$ sudo yum install gcc gmp python3-devel
$ pip install pycryptodomex
$ pip install pycryptodome-test-vectors
$ python3 -m Cryptodome.SelfTest

For PyPy:

$ sudo yum install gcc gmp pypy-devel
$ pip install pycryptodomex
$ pip install pycryptodome-test-vectors
$ pypy -m Cryptodome.SelfTest

Windows (from sources)¶

Note

If you want to install under the Crypto package, replace
below pycryptodomex with pycryptodome. That being the case and if you want to run the test, instead of Cryptodome.SelfTest, run Crypto.SelfTest.

Windows does not come with a C compiler like most Unix systems.
The simplest way to compile the PyCryptodome extensions from
source code is to install the minimum set of Visual Studio
components freely made available by Microsoft.

  1. [Once only] Download Build Tools for Visual Studio 2019.
    In the installer, select the C++ build tools, the Windows 10 SDK, and the latest version of MSVC v142 x64/x86 build tools.

  2. Compile and install PyCryptodome:

    > pip install pycryptodomex --no-binary :all:
    
  3. To make sure everything work fine, run the test suite:

    > pip install pycryptodome-test-vectors
    > python -m Cryptodome.SelfTest
    

Documentation¶

Project documentation is written in reStructuredText and it is stored under Doc/src.
To publish it as HTML files, you need to install sphinx and
use:

It will then be available under Doc/_build/html/.

PGP verification¶

All source packages and wheels on PyPI are cryptographically signed.
They can be verified with the following PGP key:

-----BEGIN PGP PUBLIC KEY BLOCK-----

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
=DpoI
-----END PGP PUBLIC KEY BLOCK-----

Last week, the instructor of ICS 444 has gave us new assignment. In the assignment, it is required to use one of Python cryptographic libraries. As for me, I have decided to use a library called PyCrypto. In this blog post, I will be discussing the following topics regarding the selected library:

  1. Installing the library in Windows 7 OS.
  2. Computing SHA512 digest of a message.
  3. Using MD5 + AES to Hash and Encrypt a Message.

Note that I have never used Python programming language before. I will explain only the parts that I will be using from the language.

Installing The Library in Windows

Installing PyCrypto library in windows is very simple. All what we have to do is to execute the following command in cmd.exe:

pip install —use-wheel —no-index —find-links=https://github.com/sfbahr/PyCrypto-Wheels/raw/master/pycrypto-2.6.1-cp35-none-win_amd64.whl pycrypto

After executing the command, the library will be installed.

After Executing this command, the library will be installed. Note that the given command is for python 64 bit windows. If your python installation is 32 bits, change pycrypto-2.6.1-cp35-none-win_amd64.whl to pycrypto-2.6.1-cp35-none-win32.whl.

Applying PyCrypto Algorithms

Suppose that we have a text file named «PythonCrypto.txt» and the file contains the following Text:
Cryptography is the practice and study of techniques for secure communication in the presence of third parties called adversaries.   These adversaries are often referred to as Eve in cryptography, while the sender and recipient of messages are called Alice and Bob respectively. More generally, cryptography is about constructing and analyzing protocols that prevent third parties or the public from reading private messages.

The algorithms of PyCrypto Library will be applied to the content of the given file. The first thing we will do is to read the contend of the file as follows:

file = open("PythonCrypto.txt", 'r')
message = file.read();
#print file content to check if it was opened
print(message)

This code snippet can be used to only read the content of a file. The method open() in the given example has two parameters, the first is the name of the file and the second is the mode in which we will open the file. ‘r’ stands for ‘read’ and ‘w’ stands for ‘write’. After opening the file, we read its content and store it in the variable ‘message’ using the method ‘read()’. The text that comes after the ‘#’ is a comment in python language. A comment is a piece of text that does not affect the output of a program. It is only used to describe what your code is doing. the ‘print()’ is a function that is used to show the output in the console. It is defined in the heart of python language.

Computing SHA512 Hash 

Now that we have the content of the file, let’s try to apply some algorithms to it. The first thing we will do is to compute SHA512 digest of the text. To do that, we have to tell Python that we are going to use a function from PyCrypto library. The statement that is used to do that is as follows:

from Crypto.Hash import SHA512

This statement is called import statement. It must be the first statement in our python file. Now, let’s compute the digest. The code for that is as follows:

from Crypto.Hash import SHA512
file = open("PythonCrypto.txt", 'r')
message = file.read();
print(message)
digest = SHA512.new(message).hexdigest();
print(digest);

If we run the code as it is shown above, we will get the following error message:

TypeError: Unicode-objects must be encoded before hashing

This error basically means that we have to specify the type of text encoding that we are using for the given text. To specify the encoding of the text, we call the method ‘encode()’ as follows:

from Crypto.Hash import SHA512
file = open("PythonCrypto.txt", 'r')
message = file.read();
print(message)
digest = SHA512.new(message.encode('utf-8')).hexdigest();
print(digest);

This will solve the problem and will show the SHA512 digest of the message. It will be something like this:

6881eae82c054693543a9111f612b7252a19003483f75cd86455d3b72cfb6bbe32882d275f8ce26346f5b48d345d459796a0067031186f9a3196ac9b6964b2a3

This is a hexadecimal representation of the digest. Now, instead of printing the digest, let’s store it in a file called «SHA512Digest.txt«. The code for performing such as task is as follows:

from Crypto.Hash import SHA512
file = open("PythonCrypto.txt", 'r')
message = file.read();
print(message)
digest = SHA512.new(message.encode('utf-8')).hexdigest();
print(digest);
file = open("SHA512Digest.txt", 'w')
file.write(digest)
file.close()

The given code will create a new file called «SHA512Digest.txt«. After that, the method ‘write()’ will write the digest to the file. The method ‘close()’ will close the file after writing the digest to it.

Using MD5 Hash With AES Cipher

Now that we have the basics of using PyCrypto, we will start using it in little bit advanced way. The first thing that we will do is to compute the MD5 digest of the message. After that, we will be using AES Cipher to encrypt the text. Finally, we will send the message to another program using text file.

Hashing + Encryption, What Can we Get?

By using the digest of the message, we can guaranty the integrity of the message that is been sent. If the message has been modified while being sent, the digest will be different at the receiver side. By using AES, we guaranty confidentiality. Basically no one can read the content of the message except the one who has the key to decrypt the message.

Basics of AES:

AES Cipher has two parameters, the first one is the data that will be encrypted and the second one is the key. The cipher accepts data of size 16 bytes only. This means in order to encrypt larger data set, we have to divide the data set into smaller parts of size 16 bytes and use AES in each part. The key size for the cipher has 3 different sizes, 16 bytes, 24 bytes or 32 bytes.

AES in PyCrypto Library

Before using AES, we have to import it as we did with SHA algorithm. But in this case, AES will be in a different place. AES can be found in ‘Crypto.Cipher.AES’. According to the documentation of AES, the algorithm takes 3 parameters, A key, Mode and Initialization Vector (IV). The initialization vector will be used depending on the mode. If the mode is ‘AES.MODE_ECB’ or AES.MODE_CTR, the initialization vector is not needed. In our case, we will ignore the initialization vector and use ‘AES.MODE_ECB’. The following code example shows how to encrypt and decrypt a simple text of size 16 bytes using AES in PyCrypt.

from Crypto.Cipher import AES
cipher = AES.new("1111111111111111", AES.MODE_ECB, b'')
#each letter is one byte 
message = '0123456789abcdef' 
print('Original message = '+message)
encryptedMessage = cipher.encrypt('aaaaaaaaaaaaaaaa')
print('Encrypted Message = '+encryptedMessage)
decryptedMessage = cipher.decrypt(encryptedMessage)
print('Decrypted Message = '+decryptedMessage)

The «» implies that we are supplying a byte string to the algorithm as initialization vector. This will be ignored since the mode is ‘AES.MODE_ECB‘. If we run the code as it is, it will not run and we will get the following error:

TypeError: Can’t convert ‘bytes’ object to str implicitly

This error means that the type of data that returned by AES algorithm is byte and it cannot be shown in the console as it is. What we have to do is to change it to string. After doing that, the code will work fine.

from Crypto.Cipher import AES
cipher = AES.new("1111111111111111", AES.MODE_ECB, b'')
message = '0123456789abcdef' 
print('Original message = '+message)
encryptedMessage = cipher.encrypt('aaaaaaaaaaaaaaaa')
print('Encrypted Message = '+str(encryptedMessage))
decryptedMessage = cipher.decrypt(encryptedMessage)
print('Decrypted Message = '+str(decryptedMessage))

The output of the given code will be something like this:

Original message = 0123456789abcdef
Encrypted Message = b’xc6xb9xd1x02xddxeaxb1ixf3$xcbxdbxe73xf0n’
Decrypted Message = b’aaaaaaaaaaaaaaaa’

We can notice that the decrypted message has the letter ‘b’ which we don’t want to appear with the text. For this reason, we will be using different way to display the decrypted message. We will use ‘bytes.decode()‘.

from Crypto.Cipher import AES

cipher = AES.new("1111111111111111", AES.MODE_ECB, b'')
message = '0123456789abcdef'
print('Original message = '+message)
encryptedMessage = cipher.encrypt('aaaaaaaaaaaaaaaa')
print('Encrypted Message = '+str(encryptedMessage))
decryptedMessage = cipher.decrypt(encryptedMessage)
print('Decrypted Message = '+bytes.decode(decryptedMessage,'utf-8'))

Using MD5 + AES to Hash and Encrypt a File

Now that we know how to use hash functions and ciphers from PyCrypto library, we will be using them in a simple application. First, we will be computing MD5 hash of the file «PythonCrypto.txt«. Then we will be storing the hash in a file. After that, we will use AES to encrypt the file and store the key in one file and the encrypted data in another file. Lastly, another program will open the 3 generated files to verify the integrity of the data. The code for the first program is as follows:

from Crypto.Hash import MD5
from Crypto.Cipher import AES


key = "1111111111111111" 
cipher = AES.new(key, AES.MODE_ECB, b'')
file = open('PythonCrypto.txt', 'r')
# notice the 'wb'. the 'b' in here means we are writing binary data to file
encryptedFile = open("AESEncrypted.txt", 'wb')
while True:
    data = file.read(16)
    if data:
        encryptedMessage = cipher.encrypt(data)
        encryptedFile.write(encryptedMessage)
    else:
        encryptedFile.close()
        break
file = open("AESKey.txt", 'w')
file.write(key)
file.close()
 
# notice the 'rb' here. This means we are reading binary data 
encryptedFile = open("AESEncrypted.txt", 'rb')
message = encryptedFile.read()
digest = MD5.new(message.encode('utf-8')).hexdigest()
file = open("MD5Digest.txt", 'w')
file.write(digest)
file.close() 

When we run the code, it will not run and the following error will appear:
ValueError: Input strings must be a multiple of 16 in length
We are sure that the length of the ‘data’ variable is multiple of 16 bytes since we are providing the number 16 in the ‘read()’ function. When we print the data that we read from the file, we will see something as follows:
Cryptography

The first 3 characters are not part of the text on the file. The 3 characters called byte order mark (BOM). they are basically used to tell the encoding type of the file. To solve the problem, we have to skip the 3 characters. So, before we go into the loop, we will read 3 bytes and then enter the loop. The code now will become as follows:

from Crypto.Hash import MD5
from Crypto.Cipher import AES


key = "1111111111111111" 
cipher = AES.new(key, AES.MODE_ECB, b'')
file = open('PythonCrypto.txt', 'r')
encryptedFile = open("AESEncrypted.txt", 'wb')
file.read(3)
while True:
    data = file.read(16)
    if data:
        encryptedMessage = cipher.encrypt(data)
        encryptedFile.write(encryptedMessage)
    else:
        encryptedFile.close()
        break 
file = open("AESKey.txt", 'w')
file.write(key)
file.close()
encryptedFile = open("AESEncrypted.txt", 'rb')
message = encryptedFile.read()
digest = MD5.new(message.encode('utf-8')).hexdigest()
file = open("MD5Digest.txt", 'w')
file.write(digest)
file.close() 

When we run the code again, we still get the same error. The reason for that is because the content of the file is not a multiple of 16 bytes. To solve the problem, we have to add a check when we reach the end of the file to add some bytes to make it multiple of 16. We will add white spaces at the end of the data. After doing so, the code should work 100% fine.

from Crypto.Hash import MD5
from Crypto.Cipher import AES


key = "1111111111111111" 
cipher = AES.new(key, AES.MODE_ECB, b'')
file = open('PythonCrypto.txt', 'r')
encryptedFile = open("AESEncrypted.txt", 'wb')
file.read(3)
while True:
    data = file.read(16)
    if data:
        if len(data) != 16:
            while len(data) != 16:
                data += ' '
        encryptedMessage = cipher.encrypt(data)
        encryptedFile.write(encryptedMessage)
    else:
        encryptedFile.close()
        break 
file = open("AESKey.txt", 'w')
file.write(key)
file.close()
encryptedFile = open("AESEncrypted.txt", 'rb')
message = encryptedFile.read()
digest = MD5.new(message).hexdigest()
file = open("MD5Digest.txt", 'w')
file.write(digest)
file.close()

The code looks little bit messy. What we will do is to modify it and use methods (or functions) instead to make it cleaner. We will create 3 methods, one to encrypt the file, one to compute the digest and one for running the two methods. The syntax for defining a method in python is as follows:

def method_name(zero_or_more_params):
    # methode code goes here

As we can see, it is very simple. Note that to run the code, your methods should come before the place where you are using them. After fixing the code, it will become as follows:

from Crypto.Hash import MD5
from Crypto.Cipher import AES


def aes_encrypt(key, key_file_name, file_name, encrypted_file_name):
    cipher = AES.new(key, AES.MODE_ECB, b'')
    file = open(file_name, 'r')
    encrypted_file = open(encrypted_file_name, 'wb')
    file.read(3)
    while True:
        data = file.read(16)
        if data:
            if len(data) != 16:
                while len(data) != 16:
                    data += ' '
            encrypted_message = cipher.encrypt(data)
            encrypted_file.write(encrypted_message)
        else:
            encrypted_file.close()
            break     
    file = open(key_file_name, 'w')
    file.write(key)
    file.close()


def compute_md5_digest(digest_file_name, file_to_digest):
    encrypted_file = open(file_to_digest, 'rb')
    message = encrypted_file.read()
    digest = MD5.new(message).hexdigest()
    md5_file = open(digest_file_name, 'w')
    md5_file.write(digest)
    md5_file.close()


def main():
    key = '1111111111111111'    
    data_file_name = 'PythonCrypto.txt'    
    encrypted_file_name = 'AESEncrypted.txt'    
    key_file_name = 'AESKey.txt'    
    digest_file_name = 'MD5Digest.txt'    
    aes_encrypt(key, key_file_name, data_file_name, encrypted_file_name)
    compute_md5_digest(digest_file_name, encrypted_file_name)

main()

Now we will start working with the other program which will verify the integrty of the message + decrypt it.The program will be very short. The first thing the program will do is to open the encrypted file, compute the digest and compare it with the digest that was created by the first program. If the two are the same, then the message was not modified by any one and it is safe to decrypt it. We will create this program as a method. The code for that is as follows:

def program_2():
    print('Running Program #2')
    encrypted_file_name = 'AESEncrypted.txt'     
    key_file_name = 'AESKey.txt' 
    program_1_digest_file = 'MD5Digest.txt' 
    decrypted_file_name = 'AESDecrypt.txt'     
    file = open(program_1_digest_file)
    program_1_digest = file.read()
    file = open(encrypted_file_name,'rb')
    message = file.read()
    digest = MD5.new(message).hexdigest()
    if digest == program_1_digest:
        print('Data Integrity Verified!')
        print('Decrypting data')
        key_file = open(key_file_name)
        key = key_file.read()
        print('Key = '+key)
        encrypted_file = open(encrypted_file_name,'rb')
        decrypted_file = open(decrypted_file_name,'w')
        cipher = AES.new(key, AES.MODE_ECB, b'')
        while True:
            data = encrypted_file.read(16)
            if data:
                decrypted_message = cipher.decrypt(data)
                decrypted_file.write(bytes.decode(decrypted_message, 'utf-8'))
            else:
                print('Decrypting Finished!')
                print('Decrypted Data can be found inside '+encrypted_file_name)
                decrypted_file.close()
                break 
    else:
        print('Data was modified by someone!!')

Now we can merge the given code with the previous code to get our full two programs:

from Crypto.Hash import MD5
from Crypto.Cipher import AES


def aes_encrypt(key, key_file_name, file_name, encrypted_file_name):
    print('Encrypting '+file_name+' using AES')
    print('Key = '+key)
    print('File to encrypt = '+file_name)
    print('Encrypted file name = '+encrypted_file_name)
    print('Note: the encrypted data is stored as binary')
    cipher = AES.new(key, AES.MODE_ECB, b'')
    file = open(file_name, 'r')
    encrypted_file = open(encrypted_file_name, 'wb')
    file.read(3)
    while True:
        data = file.read(16)
        if data:
            if len(data) != 16:
                while len(data) != 16:
                    data += ' '
            encrypted_message = cipher.encrypt(data)
            encrypted_file.write(encrypted_message)
        else:
            encrypted_file.close()
            break     
    file = open(key_file_name, 'w')
    file.write(key)
    file.close()
    print('File Encryption Completed!')


def compute_md5_digest(digest_file_name, file_to_digest):
    print('Computing MD5 digest')
    print('Input file = '+file_to_digest)
    print('Output file = '+digest_file_name)
    encrypted_file = open(file_to_digest, 'rb')
    message = encrypted_file.read()
    digest = MD5.new(message).hexdigest()
    md5_file = open(digest_file_name, 'w')
    md5_file.write(digest)
    md5_file.close()
    print('MD5 digest finished!')


def program_1():
    print('Running Program #1')
    key = '1111111111111111'    data_file_name = 'PythonCrypto.txt' 
    encrypted_file_name = 'AESEncrypted.txt' 
    key_file_name = 'AESKey.txt' 
    digest_file_name = 'MD5Digest.txt'     
    aes_encrypt(key, key_file_name, data_file_name, encrypted_file_name)
    compute_md5_digest(digest_file_name, encrypted_file_name)
    print('Program #1 Finished!')


def program_2():
    print('Running Program #2')
    encrypted_file_name = 'AESEncrypted.txt' 
    key_file_name = 'AESKey.txt' 
    program_1_digest_file = 'MD5Digest.txt' 
    decrypted_file_name = 'AESDecrypt.txt'     
    file = open(program_1_digest_file)
    program_1_digest = file.read()
    file = open(encrypted_file_name, 'rb')
    message = file.read()
    digest = MD5.new(message).hexdigest()
    if digest == program_1_digest:
        print('Data Integrity Verified!')
        print('Decrypting data')
        key_file = open(key_file_name)
        key = key_file.read()
        print('Key = '+key)
        encrypted_file = open(encrypted_file_name, 'rb')
        decrypted_file = open(decrypted_file_name, 'w')
        cipher = AES.new(key, AES.MODE_ECB, b'')
        while True:
            data = encrypted_file.read(16)
            if data:
                decrypted_message = cipher.decrypt(data)
                decrypted_file.write(bytes.decode(decrypted_message, 'utf-8'))
            else:
                print('Decrypting Finished!')
                print('Decrypted Data can be found inside '+encrypted_file_name)
                decrypted_file.close()
                break 
    else:
        print('Data was modified by someone!!')
    print('Program #2 Finished!')


# inside main, we can select which program to run. 
# program_1() means the one who will send the data. 
# program_2 means the one who will receive the data.
def main():
    program_1()
    program_2()


main()

The next step will be to learn  about asymmetric keys in PyCrypt and how to use them  to encrypt and decrypt the file. Basically we will be using digital signature.

Common Errors and how to Fix Them:

Error Message: 
ImportError: No module named ‘winrandom’

Fix:
Edit the file ‘Python35libsite-packagesCryptoRandomOSRNGnt.py’. Change ‘

import winrandom' to '
from . import winrandom'.

Error Message: 
ImportError: DLL load failed: The specified module could not be found.
Fix:

This message appear when trying to import something from the library. The reason for that is the installation is broken. You have to re-install PyCrypto library.

Error Message: 
ValueError: Input strings must be a multiple of 16 in length.
This error can appear if an algorithm needs specific data length. For example, the input to AES must be 16 bytes in length. if it is more or less, this error will appear.
Fix: Check data length that it is 16 bytes.

Error Message:
TypeError: Can’t convert ‘bytes’ object to str implicitly
This error appears when we try to print other data types such as byte. The print method accepts only string type.
Fix:
Use str(data_to_print).

Error Message:
UnicodeDecodeError: ‘utf-8’ codec can’t decode byte 0xff in position 0: invalid start byte
This error can happen when reading from file. The error means that the encoding of the file is not ‘utf-8’. All what you have to do is open the file and save it in ‘utf-8’ encoding.

Error Message:
TypeError: write() argument must be str, not bytes
This error can happen when we try to write data into a file. The method ‘write()‘ will only accept data of type string if we use ‘w’. This means we have to use the method ‘str(data)‘ to convert our data into string before using ‘write()‘ method. Another solution is to use ‘wb’ if we are writing raw data to the file.

In part 2, we will learn how to use digital signature to sign our data. Part 2 will be posted in the future.

 

Installation¶

The installation procedure depends on the package you want the library to be in. PyCryptodome can be used as:

  1. An almost drop-in replacement for the old PyCrypto library. You install it with:

In this case, all modules are installed under the Crypto package. You can test everything is right with:

You can test everything is right with:

If you intend to run PyCryptodome with Python 2.7 under Windows, you must first install the Microsoft Visual C++ 2015 Redistributable. That is not necessary if you use Python 3.

The procedures below go a bit more in detail, by explaining how to setup the environment for compiling the C extensions for each OS, and how to install the GMP library.

Compiling in Linux Ubuntu¶

If you want to install under the Crypto package, replace below pycryptodomex with pycryptodome .

Compiling in Linux Fedora¶

If you want to install under the Crypto package, replace below pycryptodomex with pycryptodome .

Windows (from sources)¶

If you want to install under the Crypto package, replace below pycryptodomex with pycryptodome .

Windows does not come with a C compiler like most Unix systems. The simplest way to compile the PyCryptodome extensions from source code is to install the minimum set of Visual Studio components freely made available by Microsoft.

[Once only] Download Build Tools for Visual Studio 2019. In the installer, select the C++ build tools, the Windows 10 SDK, and the latest version of MSVC v142 x64/x86 build tools.

Compile and install PyCryptodome:

To make sure everything work fine, run the test suite:

Documentation¶

Project documentation is written in reStructuredText and it is stored under Doc/src . To publish it as HTML files, you need to install sphinx and use:

It will then be available under Doc/_build/html/ .

PGP verification¶

All source packages and wheels on PyPI are cryptographically signed. They can be verified with the following PGP key:

Python 3 — Install pycrypto on Windows

I’m using Python 3.7 and Windows 10. ‘pip install pycrypto‘ doesn’t work with the following error:

The file includepyport.h in Python installation directory does not have #include < stdint.h > anymore. This leaves intmax_t undefined.

A workaround for Microsoft VC compiler is to force include stdint.h via OS environment variable CL:

  • Open command prompt, and Setup VC environment by runing vcvars*.bat (choose file name depending on VC version and architecture)
  • set CL=-FI»Full-Pathstdint.h» (use real value for Full-Path for the environment)
  • then, try to install pycrypto again:

Another option that I’ll try in future is to use PyCryptodome instead of pycrypto. pycrypto is discontinued and is no longer actively supported. PyCryptodome exposes almost the same API as pycrypto (source).

Как установить PyCrypto в Windows?

Я читал каждый другой источник google и поток SO, ничего не работая.

Python 2.7.3 32bit установлен на Windows 7 64bit . Загрузите, извлеките, а затем попытайтесь установить результаты PyCrypto в «Unable to find vcvarsall.bat».

Итак, я устанавливаю MinGW и придерживаюсь того, что на установочной линии является компилятором. Но затем я получаю сообщение об ошибке «RuntimeError: chmod error».

Как я могу обойти это в мире? Я пробовал использовать pip, который дает тот же результат. Я нашел предустановленный двоичный файл PyCrypto 2.3 и установил его, но его нигде не найти в системе (не работает).

17 ответов

Если у вас еще нет установленной среды разработки C/С++, совместимой с бинарниками Visual Studio, распространяемыми Python.org, вам следует придерживаться установки только чистых пакетов или пакетов Python, для которых доступен двоичный файл Windows.

К счастью, для Windows имеются доступные двоичные файлы PyCrypto: http://www.voidspace.org.uk/python/modules.shtml#pycrypto

UPDATE:
Как поясняет @Udi в комментарии ниже, следующая команда также устанавливает pycrypto и также может использоваться в virtualenv :

Обратите внимание, чтобы выбрать соответствующую ссылку для вашей установки из этот список

Если вы ищете сборки для Python 3.5, см. PyCrypto на python 3.5

Недавно Microsoft недавно выпустила автономный, выделенный Microsoft Visual С++ Compiler для Python 2.7. Если вы используете Python 2.7, просто установите этот компилятор и Setuptools 6.0 или более поздней версии, и большинство пакетов с расширениями C теперь будут легко компилироваться.

Обычно

vcvarsall.bat является частью компилятора Visual С++, вам необходимо установить то, что вы пытаетесь установить. Даже не пытайтесь иметь дело с MingGW, если ваш Python был скомпилирован с помощью инструментальной цепочки Visual Studio и наоборот. Даже важна версия цепочки инструментов Microsoft. Python, скомпилированный с VS 2008, не будет работать с расширениями, скомпилированными с VS 2010!

Вы должны скомпилировать PyCrypto с тем же компилятором, с которым была скомпилирована версия Python. Google для «Не удалось найти vcvarsall.bat», потому что это корень вашей проблемы, Это очень распространенная проблема с компиляцией расширений Python в Windows.

Остерегайтесь использования Visual Studio 2010 или не используете Visual Studio 2008

Насколько я знаю, все еще верно. Это было опубликовано в ссылке выше в июне 2010 года, ссылаясь на попытку создания расширений с помощью VS 2010 Express в отношении установщиков Python, доступных на python.org.

Будьте осторожны, если вы это сделаете. Python 2.6 и 2.7 из python.org — это построенный с помощью компиляторов Visual Studio 2008. Вам нужно будет установить связь с тот же CRT (msvcr90.dll) как Python.

Ссылки на Visual Studio 2010 Express с неправильной версией CRT: msvcr100.dll.

Если вы это сделаете, вы также должны перестроить Python с помощью Visual Studio 2010 Экспресс. Вы не можете использовать стандартный двоичный установщик Python для Окна. Вы также не можете использовать любые расширения C/С++, созданные с помощью другого компилятор, чем Visual Studio 2010 (Express).

Мнение: Это одна из причин, по которой я отказался от Windows для всех серьезных разработок OSX!

Advertisement

Advertisement


Submitted by NanoDano on Sat, 11/28/2015 — 22:32

Paramiko is a great Python library for SSH but it can be a hassle to install in Windows. In this situation, I am using Windows 10 64-bit and Python 3.4.3. Paramiko is available on Pip which helps but it is not the smoothest installation.

First, I run in to an issue with the PyCrypto dependency that it tries to install:

error: Microsoft Visual C++ 10.0 is required (Unable to find vcvarsall.bat)

Read this on how to solve that problem: Fix Pip Install Unable to Find vcvarsall.bat

After getting that done and reinstalling with Pip, it appears to install properly. However, when I try to run Python and import paramiko I get an error about winrandom:

ImportError: No module named 'winrandom'

To fix this, you have to go in the source code for the Crypto lib and fix an import statement. In my case, Python was installed to C:Python34. The full path of the file I had to change was:

C:Python34Libsite-packagesCryptoRandomOSRNGnt.py

In that file, change

import winrandom

to

from . import winrandom

Now you should be able to run python and import paramiko.

Advertisement

Advertisement

Понравилась статья? Поделить с друзьями:
  • How to install jre on windows
  • How to install jdk on windows 10
  • How to install java on windows 10
  • How to install iso windows 10
  • How to install internet explorer 11 on windows 10