KDF.py 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123
  1. #
  2. # KDF.py : a collection of Key Derivation Functions
  3. #
  4. # Part of the Python Cryptography Toolkit
  5. #
  6. # ===================================================================
  7. # The contents of this file are dedicated to the public domain. To
  8. # the extent that dedication to the public domain is not available,
  9. # everyone is granted a worldwide, perpetual, royalty-free,
  10. # non-exclusive license to exercise all rights associated with the
  11. # contents of this file for any purpose whatsoever.
  12. # No rights are reserved.
  13. #
  14. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  15. # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  16. # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  17. # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
  18. # BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
  19. # ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  20. # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  21. # SOFTWARE.
  22. # ===================================================================
  23. """This file contains a collection of standard key derivation functions.
  24. A key derivation function derives one or more secondary secret keys from
  25. one primary secret (a master key or a pass phrase).
  26. This is typically done to insulate the secondary keys from each other,
  27. to avoid that leakage of a secondary key compromises the security of the
  28. master key, or to thwart attacks on pass phrases (e.g. via rainbow tables).
  29. :undocumented: __revision__
  30. """
  31. __revision__ = "$Id$"
  32. import math
  33. import struct
  34. from Crypto.Util.py3compat import *
  35. from Crypto.Hash import SHA as SHA1, HMAC
  36. from Crypto.Util.strxor import strxor
  37. def PBKDF1(password, salt, dkLen, count=1000, hashAlgo=None):
  38. """Derive one key from a password (or passphrase).
  39. This function performs key derivation according an old version of
  40. the PKCS#5 standard (v1.5).
  41. This algorithm is called ``PBKDF1``. Even though it is still described
  42. in the latest version of the PKCS#5 standard (version 2, or RFC2898),
  43. newer applications should use the more secure and versatile `PBKDF2` instead.
  44. :Parameters:
  45. password : string
  46. The secret password or pass phrase to generate the key from.
  47. salt : byte string
  48. An 8 byte string to use for better protection from dictionary attacks.
  49. This value does not need to be kept secret, but it should be randomly
  50. chosen for each derivation.
  51. dkLen : integer
  52. The length of the desired key. Default is 16 bytes, suitable for instance for `Crypto.Cipher.AES`.
  53. count : integer
  54. The number of iterations to carry out. It's recommended to use at least 1000.
  55. hashAlgo : module
  56. The hash algorithm to use, as a module or an object from the `Crypto.Hash` package.
  57. The digest length must be no shorter than ``dkLen``.
  58. The default algorithm is `SHA1`.
  59. :Return: A byte string of length `dkLen` that can be used as key.
  60. """
  61. if not hashAlgo:
  62. hashAlgo = SHA1
  63. password = tobytes(password)
  64. pHash = hashAlgo.new(password+salt)
  65. digest = pHash.digest_size
  66. if dkLen>digest:
  67. raise ValueError("Selected hash algorithm has a too short digest (%d bytes)." % digest)
  68. if len(salt)!=8:
  69. raise ValueError("Salt is not 8 bytes long.")
  70. for i in xrange(count-1):
  71. pHash = pHash.new(pHash.digest())
  72. return pHash.digest()[:dkLen]
  73. def PBKDF2(password, salt, dkLen=16, count=1000, prf=None):
  74. """Derive one or more keys from a password (or passphrase).
  75. This performs key derivation according to the PKCS#5 standard (v2.0),
  76. by means of the ``PBKDF2`` algorithm.
  77. :Parameters:
  78. password : string
  79. The secret password or pass phrase to generate the key from.
  80. salt : string
  81. A string to use for better protection from dictionary attacks.
  82. This value does not need to be kept secret, but it should be randomly
  83. chosen for each derivation. It is recommended to be at least 8 bytes long.
  84. dkLen : integer
  85. The cumulative length of the desired keys. Default is 16 bytes, suitable for instance for `Crypto.Cipher.AES`.
  86. count : integer
  87. The number of iterations to carry out. It's recommended to use at least 1000.
  88. prf : callable
  89. A pseudorandom function. It must be a function that returns a pseudorandom string
  90. from two parameters: a secret and a salt. If not specified, HMAC-SHA1 is used.
  91. :Return: A byte string of length `dkLen` that can be used as key material.
  92. If you wanted multiple keys, just break up this string into segments of the desired length.
  93. """
  94. password = tobytes(password)
  95. if prf is None:
  96. prf = lambda p,s: HMAC.new(p,s,SHA1).digest()
  97. key = b('')
  98. i = 1
  99. while len(key)<dkLen:
  100. U = previousU = prf(password,salt+struct.pack(">I", i))
  101. for j in xrange(count-1):
  102. previousU = t = prf(password,previousU)
  103. U = strxor(U,t)
  104. key += U
  105. i = i + 1
  106. return key[:dkLen]