1
0

md5crypt.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. #!/usr/local/bin/python
  2. # Based on FreeBSD src/lib/libcrypt/crypt.c 1.2
  3. # http://www.freebsd.org/cgi/cvsweb.cgi/~checkout~/src/lib/libcrypt/crypt.c?rev=1.2&content-type=text/plain
  4. # Original license:
  5. # * "THE BEER-WARE LICENSE" (Revision 42):
  6. # * <phk@login.dknet.dk> wrote this file. As long as you retain this notice you
  7. # * can do whatever you want with this stuff. If we meet some day, and you think
  8. # * this stuff is worth it, you can buy me a beer in return. Poul-Henning Kamp
  9. # This port adds no further stipulations. I forfeit any copyright interest.
  10. import md5
  11. def _md5crypt(password, the_hash):
  12. magic, salt = the_hash[1:].split('$')[:2]
  13. magic = '$' + magic + '$'
  14. # /* The password first, since that is what is most unknown */ /* Then our magic string */ /* Then the raw salt */
  15. m = md5.new()
  16. m.update(password + magic + salt)
  17. # /* Then just as many characters of the MD5(pw,salt,pw) */
  18. mixin = md5.md5(password + salt + password).digest()
  19. for i in range(0, len(password)):
  20. m.update(mixin[i % 16])
  21. # /* Then something really weird... */
  22. # Also really broken, as far as I can tell. -m
  23. i = len(password)
  24. while i:
  25. if i & 1:
  26. m.update('\x00')
  27. else:
  28. m.update(password[0])
  29. i >>= 1
  30. final = m.digest()
  31. # /* and now, just to make sure things don't run too fast */
  32. for i in range(1000):
  33. m2 = md5.md5()
  34. if i & 1:
  35. m2.update(password)
  36. else:
  37. m2.update(final)
  38. if i % 3:
  39. m2.update(salt)
  40. if i % 7:
  41. m2.update(password)
  42. if i & 1:
  43. m2.update(final)
  44. else:
  45. m2.update(password)
  46. final = m2.digest()
  47. # This is the bit that uses to64() in the original code.
  48. itoa64 = './0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
  49. rearranged = ''
  50. for a, b, c in ((0, 6, 12), (1, 7, 13), (2, 8, 14), (3, 9, 15), (4, 10, 5)):
  51. v = ord(final[a]) << 16 | ord(final[b]) << 8 | ord(final[c])
  52. for i in range(4):
  53. rearranged += itoa64[v & 0x3f]; v >>= 6
  54. v = ord(final[11])
  55. for i in range(2):
  56. rearranged += itoa64[v & 0x3f]; v >>= 6
  57. return magic + salt + '$' + rearranged
  58. word = "joefoo1234"
  59. magicsalt = "$1$kBmmDTGr"
  60. magic, salt = magicsalt[1:].split('$')[:2]
  61. magic = '$' + magic + '$'
  62. hashword = _md5crypt(word, magic + salt)
  63. from crypt import crypt as _crypt
  64. if _crypt(word, hashword) == '$1$kBmmDTGr$FngxLa03zfySCR3dZTdXS1':
  65. md5crypt = _crypt
  66. else:
  67. md5crypt = _md5crypt