#!/usr/bin/python
# -*- coding: UTF-8 -*-

import binascii
import hashlib

from .rand import random_data

class pbkdf2( object ):
    def __init__( self, word, salt = None, iterations = 20000, hash_name = "sha512" ):
        if salt != None and salt.startswith( "pbkdf2$" ):
            self.word = word
            self.stored_hash = salt
            _, self.hash_name, self.salt, self.iterations, self.h = salt.split( "$" )
            self.iterations = int( self.iterations )
        
        else:
            self.word = word
            self.salt = salt or random_data( 100 )
            self.iterations = int( iterations )
            self.hash_name = hash_name
            self.stored_hash = None
            self.h = None
    
    def hash( self, hash_only = False ):
        h = hashlib.pbkdf2_hmac( self.hash_name, self.word, self.salt, self.iterations )
        h = binascii.hexlify( h )
        
        if hash_only:
            return h
        else:
            return "$".join( map( str, [ "pbkdf2", self.hash_name, self.salt, self.iterations, h ] ) )
    
    def verify( self ):
        return self.stored_hash == self.hash()
