updated pycrypto

This commit is contained in:
shim_
2018-05-10 16:56:32 +02:00
parent fb89f1946b
commit 26579a25f1
92 changed files with 2518 additions and 5288 deletions

View File

@@ -43,7 +43,7 @@ The strength of an HMAC depends on:
- the strength of the hash algorithm
- the length and entropy of the secret key
This is an example showing how to *create* a MAC:
An example of possible usage is the following:
>>> from Crypto.Hash import HMAC
>>>
@@ -52,22 +52,6 @@ This is an example showing how to *create* a MAC:
>>> h.update(b'Hello')
>>> print h.hexdigest()
This is an example showing how to *check* a MAC:
>>> from Crypto.Hash import HMAC
>>>
>>> # We have received a message 'msg' together
>>> # with its MAC 'mac'
>>>
>>> secret = b'Swordfish'
>>> h = HMAC.new(secret)
>>> h.update(msg)
>>> try:
>>> h.verify(mac)
>>> print "The message '%s' is authentic" % msg
>>> except ValueError:
>>> print "The message or the key is wrong"
.. _RFC2104: http://www.ietf.org/rfc/rfc2104.txt
.. _FIPS-198: http://csrc.nist.gov/publications/fips/fips198/fips-198a.pdf
"""
@@ -79,8 +63,6 @@ __revision__ = "$Id$"
__all__ = ['new', 'digest_size', 'HMAC' ]
from binascii import unhexlify
from Crypto.Util.strxor import strxor_c
from Crypto.Util.py3compat import *
@@ -189,32 +171,12 @@ class HMAC:
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.
characters, including null bytes.
"""
h = self.outer.copy()
h.update(self.inner.digest())
return h.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 hexdigest(self):
"""Return the **printable** MAC of the message that has been
authenticated so far.
@@ -227,19 +189,6 @@ class HMAC:
return "".join(["%02x" % bord(x)
for x in tuple(self.digest())])
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, digestmod = None):
"""Create a new HMAC object.

View File

@@ -0,0 +1,91 @@
# -*- coding: utf-8 -*-
#
# ===================================================================
# 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.
# ===================================================================
"""MD2 cryptographic hash algorithm.
MD2 is specified in RFC1319_ and it produces the 128 bit digest of a message.
>>> from Crypto.Hash import MD2
>>>
>>> h = MD2.new()
>>> h.update(b'Hello')
>>> print h.hexdigest()
MD2 stand for Message Digest version 2, and it was invented by Rivest in 1989.
This algorithm is both slow and insecure. Do not use it for new designs.
.. _RFC1319: http://tools.ietf.org/html/rfc1319
"""
_revision__ = "$Id$"
__all__ = ['new', 'digest_size', 'MD2Hash' ]
from Crypto.Util.py3compat import *
from Crypto.Hash.hashalgo import HashAlgo
import Crypto.Hash._MD2 as _MD2
hashFactory = _MD2
class MD2Hash(HashAlgo):
"""Class that implements an MD2 hash
:undocumented: block_size
"""
#: ASN.1 Object identifier (OID)::
#:
#: id-md2 OBJECT IDENTIFIER ::= {
#: iso(1) member-body(2) us(840) rsadsi(113549)
#: digestAlgorithm(2) 2
#: }
#:
#: This value uniquely identifies the MD2 algorithm.
oid = b('\x06\x08\x2a\x86\x48\x86\xf7\x0d\x02\x02')
digest_size = 16
block_size = 16
def __init__(self, data=None):
HashAlgo.__init__(self, hashFactory, data)
def new(self, data=None):
return MD2Hash(data)
def new(data=None):
"""Return a fresh instance of the hash object.
:Parameters:
data : byte string
The very first chunk of the message to hash.
It is equivalent to an early call to `MD2Hash.update()`.
Optional.
:Return: An `MD2Hash` object
"""
return MD2Hash().new(data)
#: The size of the resulting hash in bytes.
digest_size = MD2Hash.digest_size
#: The internal block size of the hash algorithm in bytes.
block_size = MD2Hash.block_size

View File

@@ -0,0 +1,91 @@
# -*- coding: utf-8 -*-
#
# ===================================================================
# 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.
# ===================================================================
"""MD4 cryptographic hash algorithm.
MD4 is specified in RFC1320_ and produces the 128 bit digest of a message.
>>> from Crypto.Hash import MD4
>>>
>>> h = MD4.new()
>>> h.update(b'Hello')
>>> print h.hexdigest()
MD4 stand for Message Digest version 4, and it was invented by Rivest in 1990.
This algorithm is insecure. Do not use it for new designs.
.. _RFC1320: http://tools.ietf.org/html/rfc1320
"""
_revision__ = "$Id$"
__all__ = ['new', 'digest_size', 'MD4Hash' ]
from Crypto.Util.py3compat import *
from Crypto.Hash.hashalgo import HashAlgo
import Crypto.Hash._MD4 as _MD4
hashFactory = _MD4
class MD4Hash(HashAlgo):
"""Class that implements an MD4 hash
:undocumented: block_size
"""
#: ASN.1 Object identifier (OID)::
#:
#: id-md2 OBJECT IDENTIFIER ::= {
#: iso(1) member-body(2) us(840) rsadsi(113549)
#: digestAlgorithm(2) 4
#: }
#:
#: This value uniquely identifies the MD4 algorithm.
oid = b('\x06\x08\x2a\x86\x48\x86\xf7\x0d\x02\x04')
digest_size = 16
block_size = 64
def __init__(self, data=None):
HashAlgo.__init__(self, hashFactory, data)
def new(self, data=None):
return MD4Hash(data)
def new(data=None):
"""Return a fresh instance of the hash object.
:Parameters:
data : byte string
The very first chunk of the message to hash.
It is equivalent to an early call to `MD4Hash.update()`.
Optional.
:Return: A `MD4Hash` object
"""
return MD4Hash().new(data)
#: The size of the resulting hash in bytes.
digest_size = MD4Hash.digest_size
#: The internal block size of the hash algorithm in bytes.
block_size = MD4Hash.block_size

View File

@@ -35,58 +35,63 @@ This algorithm is insecure. Do not use it for new designs.
.. _RFC1321: http://tools.ietf.org/html/rfc1321
"""
from __future__ import nested_scopes
_revision__ = "$Id$"
__all__ = ['new', 'block_size', 'digest_size']
__all__ = ['new', 'digest_size', 'MD5Hash' ]
from Crypto.Util.py3compat import *
if sys.version_info[0] == 2 and sys.version_info[1] == 1:
from Crypto.Util.py21compat import *
from Crypto.Hash.hashalgo import HashAlgo
def __make_constructor():
try:
# The md5 module is deprecated in Python 2.6, so use hashlib when possible.
from hashlib import md5 as _hash_new
except ImportError:
from md5 import new as _hash_new
try:
# The md5 module is deprecated in Python 2.6, so use hashlib when possible.
import hashlib
hashFactory = hashlib.md5
h = _hash_new()
if hasattr(h, 'new') and hasattr(h, 'name') and hasattr(h, 'digest_size') and hasattr(h, 'block_size'):
# The module from stdlib has the API that we need. Just use it.
return _hash_new
else:
# Wrap the hash object in something that gives us the expected API.
_copy_sentinel = object()
class _MD5(object):
digest_size = 16
block_size = 64
name = "md5"
def __init__(self, *args):
if args and args[0] is _copy_sentinel:
self._h = args[1]
else:
self._h = _hash_new(*args)
def copy(self):
return _MD5(_copy_sentinel, self._h.copy())
def update(self, *args):
f = self.update = self._h.update
f(*args)
def digest(self):
f = self.digest = self._h.digest
return f()
def hexdigest(self):
f = self.hexdigest = self._h.hexdigest
return f()
_MD5.new = _MD5
return _MD5
except ImportError:
import md5
hashFactory = md5
new = __make_constructor()
del __make_constructor
class MD5Hash(HashAlgo):
"""Class that implements an MD5 hash
:undocumented: block_size
"""
#: ASN.1 Object identifier (OID)::
#:
#: id-md5 OBJECT IDENTIFIER ::= {
#: iso(1) member-body(2) us(840) rsadsi(113549)
#: digestAlgorithm(2) 5
#: }
#:
#: This value uniquely identifies the MD5 algorithm.
oid = b('\x06\x08\x2a\x86\x48\x86\xf7\x0d\x02\x05')
digest_size = 16
block_size = 64
def __init__(self, data=None):
HashAlgo.__init__(self, hashFactory, data)
def new(self, data=None):
return MD5Hash(data)
def new(data=None):
"""Return a fresh instance of the hash object.
:Parameters:
data : byte string
The very first chunk of the message to hash.
It is equivalent to an early call to `MD5Hash.update()`.
Optional.
:Return: A `MD5Hash` object
"""
return MD5Hash().new(data)
#: The size of the resulting hash in bytes.
digest_size = new().digest_size
digest_size = MD5Hash.digest_size
#: The internal block size of the hash algorithm in bytes.
block_size = new().block_size
block_size = MD5Hash.block_size

View File

@@ -18,9 +18,77 @@
# SOFTWARE.
# ===================================================================
# This file exists for backward compatibility with old code that refers to
# Crypto.Hash.RIPEMD
"""RIPEMD-160 cryptographic hash algorithm.
"""Deprecated alias for `Crypto.Hash.RIPEMD160`"""
RIPEMD-160_ produces the 160 bit digest of a message.
>>> from Crypto.Hash import RIPEMD
>>>
>>> h = RIPEMD.new()
>>> h.update(b'Hello')
>>> print h.hexdigest()
RIPEMD-160 stands for RACE Integrity Primitives Evaluation Message Digest
with a 160 bit digest. It was invented by Dobbertin, Bosselaers, and Preneel.
This algorithm is considered secure, although it has not been scrutinized as
extensively as SHA-1. Moreover, it provides an informal security level of just
80bits.
.. _RIPEMD-160: http://homes.esat.kuleuven.be/~bosselae/ripemd160.html
"""
_revision__ = "$Id$"
__all__ = ['new', 'digest_size', 'RIPEMD160Hash' ]
from Crypto.Util.py3compat import *
from Crypto.Hash.hashalgo import HashAlgo
import Crypto.Hash._RIPEMD160 as _RIPEMD160
hashFactory = _RIPEMD160
class RIPEMD160Hash(HashAlgo):
"""Class that implements a RIPMD-160 hash
:undocumented: block_size
"""
#: ASN.1 Object identifier (OID)::
#:
#: id-ripemd160 OBJECT IDENTIFIER ::= {
#: iso(1) identified-organization(3) teletrust(36)
#: algorithm(3) hashAlgorithm(2) ripemd160(1)
#: }
#:
#: This value uniquely identifies the RIPMD-160 algorithm.
oid = b("\x06\x05\x2b\x24\x03\x02\x01")
digest_size = 20
block_size = 64
def __init__(self, data=None):
HashAlgo.__init__(self, hashFactory, data)
def new(self, data=None):
return RIPEMD160Hash(data)
def new(data=None):
"""Return a fresh instance of the hash object.
:Parameters:
data : byte string
The very first chunk of the message to hash.
It is equivalent to an early call to `RIPEMD160Hash.update()`.
Optional.
:Return: A `RIPEMD160Hash` object
"""
return RIPEMD160Hash().new(data)
#: The size of the resulting hash in bytes.
digest_size = RIPEMD160Hash.digest_size
#: The internal block size of the hash algorithm in bytes.
block_size = RIPEMD160Hash.block_size
from Crypto.Hash.RIPEMD160 import new, block_size, digest_size

View File

@@ -18,7 +18,81 @@
# SOFTWARE.
# ===================================================================
# This file exists for backward compatibility with old code that refers to
# Crypto.Hash.SHA
"""SHA-1 cryptographic hash algorithm.
SHA-1_ produces the 160 bit digest of a message.
>>> from Crypto.Hash import SHA
>>>
>>> h = SHA.new()
>>> h.update(b'Hello')
>>> print h.hexdigest()
*SHA* stands for Secure Hash Algorithm.
This algorithm is not considered secure. Do not use it for new designs.
.. _SHA-1: http://csrc.nist.gov/publications/fips/fips180-2/fips180-2.pdf
"""
_revision__ = "$Id$"
__all__ = ['new', 'digest_size', 'SHA1Hash' ]
from Crypto.Util.py3compat import *
from Crypto.Hash.hashalgo import HashAlgo
try:
# The sha module is deprecated in Python 2.6, so use hashlib when possible.
import hashlib
hashFactory = hashlib.sha1
except ImportError:
import sha
hashFactory = sha
class SHA1Hash(HashAlgo):
"""Class that implements a SHA-1 hash
:undocumented: block_size
"""
#: ASN.1 Object identifier (OID)::
#:
#: id-sha1 OBJECT IDENTIFIER ::= {
#: iso(1) identified-organization(3) oiw(14) secsig(3)
#: algorithms(2) 26
#: }
#:
#: This value uniquely identifies the SHA-1 algorithm.
oid = b('\x06\x05\x2b\x0e\x03\x02\x1a')
digest_size = 20
block_size = 64
def __init__(self, data=None):
HashAlgo.__init__(self, hashFactory, data)
def new(self, data=None):
return SHA1Hash(data)
def new(data=None):
"""Return a fresh instance of the hash object.
:Parameters:
data : byte string
The very first chunk of the message to hash.
It is equivalent to an early call to `SHA1Hash.update()`.
Optional.
:Return: A `SHA1Hash` object
"""
return SHA1Hash().new(data)
#: The size of the resulting hash in bytes.
digest_size = SHA1Hash.digest_size
#: The internal block size of the hash algorithm in bytes.
block_size = SHA1Hash.block_size
from Crypto.Hash.SHA1 import __doc__, new, block_size, digest_size

View File

@@ -0,0 +1,95 @@
# -*- coding: utf-8 -*-
#
# ===================================================================
# 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.
# ===================================================================
"""SHA-224 cryptographic hash algorithm.
SHA-224 belongs to the SHA-2_ family of cryptographic hashes.
It produces the 224 bit digest of a message.
>>> from Crypto.Hash import SHA224
>>>
>>> h = SHA224.new()
>>> h.update(b'Hello')
>>> print h.hexdigest()
*SHA* stands for Secure Hash Algorithm.
.. _SHA-2: http://csrc.nist.gov/publications/fips/fips180-2/fips180-2.pdf
"""
_revision__ = "$Id$"
__all__ = ['new', 'digest_size', 'SHA224Hash' ]
from Crypto.Util.py3compat import *
from Crypto.Hash.hashalgo import HashAlgo
try:
import hashlib
hashFactory = hashlib.sha224
except ImportError:
from Crypto.Hash import _SHA224
hashFactory = _SHA224
class SHA224Hash(HashAlgo):
"""Class that implements a SHA-224 hash
:undocumented: block_size
"""
#: ASN.1 Object identifier (OID)::
#:
#: id-sha224 OBJECT IDENTIFIER ::= {
#: joint-iso-itu-t(2) country(16) us(840) organization(1) gov(101) csor(3)
#: nistalgorithm(4) hashalgs(2) 4
#: }
#:
#: This value uniquely identifies the SHA-224 algorithm.
oid = b('\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x04')
digest_size = 28
block_size = 64
def __init__(self, data=None):
HashAlgo.__init__(self, hashFactory, data)
def new(self, data=None):
return SHA224Hash(data)
def new(data=None):
"""Return a fresh instance of the hash object.
:Parameters:
data : byte string
The very first chunk of the message to hash.
It is equivalent to an early call to `SHA224Hash.update()`.
Optional.
:Return: A `SHA224Hash` object
"""
return SHA224Hash().new(data)
#: The size of the resulting hash in bytes.
digest_size = SHA224Hash.digest_size
#: The internal block size of the hash algorithm in bytes.
block_size = SHA224Hash.block_size

View File

@@ -0,0 +1,95 @@
# -*- coding: utf-8 -*-
#
# ===================================================================
# 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.
# ===================================================================
"""SHA-256 cryptographic hash algorithm.
SHA-256 belongs to the SHA-2_ family of cryptographic hashes.
It produces the 256 bit digest of a message.
>>> from Crypto.Hash import SHA256
>>>
>>> h = SHA256.new()
>>> h.update(b'Hello')
>>> print h.hexdigest()
*SHA* stands for Secure Hash Algorithm.
.. _SHA-2: http://csrc.nist.gov/publications/fips/fips180-2/fips180-2.pdf
"""
_revision__ = "$Id$"
__all__ = ['new', 'digest_size', 'SHA256Hash' ]
from Crypto.Util.py3compat import *
from Crypto.Hash.hashalgo import HashAlgo
try:
import hashlib
hashFactory = hashlib.sha256
except ImportError:
from Crypto.Hash import _SHA256
hashFactory = _SHA256
class SHA256Hash(HashAlgo):
"""Class that implements a SHA-256 hash
:undocumented: block_size
"""
#: ASN.1 Object identifier (OID)::
#:
#: id-sha256 OBJECT IDENTIFIER ::= {
#: joint-iso-itu-t(2) country(16) us(840) organization(1)
#: gov(101) csor(3) nistalgorithm(4) hashalgs(2) 1
#: }
#:
#: This value uniquely identifies the SHA-256 algorithm.
oid = b('\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x01')
digest_size = 32
block_size = 64
def __init__(self, data=None):
HashAlgo.__init__(self, hashFactory, data)
def new(self, data=None):
return SHA256Hash(data)
def new(data=None):
"""Return a fresh instance of the hash object.
:Parameters:
data : byte string
The very first chunk of the message to hash.
It is equivalent to an early call to `SHA256Hash.update()`.
Optional.
:Return: A `SHA256Hash` object
"""
return SHA256Hash().new(data)
#: The size of the resulting hash in bytes.
digest_size = SHA256Hash.digest_size
#: The internal block size of the hash algorithm in bytes.
block_size = SHA256Hash.block_size

View File

@@ -0,0 +1,96 @@
# -*- coding: utf-8 -*-
#
# ===================================================================
# 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.
# ===================================================================
"""SHA-384 cryptographic hash algorithm.
SHA-384 belongs to the SHA-2_ family of cryptographic hashes.
It produces the 384 bit digest of a message.
>>> from Crypto.Hash import SHA384
>>>
>>> h = SHA384.new()
>>> h.update(b'Hello')
>>> print h.hexdigest()
*SHA* stands for Secure Hash Algorithm.
.. _SHA-2: http://csrc.nist.gov/publications/fips/fips180-2/fips180-2.pdf
"""
_revision__ = "$Id$"
__all__ = ['new', 'digest_size', 'SHA384Hash' ]
from Crypto.Util.py3compat import *
from Crypto.Hash.hashalgo import HashAlgo
try:
import hashlib
hashFactory = hashlib.sha384
except ImportError:
from Crypto.Hash import _SHA384
hashFactory = _SHA384
class SHA384Hash(HashAlgo):
"""Class that implements a SHA-384 hash
:undocumented: block_size
"""
#: ASN.1 Object identifier (OID)::
#:
#: id-sha384 OBJECT IDENTIFIER ::= {
#: joint-iso-itu-t(2) country(16) us(840) organization(1) gov(101) csor(3)
#: nistalgorithm(4) hashalgs(2) 2
#: }
#:
#: This value uniquely identifies the SHA-384 algorithm.
oid = b('\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x02')
digest_size = 48
block_size = 128
def __init__(self, data=None):
HashAlgo.__init__(self, hashFactory, data)
def new(self, data=None):
return SHA384Hash(data)
def new(data=None):
"""Return a fresh instance of the hash object.
:Parameters:
data : byte string
The very first chunk of the message to hash.
It is equivalent to an early call to `SHA384Hash.update()`.
Optional.
:Return: A `SHA384Hash` object
"""
return SHA384Hash().new(data)
#: The size of the resulting hash in bytes.
digest_size = SHA384Hash.digest_size
#: The internal block size of the hash algorithm in bytes.
block_size = SHA384Hash.block_size

View File

@@ -0,0 +1,95 @@
# -*- coding: utf-8 -*-
#
# ===================================================================
# 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.
# ===================================================================
"""SHA-512 cryptographic hash algorithm.
SHA-512 belongs to the SHA-2_ family of cryptographic hashes.
It produces the 512 bit digest of a message.
>>> from Crypto.Hash import SHA512
>>>
>>> h = SHA512.new()
>>> h.update(b'Hello')
>>> print h.hexdigest()
*SHA* stands for Secure Hash Algorithm.
.. _SHA-2: http://csrc.nist.gov/publications/fips/fips180-2/fips180-2.pdf
"""
_revision__ = "$Id$"
__all__ = ['new', 'digest_size', 'SHA512Hash' ]
from Crypto.Util.py3compat import *
from Crypto.Hash.hashalgo import HashAlgo
try:
import hashlib
hashFactory = hashlib.sha512
except ImportError:
from Crypto.Hash import _SHA512
hashFactory = _SHA512
class SHA512Hash(HashAlgo):
"""Class that implements a SHA-512 hash
:undocumented: block_size
"""
#: ASN.1 Object identifier (OID)::
#:
#: id-sha512 OBJECT IDENTIFIER ::= {
#: joint-iso-itu-t(2)
#: country(16) us(840) organization(1) gov(101) csor(3) nistalgorithm(4) hashalgs(2) 3
#: }
#:
#: This value uniquely identifies the SHA-512 algorithm.
oid = b('\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x03')
digest_size = 64
block_size = 128
def __init__(self, data=None):
HashAlgo.__init__(self, hashFactory, data)
def new(self, data=None):
return SHA512Hash(data)
def new(data=None):
"""Return a fresh instance of the hash object.
:Parameters:
data : byte string
The very first chunk of the message to hash.
It is equivalent to an early call to `SHA512Hash.update()`.
Optional.
:Return: A `SHA512Hash` object
"""
return SHA512Hash().new(data)
#: The size of the resulting hash in bytes.
digest_size = SHA512Hash.digest_size
#: The internal block size of the hash algorithm in bytes.
block_size = SHA512Hash.block_size

BIN
modules/Crypto/Hash/_MD2.so Executable file

Binary file not shown.

BIN
modules/Crypto/Hash/_MD4.so Executable file

Binary file not shown.

BIN
modules/Crypto/Hash/_RIPEMD160.so Executable file

Binary file not shown.

BIN
modules/Crypto/Hash/_SHA224.so Executable file

Binary file not shown.

BIN
modules/Crypto/Hash/_SHA256.so Executable file

Binary file not shown.

BIN
modules/Crypto/Hash/_SHA384.so Executable file

Binary file not shown.

BIN
modules/Crypto/Hash/_SHA512.so Executable file

Binary file not shown.

View File

@@ -49,128 +49,8 @@ The hashing modules here all support the interface described in `PEP
:undocumented: _MD2, _MD4, _RIPEMD160, _SHA224, _SHA256, _SHA384, _SHA512
"""
__all__ = ['HMAC', 'MD2', 'MD4', 'MD5', 'RIPEMD160', 'SHA1',
'SHA224', 'SHA256', 'SHA384', 'SHA512', 'CMAC']
__all__ = ['HMAC', 'MD2', 'MD4', 'MD5', 'RIPEMD', 'SHA',
'SHA224', 'SHA256', 'SHA384', 'SHA512']
__revision__ = "$Id$"
import sys
if sys.version_info[0] == 2 and sys.version_info[1] == 1:
from Crypto.Util.py21compat import *
from Crypto.Util.py3compat import *
def new(algo, *args):
"""Initialize a new hash object.
The first argument to this function may be an algorithm name or another
hash object.
This function has significant overhead. It's recommended that you instead
import and use the individual hash modules directly.
"""
# Try just invoking algo.new()
# We do this first so that this is the fastest.
try:
new_func = algo.new
except AttributeError:
pass
else:
return new_func(*args)
# Try getting the algorithm name.
if isinstance(algo, str):
name = algo
else:
try:
name = algo.name
except AttributeError:
raise ValueError("unsupported hash type %r" % (algo,))
# Got the name. Let's see if we have a PyCrypto implementation.
try:
new_func = _new_funcs[name]
except KeyError:
# No PyCrypto implementation. Try hashlib.
try:
import hashlib
except ImportError:
# There is no hashlib.
raise ValueError("unsupported hash type %s" % (name,))
return hashlib.new(name, *args)
else:
# We have a PyCrypto implementation. Instantiate it.
return new_func(*args)
# This dict originally gets the following _*_new methods, but its members get
# replaced with the real new() methods of the various hash modules as they are
# used. We do it without locks to improve performance, which is safe in
# CPython because dict access is atomic in CPython. This might break PyPI.
_new_funcs = {}
def _md2_new(*args):
from Crypto.Hash import MD2
_new_funcs['MD2'] = _new_funcs['md2'] = MD2.new
return MD2.new(*args)
_new_funcs['MD2'] = _new_funcs['md2'] = _md2_new
del _md2_new
def _md4_new(*args):
from Crypto.Hash import MD4
_new_funcs['MD4'] = _new_funcs['md4'] = MD4.new
return MD4.new(*args)
_new_funcs['MD4'] = _new_funcs['md4'] = _md4_new
del _md4_new
def _md5_new(*args):
from Crypto.Hash import MD5
_new_funcs['MD5'] = _new_funcs['md5'] = MD5.new
return MD5.new(*args)
_new_funcs['MD5'] = _new_funcs['md5'] = _md5_new
del _md5_new
def _ripemd160_new(*args):
from Crypto.Hash import RIPEMD160
_new_funcs['RIPEMD160'] = _new_funcs['ripemd160'] = \
_new_funcs['RIPEMD'] = _new_funcs['ripemd'] = RIPEMD160.new
return RIPEMD160.new(*args)
_new_funcs['RIPEMD160'] = _new_funcs['ripemd160'] = \
_new_funcs['RIPEMD'] = _new_funcs['ripemd'] = _ripemd160_new
del _ripemd160_new
def _sha1_new(*args):
from Crypto.Hash import SHA1
_new_funcs['SHA1'] = _new_funcs['sha1'] = \
_new_funcs['SHA'] = _new_funcs['sha'] = SHA1.new
return SHA1.new(*args)
_new_funcs['SHA1'] = _new_funcs['sha1'] = \
_new_funcs['SHA'] = _new_funcs['sha'] = _sha1_new
del _sha1_new
def _sha224_new(*args):
from Crypto.Hash import SHA224
_new_funcs['SHA224'] = _new_funcs['sha224'] = SHA224.new
return SHA224.new(*args)
_new_funcs['SHA224'] = _new_funcs['sha224'] = _sha224_new
del _sha224_new
def _sha256_new(*args):
from Crypto.Hash import SHA256
_new_funcs['SHA256'] = _new_funcs['sha256'] = SHA256.new
return SHA256.new(*args)
_new_funcs['SHA256'] = _new_funcs['sha256'] = _sha256_new
del _sha256_new
def _sha384_new(*args):
from Crypto.Hash import SHA384
_new_funcs['SHA384'] = _new_funcs['sha384'] = SHA384.new
return SHA384.new(*args)
_new_funcs['SHA384'] = _new_funcs['sha384'] = _sha384_new
del _sha384_new
def _sha512_new(*args):
from Crypto.Hash import SHA512
_new_funcs['SHA512'] = _new_funcs['sha512'] = SHA512.new
return SHA512.new(*args)
_new_funcs['SHA512'] = _new_funcs['sha512'] = _sha512_new
del _sha512_new

View File

@@ -0,0 +1,116 @@
# -*- coding: utf-8 -*-
#
# ===================================================================
# 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.
# ===================================================================
from binascii import hexlify
class HashAlgo:
"""A generic class for an abstract cryptographic hash algorithm.
:undocumented: block_size
"""
#: The size of the resulting hash in bytes.
digest_size = None
#: The internal block size of the hash algorithm in bytes.
block_size = None
def __init__(self, hashFactory, data=None):
"""Initialize the hash object.
:Parameters:
hashFactory : callable
An object that will generate the actual hash implementation.
*hashFactory* must have a *new()* method, or must be directly
callable.
data : byte string
The very first chunk of the message to hash.
It is equivalent to an early call to `update()`.
"""
if hasattr(hashFactory, 'new'):
self._hash = hashFactory.new()
else:
self._hash = hashFactory()
if data:
self.update(data)
def update(self, data):
"""Continue hashing 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:
data : byte string
The next chunk of the message being hashed.
"""
return self._hash.update(data)
def digest(self):
"""Return the **binary** (non-printable) digest of the message that has been hashed so far.
This method does not change the state of the hash 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 self._hash.digest()
def hexdigest(self):
"""Return the **printable** digest of the message that has been hashed so far.
This method does not change the state of the hash object.
:Return: A string of 2* `digest_size` characters. It contains only
hexadecimal ASCII digits.
"""
return self._hash.hexdigest()
def copy(self):
"""Return a copy ("clone") of the hash object.
The copy will have the same internal state as the original hash
object.
This can be used to efficiently compute the digests of strings that
share a common initial substring.
:Return: A hash object of the same type
"""
return self._hash.copy()
def new(self, data=None):
"""Return a fresh instance of the hash object.
Unlike the `copy` method, the internal state of the object is empty.
:Parameters:
data : byte string
The next chunk of the message being hashed.
:Return: A hash object of the same type
"""
pass