0
\$\begingroup\$

I found this old code in one of the old files of mine which I have converted into Python3 but not very much satisfied and cannot reproduce the whole thing especially decoding it in check_password function.

#!/usr/bin/python2.7
# Imports
from hashlib import sha256
from hmac import HMAC
import random

# random bytes function convert random number into random 64-bit bytes
def random_bytes(num_bytes):
  return "".join(chr(random.randrange(256)) for i in xrange(num_bytes))

# password based key derivation function with number of iterations
def pbkdf_sha256(password, salt, iterations):
  result = password
  for i in xrange(iterations):
    result = HMAC(result, salt, sha256).digest()  # use HMAC to apply the salt
  return result


NUM_ITERATIONS = 5000

#hashing password and producing hashed password as well as salt
def hash_password(plain_password):
  salt = random_bytes(8)  # 64 bits

  hashed_password = pbkdf_sha256(plain_password, salt, NUM_ITERATIONS)

  # return the salt and hashed password, encoded in base64 and split with ","
  return salt.encode("base64").strip() + "," + hashed_password.encode("base64").strip()

# check hashed_password that returns true if properly decoded
def check_password(saved_password_entry, plain_password):
  salt, hashed_password = saved_password_entry.split(",")
  salt = salt.decode("base64")
  hashed_password = hashed_password.decode("base64")

  return hashed_password == pbkdf_sha256(plain_password, salt, NUM_ITERATIONS)


password_entry = hash_password("mysecret")
# will print, for example: 8Y1ZO8Y1pi4=,r7Acg5iRiZ/x4QwFLhPMjASESxesoIcdJRSDkqWYfaA=
print password_entry
print check_password(password_entry, "mysecret")  # returns True
\$\endgroup\$
2
  • \$\begingroup\$ What do you mean when you say you cannot reproduce the whole thing? As in, parts were unable to be converted to Python 3? \$\endgroup\$ – Reinderien Jan 31 at 2:43
  • \$\begingroup\$ @Reinderien I mean that after using 2to3 with -w option I was able to make it work by making further changes and almost all the parts are working except check_password part as that part is always giving errors of Unicode. \$\endgroup\$ – S Habeeb Ullah Mar 4 at 15:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.