pythoncryptographyrainbowtable

TypeError: must be string or buffer, not int


i am trying to solve the Rainbow Tables issue with password encryption and have come only this far.

import sys
import random
import hashlib

def mt_rand (low = 0, high = sys.maxint):
    """Generate a better random value
    """
    return random.randint (low, high)

def substr (s, start, length = None):
    """Returns the portion of string specified by the start and length
    parameters.
    """
    if len(s) >= start:
        return False
    if not length:
        return s[start:]
    elif length > 0:
        return s[start:start + length]
    else:
        return s[start:length]

def unique_salt():
    return substr(hashlib.sha1(mt_rand()),0,22)

password = "12345"
salt = unique_salt()
hash = hashlib.sha1(salt + password).hexdigest()
print(hash)

I am getting this error:

Traceback (most recent call last):
  File "C:/Users/Ajay/PycharmProjects/itertools/test.py", line 27, in <module>
    salt = unique_salt()
  File "C:/Users/Ajay/PycharmProjects/itertools/test.py", line 24, in unique_salt
    return substr(hashlib.sha1(mt_rand()),0,22)
TypeError: must be string or buffer, not int

I know i am missing something very trivial but cant get where i am missing. Please Help.


Solution

  • hashlib.sha1 accepts a string as a parameter.

    >>> import hashlib
    >>> hashlib.sha1('asdf')
    <sha1 HASH object @ 0000000002B97DF0>
    

    But you're passing a int object. (The return value of the random.randint is int object as the name suggest)

    >>> hashlib.sha1(1234)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: must be string or buffer, not int
    

    You can use os.urandom to generate random string:

    >>> import os
    >>> hashlib.sha1(os.urandom(10)) # `os.urandom(10)` generate 10-bytes random string.
    <sha1 HASH object @ 0000000002B97F30>
    >>> hashlib.sha1(os.urandom(10)).digest()
    '\x0c.y\x08\x13\xf0\x16.\xea\x05\x03\x07{6H\xa0U\xfe\xdfT'
    >>> hashlib.sha1(os.urandom(10)).hexdigest()
    '6e33d9cfdbd7ffcf062ee502eaa25893f618fcff'