Guest User

Untitled

a guest
Feb 18th, 2018
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.19 KB | None | 0 0
  1. import hashlib
  2. from string import printable
  3. from time import time
  4. import itertools
  5. from array import array
  6.  
  7. ENCODING = "ascii" # utf-8 for unicode support
  8.  
  9. class CharSet():
  10. def __init__(self, chars):
  11. chars = to_bytes(chars)
  12. self.chars = set(chars)
  13. self.first = chars[0]
  14. self.last = chars[-1]
  15. self.next = array("B", [0] * 256)
  16. for char, next_char in zip(chars, chars[1:]):
  17. self.next[char] = next_char
  18.  
  19. def update_chars(self, new_chars):
  20. new_chars = to_bytes(new_chars)
  21. new_chars = set(new_chars) - self.chars
  22. if new_chars: # if theres anything new
  23. self.chars |= new_chars
  24. new_chars = list(new_chars)
  25. self.next[self.last] = new_chars[0]
  26. self.last = new_chars[-1]
  27. for char, next_char in zip(new_chars, new_chars[1:]):
  28. self.next[char] = next_char
  29.  
  30. def get_advance(self, arr, hash_):
  31. first = self.first
  32. last = self.last
  33. next_ = self.next
  34. def advance():
  35. for ind, byte in enumerate(arr):
  36. if byte == last:
  37. arr[ind] = first
  38. else:
  39. arr[ind] = next_[byte]
  40. return hash_(arr)
  41.  
  42. arr.append(first)
  43. return hash_(arr)
  44.  
  45. return advance
  46.  
  47. class PasswordCracker():
  48. def __init__(self, hash_, chars=None):
  49. self.hash = hash_
  50. if chars is None:
  51. chars = printable
  52. self.char_set = CharSet(chars)
  53.  
  54. def update_chars(self, string):
  55. self.char_set.update_chars(string)
  56.  
  57. def crack(self, hashed):
  58. arr = bytearray()
  59. advance = self.char_set.get_advance(arr, self.hash)
  60. for _ in iter(advance, hashed):
  61. pass
  62. return arr
  63.  
  64. def to_bytes(string):
  65. if isinstance(string, str):
  66. return bytearray(string, ENCODING)
  67. elif isinstance(string, (bytes, bytearray)):
  68. return string
  69. else:
  70. raise TypeError(f"Cannot convert {string} to bytes")
  71.  
  72. def get_hasher(hash_):
  73. def hasher(bytes):
  74. return hash_(bytes).digest()
  75.  
  76. return hasher
  77.  
  78. md5 = get_hasher(hashlib.md5)
  79.  
  80. cracker = PasswordCracker(md5)
  81.  
  82. password = input("Enter password: ")
  83.  
  84. cracker.update_chars(password)
  85. password = md5(to_bytes(password))
  86.  
  87. start = time()
  88. cracked = cracker.crack(password)
  89. end = time()
  90. print(f"Password cracked: {cracked.decode(ENCODING)}")
  91. print(f"Time: {end - start} seconds.")
Add Comment
Please, Sign In to add comment