- pycrypto 2.6.1
- Navigation
- Project links
- Statistics
- Maintainers
- Classifiers
- Project description
- Python Cryptography Toolkit (pycrypto)
- Installation
- InstallationВ¶
- Compiling in Linux UbuntuВ¶
- Compiling in Linux FedoraВ¶
- Windows (from sources)В¶
- DocumentationВ¶
- PGP verificationВ¶
- PyCrypto — The Python Cryptography Toolkit
- Random number generation
- Download the latest release
- Documentation
- Contributing
- Submitting patches
- Export of cryptography software
- Pycrypto ��� ���������� linux
- Users who have contributed to this file
pycrypto 2.6.1
pip install pycrypto Copy PIP instructions
Released: Oct 17, 2013
Cryptographic modules for Python.
Navigation
Project links
Statistics
View statistics for this project via Libraries.io, or by using our public dataset on Google BigQuery
License: Public Domain (Public domain)
Maintainers
Classifiers
- Development Status
- 5 — Production/Stable
- Intended Audience
- Developers
- License
- Public Domain
- Operating System
- MacOS :: MacOS X
- Microsoft :: Windows
- Unix
- Programming Language
- Python :: 2
- Python :: 3
- Topic
- Security :: Cryptography
Project description
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
An example usage of the SHA256 module is:
An example usage of an encryption algorithm (AES, in this case) is:
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:
A stronger version of Python’s standard “random” module is also provided:
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:
Источник
InstallationВ¶
The installation procedure depends on the package you want the library to be in. PyCryptodome can be used as:
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:
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 .
A library independent of the old PyCrypto. You install it with:
You can test everything is right with:
In this case, all modules are installed under the Cryptodome package. The old PyCrypto and PyCryptodome can coexist.
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:
Источник
PyCrypto — The Python Cryptography Toolkit
Random number generation
Here is the current list of known random number generation issues/bugs that have been found in previous versions of PyCrypto:
- In versions prior to v2.6.1, Crypto.Random was insecure when using fork() in some cases. See the advisory for CVE-2013-1445 for more information. It is recommended that users upgrade to PyCrypto v2.6.1 or later.
- In versions prior to v2.1.0, Crypto.Util.randpool.RandomPool was unsafe as commonly used. It was not thread-safe or fork-safe at all, and it was not always properly seeded with entropy. This was by design, but most application developers simply read from it without any further thought, resulting in insecure applications. See this thread for more information. It is now is deprecated, and will be removed in a future release; Use Crypto.Random or os.urandom instead.
Keeping an entropy pool in a user-space program is complex and error-prone. It is especially difficult to do reliably in a generic crypto library, and it is quite common for mistakes to be made. Hopefully, operating systems will one day provide random number generation facilities that are sufficiently fast, trustworthy, and reliable that they can completely replace the multitude of user-space random number generators that currently plague our software.
Download the latest release
The latest stable release is available here:
The latest experimental release is available here:
Documentation
Contributing
Bugs and feature requests are tracked on GitHub. If you are interested in contributing, please join the mailing list.
The source code is now managed on GitHub. Clone it using git by running the following command:
Submitting patches
In an effort to clarify PyCrypto’s licensing terms and export control status, all new patch submissions must meet the requirements set out in the document, «PyCrypto Code Submission Requirements — Rev. D».
Once you have confirmed that you meet the «Code Submission Requirements» above, please send me a push request on GitHub. Alternatively, you can send your patches to the mailing list.
Tips for getting your patches accepted:
- Don’t needlessly break compatibility with older versions of PyCrypto. Patches that break compatibility with older version of PyCrypto, especially PyCrypto 2.0.1, will need an explanation about why it’s worth breaking compatibility. Exception: Removing buggy code that nobody uses is fine.
- Don’t needlessly break compatibility with older versions of Python. Run the test suite using Python 2.1 and the latest version of Python 2.x.
- Don’t needlessly add complexity. The more complex the code is, the harder it is to maintain, and the more likely it is to have bugs.
- Don’t needlessly add features. Seriously. X.509 doesn’t belong in PyCrypto. Or anywhere, really.
- Don’t create copyright headaches. It took me the better part of a year to sort out the licensing ambiguities in PyCrypto 2.0.1. If you’re adding new files, include the standard PyCrypto public domain dedication at the top.
- Whatever you do in _fastmath.c, also do in _slowmath.py. PyCrypto has two math libraries: one that depends on libgmp, and one that doesn’t. They need to be kept synchronized with each other.
- Make small, incremental, well-documented changes. Your commit messages should be clear and detailed. Include any applicable background information. Your patches should do one thing. Your code should have sensible comments.
Export of cryptography software
The export of cryptography software is (still) governed by arms control regulations in Canada, the United States, and elsewhere. The export or re-export of this software may be regulated by law in your country.
Источник
Pycrypto ��� ���������� linux
2 contributors
Users who have contributed to this file
Copy raw contents
Copy raw contents
# -*- coding: utf-8 -*- |
# |
# Hash/CMAC.py — Implements the CMAC algorithm |
# |
# =================================================================== |
# The contents of this file are dedicated to the public domain. To |
# the extent that dedication to the public domain is not available, |
# everyone is granted a worldwide, perpetual, royalty-free, |
# non-exclusive license to exercise all rights associated with the |
# contents of this file for any purpose whatsoever. |
# No rights are reserved. |
# |
# THE SOFTWARE IS PROVIDED «AS IS», WITHOUT WARRANTY OF ANY KIND, |
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF |
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND |
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS |
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN |
# ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN |
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE |
# SOFTWARE. |
# =================================================================== |
«»»CMAC (Cipher-based Message Authentication Code) algorithm |
CMAC is a MAC defined in `NIST SP 800-38B`_ and in RFC4493_ (for AES only) |
and constructed using a block cipher. It was originally known as `OMAC1`_. |
The algorithm is sometimes named *X-CMAC* where *X* is the name |
of the cipher (e.g. AES-CMAC). |
This is an example showing how to *create* an AES-CMAC: |
>>> from Crypto.Hash import CMAC |
>>> from Crypto.Cipher import AES |
>>> |
>>> secret = b’Sixteen byte key’ |
>>> cobj = CMAC.new(secret, ciphermod=AES) |
>>> cobj.update(b’Hello’) |
>>> print cobj.hexdigest() |
And this is an example showing how to *check* an AES-CMAC: |
>>> from Crypto.Hash import CMAC |
>>> from Crypto.Cipher import AES |
>>> |
>>> # We have received a message ‘msg’ together |
>>> # with its MAC ‘mac’ |
>>> |
>>> secret = b’Sixteen byte key’ |
>>> cobj = CMAC.new(secret, ciphermod=AES) |
>>> cobj.update(msg) |
>>> try: |
>>> cobj.verify(mac) |
>>> print «The message ‘%s’ is authentic» % msg |
>>> except ValueError: |
>>> print «The message or the key is wrong» |
.. _`NIST SP 800-38B`: http://csrc.nist.gov/publications/nistpubs/800-38B/SP_800-38B.pdf |
.. _RFC4493: http://www.ietf.org/rfc/rfc4493.txt |
.. _OMAC1: http://www.nuee.nagoya-u.ac.jp/labs/tiwata/omac/omac.html |
«»» |
__all__ = [ ‘new’ , ‘digest_size’ , ‘CMAC’ ] |
import sys |
if sys . version_info [ 0 ] == 2 and sys . version_info [ 1 ] == 1 : |
from Crypto . Util . py21compat import * |
from Crypto . Util . py3compat import * |
from binascii import unhexlify |
from Crypto . Util . strxor import strxor |
from Crypto . Util . number import long_to_bytes , bytes_to_long |
#: The size of the authentication tag produced by the MAC. |
digest_size = None |
def _shift_bytes ( bs , xor_lsb = 0 ): |
num = ( bytes_to_long ( bs ) 1 ) ^ xor_lsb |
return long_to_bytes ( num , len ( bs ))[ — len ( bs ):] |
class _SmoothMAC ( object ): |
«»»Turn a MAC that only operates on aligned blocks of data |
into a MAC with granularity of 1 byte.»»» |
def __init__ ( self , block_size , msg = b ( «» ), min_digest = 0 ): |
self . _bs = block_size |
#: Data waiting to be MAC-ed |
self . _buffer = [] |
self . _buffer_len = 0 |
#: Data received via update() |
self . _total_len = 0 |
#: Minimum amount of bytes required by the final digest step |
self . _min_digest = min_digest |
#: Block MAC object |
self . _mac = None |
#: Cached digest |
self . _tag = None |
if msg : |
self . update ( msg ) |
def can_reduce ( self ): |
return ( self . _mac is not None ) |
def get_len ( self ): |
return self . _total_len |
def zero_pad ( self ): |
if self . _buffer_len & ( self . _bs — 1 ): |
npad = self . _bs — self . _buffer_len & ( self . _bs — 1 ) |
self . _buffer . append ( bchr ( 0 ) * npad ) |
self . _buffer_len += npad |
def update ( self , data ): |
# Optimization (try not to copy data if possible) |
if self . _buffer_len == 0 and self . can_reduce () and \ |
self . _min_digest == 0 and len ( data ) % self . _bs == 0 : |
self . _update ( data ) |
self . _total_len += len ( data ) |
return |
self . _buffer . append ( data ) |
self . _buffer_len += len ( data ) |
self . _total_len += len ( data ) |
# Feed data into MAC |
blocks , rem = divmod ( self . _buffer_len , self . _bs ) |
if rem self . _min_digest : |
blocks -= 1 |
if blocks > 0 and self . can_reduce (): |
aligned_data = blocks * self . _bs |
buf = b ( «» ). join ( self . _buffer ) |
self . _update ( buf [: aligned_data ]) |
self . _buffer = [ buf [ aligned_data :] ] |
self . _buffer_len -= aligned_data |
def _deep_copy ( self , target ): |
# Copy everything by self._mac, since we don’t know how to |
target . _buffer = self . _buffer [:] |
for m in [ ‘_bs’ , ‘_buffer_len’ , ‘_total_len’ , ‘_min_digest’ , ‘_tag’ ]: |
setattr ( target , m , getattr ( self , m )) |
def _update ( self , data_block ): |
«»»Delegate to the implementation the update |
of the MAC state given some new *block aligned* data.»»» |
raise NotImplementedError ( «_update() must be still implemented» ) |
def _digest ( self , left_data ): |
«»»Delegate to the implementation the computation |
of the final MAC given the current MAC state |
and the last piece of data (not block aligned).»»» |
raise NotImplementedError ( «_digest() must be still implemented» ) |
def digest ( self ): |
if self . _tag : |
return self . _tag |
if self . _buffer_len > 0 : |
self . update ( b ( «» )) |
left_data = b ( «» ). join ( self . _buffer ) |
self . _tag = self . _digest ( left_data ) |
return self . _tag |
class CMAC ( _SmoothMAC ): |
«»»Class that implements CMAC»»» |
#: The size of the authentication tag produced by the MAC. |
digest_size = None |
def __init__ ( self , key , msg = None , ciphermod = None ): |
«»»Create a new CMAC object. |
:Parameters: |
key : byte string |
secret key for the CMAC object. |
The key must be valid for the underlying cipher algorithm. |
For instance, it must be 16 bytes long for AES-128. |
msg : byte string |
The very first chunk of the message to authenticate. |
It is equivalent to an early call to `update`. Optional. |
ciphermod : module |
A cipher module from `Crypto.Cipher`. |
The cipher’s block size must be 64 or 128 bits. |
It is recommended to use `Crypto.Cipher.AES`. |
«»» |
if ciphermod is None : |
raise TypeError ( «ciphermod must be specified (try AES)» ) |
_SmoothMAC . __init__ ( self , ciphermod . block_size , msg , 1 ) |
self . _key = key |
self . _factory = ciphermod |
# Section 5.3 of NIST SP 800 38B |
if ciphermod . block_size == 8 : |
const_Rb = 0x1B |
elif ciphermod . block_size == 16 : |
const_Rb = 0x87 |
else : |
raise TypeError ( «CMAC requires a cipher with a block size of 8 or 16 bytes, not %d» % |
( ciphermod . block_size ,)) |
self . digest_size = ciphermod . block_size |
# Compute sub-keys |
cipher = ciphermod . new ( key , ciphermod . MODE_ECB ) |
l = cipher . encrypt ( bchr ( 0 ) * ciphermod . block_size ) |
if bord ( l [ 0 ]) & 0x80 : |
self . _k1 = _shift_bytes ( l , const_Rb ) |
else : |
self . _k1 = _shift_bytes ( l ) |
if bord ( self . _k1 [ 0 ]) & 0x80 : |
self . _k2 = _shift_bytes ( self . _k1 , const_Rb ) |
else : |
self . _k2 = _shift_bytes ( self . _k1 ) |
# Initialize CBC cipher with zero IV |
self . _IV = bchr ( 0 ) * ciphermod . block_size |
self . _mac = ciphermod . new ( key , ciphermod . MODE_CBC , self . _IV ) |
def update ( self , msg ): |
«»»Continue authentication of a message by consuming the next chunk of data. |
Repeated calls are equivalent to a single call with the concatenation |
of all the arguments. In other words: |
>>> m.update(a); m.update(b) |
is equivalent to: |
>>> m.update(a+b) |
:Parameters: |
msg : byte string |
The next chunk of the message being authenticated |
«»» |
_SmoothMAC . update ( self , msg ) |
def _update ( self , data_block ): |
self . _IV = self . _mac . encrypt ( data_block )[ — self . _mac . block_size :] |
def copy ( self ): |
«»»Return a copy («clone») of the MAC object. |
The copy will have the same internal state as the original MAC |
object. |
This can be used to efficiently compute the MAC of strings that |
share a common initial substring. |
:Returns: A `CMAC` object |
«»» |
obj = CMAC ( self . _key , ciphermod = self . _factory ) |
_SmoothMAC . _deep_copy ( self , obj ) |
obj . _mac = self . _factory . new ( self . _key , self . _factory . MODE_CBC , self . _IV ) |
for m in [ ‘_tag’ , ‘_k1’ , ‘_k2’ , ‘_IV’ ]: |
setattr ( obj , m , getattr ( self , m )) |
return obj |
def digest ( self ): |
«»»Return the **binary** (non-printable) MAC of the message that has |
been authenticated so far. |
This method does not change the state of the MAC object. |
You can continue updating the object after calling this function. |
:Return: A byte string of `digest_size` bytes. It may contain non-ASCII |
characters, including null bytes. |
«»» |
return _SmoothMAC . digest ( self ) |
def _digest ( self , last_data ): |
if len ( last_data ) == self . _bs : |
last_block = strxor ( last_data , self . _k1 ) |
else : |
last_block = strxor ( last_data + bchr ( 128 ) + |
bchr ( 0 ) * ( self . _bs — 1 — len ( last_data )), self . _k2 ) |
tag = self . _mac . encrypt ( last_block ) |
return tag |
def hexdigest ( self ): |
«»»Return the **printable** MAC of the message that has been |
authenticated so far. |
This method does not change the state of the MAC object. |
:Return: A string of 2* `digest_size` bytes. It contains only |
hexadecimal ASCII digits. |
«»» |
return «» . join ([ «%02x» % bord ( x ) |
for x in tuple ( self . digest ())]) |
def verify ( self , mac_tag ): |
«»»Verify that a given **binary** MAC (computed by another party) is valid. |
:Parameters: |
mac_tag : byte string |
The expected MAC of the message. |
:Raises ValueError: |
if the MAC does not match. It means that the message |
has been tampered with or that the MAC key is incorrect. |
«»» |
mac = self . digest () |
res = 0 |
# Constant-time comparison |
for x , y in zip ( mac , mac_tag ): |
res |= bord ( x ) ^ bord ( y ) |
if res or len ( mac_tag ) != self . digest_size : |
raise ValueError ( «MAC check failed» ) |
def hexverify ( self , hex_mac_tag ): |
«»»Verify that a given **printable** MAC (computed by another party) is valid. |
:Parameters: |
hex_mac_tag : string |
The expected MAC of the message, as a hexadecimal string. |
:Raises ValueError: |
if the MAC does not match. It means that the message |
has been tampered with or that the MAC key is incorrect. |
«»» |
self . verify ( unhexlify ( tobytes ( hex_mac_tag ))) |
def new ( key , msg = None , ciphermod = None ): |
«»»Create a new CMAC object. |
:Parameters: |
key : byte string |
secret key for the CMAC object. |
The key must be valid for the underlying cipher algorithm. |
For instance, it must be 16 bytes long for AES-128. |
msg : byte string |
The very first chunk of the message to authenticate. |
It is equivalent to an early call to `CMAC.update`. Optional. |
ciphermod : module |
A cipher module from `Crypto.Cipher`. |
The cipher’s block size must be 64 or 128 bits. |
Default is `Crypto.Cipher.AES`. |
:Returns: A `CMAC` object |
«»» |
return CMAC ( key , msg , ciphermod ) |
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.
Источник