SHA1.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. # -*- coding: utf-8 -*-
  2. #
  3. # ===================================================================
  4. # The contents of this file are dedicated to the public domain. To
  5. # the extent that dedication to the public domain is not available,
  6. # everyone is granted a worldwide, perpetual, royalty-free,
  7. # non-exclusive license to exercise all rights associated with the
  8. # contents of this file for any purpose whatsoever.
  9. # No rights are reserved.
  10. #
  11. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  12. # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  13. # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  14. # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
  15. # BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
  16. # ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  17. # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  18. # SOFTWARE.
  19. # ===================================================================
  20. from Crypto.Util.py3compat import *
  21. __all__ = ['new', 'block_size', 'digest_size']
  22. def __make_constructor():
  23. try:
  24. # The sha module is deprecated in Python 2.6, so use hashlib when possible.
  25. from hashlib import sha1 as _hash_new
  26. except ImportError:
  27. from sha import new as _hash_new
  28. h = _hash_new()
  29. if hasattr(h, 'new') and hasattr(h, 'name') and hasattr(h, 'digest_size') and hasattr(h, 'block_size'):
  30. # The module from stdlib has the API that we need. Just use it.
  31. return _hash_new
  32. else:
  33. # Wrap the hash object in something that gives us the expected API.
  34. _copy_sentinel = object()
  35. class _SHA1(object):
  36. digest_size = 20
  37. block_size = 64
  38. oid = "1.3.14.3.2.26"
  39. def __init__(self, *args):
  40. if args and args[0] is _copy_sentinel:
  41. self._h = args[1]
  42. else:
  43. self._h = _hash_new(*args)
  44. def copy(self):
  45. return _SHA1(_copy_sentinel, self._h.copy())
  46. def update(self, *args):
  47. f = self.update = self._h.update
  48. f(*args)
  49. def digest(self):
  50. f = self.digest = self._h.digest
  51. return f()
  52. def hexdigest(self):
  53. f = self.hexdigest = self._h.hexdigest
  54. return f()
  55. _SHA1.new = _SHA1
  56. return _SHA1
  57. new = __make_constructor()
  58. del __make_constructor
  59. # The size of the resulting hash in bytes.
  60. digest_size = new().digest_size
  61. # The internal block size of the hash algorithm in bytes.
  62. block_size = new().block_size