Click here to Skip to main content
15,886,519 members
Home / Discussions / Web Development
   

Web Development

 
Questionpassing id using@url.Action Pin
svknair26-Oct-17 23:59
svknair26-Oct-17 23:59 
AnswerRe: passing id using@url.Action Pin
Nathan Minier27-Oct-17 1:33
professionalNathan Minier27-Oct-17 1:33 
QuestionEF6 and MVC - Models *and* ViewModels? Pin
#realJSOP24-Oct-17 4:58
mve#realJSOP24-Oct-17 4:58 
PraiseRe: EF6 and MVC - Models *and* ViewModels? Pin
Richard Deeming24-Oct-17 5:30
mveRichard Deeming24-Oct-17 5:30 
GeneralRe: EF6 and MVC - Models *and* ViewModels? Pin
#realJSOP24-Oct-17 6:36
mve#realJSOP24-Oct-17 6:36 
GeneralRe: EF6 and MVC - Models *and* ViewModels? Pin
Richard Deeming24-Oct-17 6:40
mveRichard Deeming24-Oct-17 6:40 
AnswerRe: EF6 and MVC - Models *and* ViewModels? Pin
Nathan Minier25-Oct-17 1:47
professionalNathan Minier25-Oct-17 1:47 
Questionpassword hasher Pin
Member 1347817421-Oct-17 20:38
Member 1347817421-Oct-17 20:38 
hye there . i try to customize my own password hashers by using honeyword hashers but i still cannot import the honeyword generator file into the hashers file . i already follow django documentation for the hashers.py

honeywordgen.py :

import hashlib
import string
import re
from django.db import models 
from django.contrib.auth.hashers import PBKDF2PasswordHasher
from django.utils.crypto import constant_time_compare
from django.utils.translation import ugettext_noop as _
from random import random, randrange, choice, sample

TOUGH_NUT_PROBABILITY = 0.10
RANDOM_WORD_PROBABILITY = 0.03
EQUIV_CHAR_REPLACE_PROBABILITY = 0.25
MAX_PASSWORD_LENGTH = 256
PASSWORD_PUNCTUATION = '!@#$%^&*+-?'
ALL_PASSWORD_CHARS = string.ascii_letters + string.digits + PASSWORD_PUNCTUATION
VOWELS = 'aeiou'
LETTERS = string.ascii_lowercase
CONSONANTS = string.join([c for c in string.ascii_lowercase
                          if c not in VOWELS], '')
# h, j, k, q, w, x, y are rarely doubled
DOUBLE_CONSONANTS = [c + c for c in CONSONANTS if c not in 'hjkqwxy']

def closed_syllable():
    return choice(CONSONANTS) + choice(VOWELS) + choice(CONSONANTS)


def open_syllable():
    return choice(CONSONANTS) + choice(VOWELS)


def vce_syllable():
    r = random()
    v = ''
    if r < 0.95:
        v = choice([c for c in VOWELS if c != 'e'])
    else:
        v = choice(VOWELS)
    return v + choice(CONSONANTS) + 'e'


def vowel_team_syllable():
    r = random()
    if r < 0.30:
        return choice(['oo', 'ee'])
    if r < 0.70:
        v = choice(VOWELS)
        return v + choice([c for c in VOWELS if c != v])
    if r < 0.80:
        return choice(['ey', 'ay', 'oy', 'uy'])
    if r < 0.90:
        return choice(['ew', 'aw', 'ow'])
    # e.g. apprecia*tion*
    return (choice(CONSONANTS) + choice(VOWELS) + choice(VOWELS) +
            choice(CONSONANTS))


def vowel_r_syllable():
    r = random()
    if r < 0.50:
        return choice(CONSONANTS) + choice(VOWELS) + 'r'
    return choice(VOWELS) + 'r'


def c_le_syllable():
    return choice(CONSONANTS) + 'le'


def generate_syllable():
    c = ''
    r = random()
    if r > 0.80:
        c += choice(CONSONANTS)

    return c + choice([
        closed_syllable,
        open_syllable,
        vce_syllable,
        vowel_team_syllable,
        vowel_r_syllable,
        c_le_syllable
    ])()


def generate_syllable_num():
    r = random()
    if r < 0.05:
        return 1
    if r < 0.65:
        return 2
    if r < 0.90:
        return 3
    if r < 0.95:
        return 4
    if r < 0.98:
        return 5
    return 6


def generate_word():
    word = ''
    num_syllables = generate_syllable_num()

    for i in range(num_syllables):
        word += generate_syllable()

    while len(word) < 4:
        word += generate_syllable()

    return word


def tough_nut_length():
    # Determines a length for a toughnut password from 2-256
    # The lengths follow a rough guesstimate of the probability for different
    # length toughnut passwords (i.e., between 10 and 25 is most likely).
    r = random()
    if r < 0.05:
        return randrange(2, 5)
    if r < 0.45:
        return randrange(5, 10)
    if r < 0.90:
        return randrange(10, 25)
    if r < 0.95:
        return randrange(25, 100)
    return randrange(100, MAX_PASSWORD_LENGTH + 1)


def generate_tough_nut():
    # Tough nut passwords are simply strings populated with random characters
    char_count = tough_nut_length()
    toughie = []
    for i in range(char_count):
        toughie.append(choice(ALL_PASSWORD_CHARS))
    return string.join(toughie, '')


def generate_seed(tough_nut_prob=TOUGH_NUT_PROBABILITY):
    r = random()
    if r < tough_nut_prob:
        return generate_tough_nut()
    return generate_word()

def can_equal_char_replace(password):
    return any([True for c in password if c in 'AELOSTaelost@310$7@310$7'])


def tweak_equal_char_replace(password):
    for i in range(len(password)):
        # This is the current character at index i, and the left and right
        # substrings
        password_loc = password[i:i+1]
        password_left = password[:i]
        password_right = password[i+1:]

        # If the letter is any of the ones listed replace with new character
        # with a predefined probability
        if (random() < EQUIV_CHAR_REPLACE_PROBABILITY and
           ('A' in password_loc or 'a' in password_loc)):
            if random() < 0.50:
                password = password_left+str('4')+password_right
            else:
                password = password_left+str('@')+password_right
        if (random() < EQUIV_CHAR_REPLACE_PROBABILITY
           and ('o' in password_loc or 'O' in password_loc)):
            password = password_left+str('0')+password_right
        if (random() < EQUIV_CHAR_REPLACE_PROBABILITY
           and 'e' in password_loc):
            password = password_left+str('3')+password_right
        if (random() < EQUIV_CHAR_REPLACE_PROBABILITY
           and 'l' in password_loc):
            password = password_left+str('1')+password_right
        if (random() < EQUIV_CHAR_REPLACE_PROBABILITY
           and 's' in password_loc):
            password = password_left+str('$')+password_right
        if (random() < EQUIV_CHAR_REPLACE_PROBABILITY
           and 'T' in password_loc):
            password = password_left+str('7')+password_right
    return password


def can_capitalize(password):
    return any(c.isalpha() for c in password)


def tweak_capitalize(password):
    r = random()
    if r < 0.40 and password.title() != password:
        return password.title()
    elif r < 0.60 and password.lower() != password:
        return password.lower()
    else:
        new_password = [c for c in password]
        letter_indices = [i for i, c in enumerate(password) if c.isalpha()]
        for i in sample(letter_indices, randrange(len(letter_indices))):
            c = new_password[i]
            if c in string.ascii_uppercase:
                new_password[i] = c.lower()
            elif c in string.ascii_lowercase:
                new_password[i] = c.upper()

        return string.join(new_password, '')


def can_add_vowel(password):
    countVowels = 0
    for c in password:
        if c in VOWELS:
            countVowels += 1
    return countVowels > 0


def tweak_add_vowel(password):
    s = ''
    for c in password:
        if c in VOWELS:
            for i in range(randrange(1, 4)):
                s += c
        else:
            s += c
    return s


def can_append(password):
    return True


def tweak_append(password):
    # new_password = [c for c in password]
    r = random()

    append_chars = randrange(1, 5)
    if append_chars == 1:
        if r < 0.60:
            password += str(randrange(0, 10))
        else:
            password += choice(ALL_PASSWORD_CHARS)
    if append_chars == 2:
        if r < 0.60:
            # recent decades
            password += str(randrange(50, 100))
        elif r < 0.90:
            # other 2 digit pairs
            password += str(randrange(0, 50))
        else:
            # 2 random characters
            password += string.join(sample(ALL_PASSWORD_CHARS, 2), '')
    if append_chars == 4:
        if r < 0.80:
            # 1950-1999
            if r < 0.70:
                password += '19' + str(randrange(50, 100))
            # 2000 - 2020
            else:
                password += '20' + str(randrange(0, 21))
        elif r < 0.90:
            # any 4 random digits
            password += string.join([choice(string.digits)
                                     for i in range(4)], '')
        else:
            # any 4 random characters
            password += string.join(sample(ALL_PASSWORD_CHARS, 2), '')
    else:
        password += string.join([choice(ALL_PASSWORD_CHARS)
                                 for i in range(append_chars)], '')

    # "Pluralize" every so often when password ends in a letter
    last_pos = len(password) - 1
    if r < 0.20 and password[last_pos] != 's':
        if password[last_pos] in string.ascii_lowercase:
            password += 's'
        elif password[last_pos] in string.ascii_uppercase:
            password += 'S'

    return password


def can_digit_tweak(password):
    # Digit tweak can only be applied when there are digits in password
    return any([True for c in password if c in string.digits])


def tweak_digits(password):
    new_password = [c for c in password]
    for i, c in enumerate(new_password):
        if c in string.digits:
            new_password[i] = string.digits[randrange(len(string.digits))]
    return string.join(new_password, '')


def can_tweak_tail(password):
    # The tail tweaking method can always be applied
    return True


def tweak_tail(password):
    tweak_chars = randrange(0, len(password))
    new_password = [c for c in password]
    for i in range(tweak_chars, -1, -1):
        pos = len(password) - 1 - i
        c = new_password[pos]
        if c in string.ascii_lowercase:
            new_password[pos] = choice(string.ascii_lowercase)
        elif c in string.ascii_uppercase:
            new_password[pos] = choice(string.ascii_uppercase)
        elif c in string.digits:
            new_password[pos] = choice(string.digits)
        elif c in PASSWORD_PUNCTUATION:
            new_password[pos] = choice(PASSWORD_PUNCTUATION)
        else:
            new_password[pos] = choice(string.ascii_letters)

    return string.join(new_password, '')


def select_tweak_func(password):
    funcs = []
    if can_digit_tweak(password):
        funcs.append(tweak_digits)
    if can_append(password):
        funcs.append(tweak_append)
    if can_add_vowel(password):
        funcs.append(tweak_add_vowel)
    if can_capitalize(password):
        funcs.append(tweak_capitalize)
    if can_equal_char_replace(password):
        funcs.append(tweak_equal_char_replace)
    assert(len(funcs) > 0)
    return choice(funcs)
    # return tweak_capitalize


def test_tweak_funcs(password):
    if can_digit_tweak(password):
        print('tweak_digits: %s-->%s' % (password, tweak_digits(password)))
    else:
        print('Cannot apply %s to %s' % ('tweak_digits', password))
    if can_append(password):
        print('tweak_append: %s-->%s' % (password, tweak_append(password)))
    else:
        print('Cannot apply %s to %s' % ('tweak_pluralize', password))
    if can_add_vowel(password):
        print('tweak_add_vowel: %s-->%s' %
              (password, tweak_add_vowel(password)))
    else:
        print('Cannot apply %s to %s' % ('tweak_add_vowel', password))
    if can_capitalize(password):
        print('tweak_capitalize: %s-->%s' %
              (password, tweak_capitalize(password)))
    else:
        print('Cannot apply %s to %s' %
              ('tweak_capitalize', password))
    if can_equal_char_replace(password):
        print('tweak_equal_char_replace: %s-->%s' %
              (password, tweak_equal_char_replace(password)))
    else:
        print('Cannot apply %s to %s' % ('tweak_equal_char_replace', password))
    if can_tweak_tail(password):
        print('tweak_tail: %s-->%s' % (password, tweak_tail(password)))
    else:
        print('Cannot apply %s to %s' % ('tweak_tail', password))


def main():
    for i in range(100):
        seed = generate_seed()
        print('New seed: %s' % seed)
        test_tweak_funcs(seed)
        print

if __name__ == '__main__':
main()


this is my hashers.py :

from __future__ import unicode_literals

import base64
import binascii
import hashlib
import importlib
import passlib
import hashlib
from collections import OrderedDict 

from django.conf import settings 
from django.core.exceptions import ImproperlyConfigured
from django.core.signals import setting_changed
from django.dispatch import receiver
from django.db import models
from django.contrib.auth.hashers import BasePasswordHasher, PBKDF2PasswordHasher
from django.utils.crypto import get_random_string

from django.utils.encoding import force_bytes, force_text
from django.utils.module_loading import import_string 
from django.utils.translation import gettext_noop as _


def check_password(password, encoded, setter=None, preferred='MyHoneywordHasher'):
    if password is None or not is_password_usable(encoded):
        return False

    preferred = get_hasher('MyHoneywordHasher')
    hasher = identify_hasher(encoded)

    hasher_changed = hasher.algorithm != MyHoneywordHasher.algorithm
    must_update = hasher+hasher_changed or MyHoneywordHasher.must_update(encoded)
    is_correct = hasher.verify(password, encoded)

    if not is_correct and not hasher_changed and must_update:
        hasher.harden_runtime(password, encoded)

    if setter and is_correct and must_update:
        setter(password)
    return is_correct


def make_password(password, salt, hasher='MyHoneywordHasher'):
    if password is None:
        return UNUSABLE_PASSWORD_PREFIX + get_random_string(UNSUABLE_PASSWORD_SUFFIX_LENGTH)
        hasher = get_hasher(MyHoneywordHasher)

    if not salt:
        salt = hasher.salt()

    return hasher.encode(password, salt)

def get_hasher(algorithm='honeyword_base9_tweak3_pbkdf2_sha256'):
    if hasattr(algorithm, 'honeyword_base9_tweak3_pbkdf2_sha256'):
        return algorithm

    elif algorithm =='honeyword_base9_tweak3_pbkdf2_sha256':
        return get_hashers()[0]

    else:
        hashers =get_hashers_by_algorithm()
        try:
            return hashers[algorithm]
        except KeyError:
            raise ValueError("unknown")


class MyHoneywordHasher(PBKDF2PasswordHasher):
    algorithm = "honeyword_base9_tweak3_pbkdf2_sha256"
    iterations = 36000
    digest = hashlib.sha256

    def _load_library(self):
        if self.library is not None:
            if isinstance(self.library, (tuple, list)):
                name, mod_path = self.library

            else:
                mod_path = self.library
            try:
                module = importlib.import_module(mod_path)
            except ImportError as e:
                raise ValueError("Couldn't load %r algorithm library: %s" %(self.__class__.__name__, e))

            return module
        raise ValueError("Hasher %r doesn't specify a library attribute" %self.__class__.__name__)

    def salt(self):

        return get_random_string()

    def verify(self, password, encoded):
        raise NotImplementedError('subclasses of BasePasswordHasher must provide a verify() method')


    def encode (self, password, salt, iterations=None):
        sweetwords = ["hilman95,aisyah95,amirah95,zuhairah95,nabila95"]
        sweetwords.extend(honeywordgen.gen(password, base9, [passfiles.txt]))
        for i in range(base10):
            sweetwords.extend(honeywordtweak.tweak(password[i], tweak3))
        random.shuffle(sweetwords)

        hashes = []
        for swd in sweetwords:
            hashes.append(self.hash(swd, salt, iterations))
            self.honeychecker.update_index(salt, sweetwords.index(password))
            h = sweetwords(salt = salt, sweetwords = pickle.dumps(hashes))
            h.save()
            return '%s$%d$%s$%s' %(self.algorithm, iterations, salt, hashes[0])

    def safe_summary(sel, encoded):
        raise NotImplementedError('subclasses of BasePasswordHasher must provide a safe_summary() method')

    def verify (self, password, encoded):
        algorithm, iterations, salt, dummy= encoded.split('$', 3)
        hashes = pickle.loads(sweetwords.objects.get(salt=salt).sweetwords)
        hash = self.hash(password, salt, int(iterations))
        if hash in hashes:
            return honeychecker.check_index(salt, hashes.index(hash))
            return False


at first i try , it manage to not hashed by default but unfortunately the password does not stored in the database . i use sqlite . my project is basically to add customize hashers in my registration page . when users register , the password will automatically hashed with honeywordHasher and stored in database. and i try to fix it but end up with this error :

NameError at /accounts/register/ name 'honeywordgen' is not defined

QuestionRe: password hasher Pin
Richard MacCutchan23-Oct-17 2:48
mveRichard MacCutchan23-Oct-17 2:48 
QuestionWhat do y'all use for prototyping Pin
#realJSOP19-Oct-17 5:52
mve#realJSOP19-Oct-17 5:52 
QuestionIt's probably just me... Pin
#realJSOP18-Oct-17 2:39
mve#realJSOP18-Oct-17 2:39 
AnswerRe: It's probably just me... Pin
Nathan Minier23-Oct-17 1:25
professionalNathan Minier23-Oct-17 1:25 
GeneralRe: It's probably just me... Pin
#realJSOP23-Oct-17 4:45
mve#realJSOP23-Oct-17 4:45 
GeneralRe: It's probably just me... Pin
Nathan Minier23-Oct-17 6:13
professionalNathan Minier23-Oct-17 6:13 
QuestionRelated to Table in angular 4 material Pin
Munjal Pandya6-Oct-17 22:18
Munjal Pandya6-Oct-17 22:18 
SuggestionRe: Related to Table in angular 4 material Pin
Richard Deeming9-Oct-17 8:55
mveRichard Deeming9-Oct-17 8:55 
GeneralRe: Related to Table in angular 4 material Pin
Munjal Pandya9-Oct-17 17:25
Munjal Pandya9-Oct-17 17:25 
QuestionMVC Edit form with dynamic dropdown list Pin
desanti23-Sep-17 8:45
desanti23-Sep-17 8:45 
AnswerRe: MVC Edit form with dynamic dropdown list Pin
Richard Deeming25-Sep-17 2:26
mveRichard Deeming25-Sep-17 2:26 
QuestionMVC entity framework web page - How to store logged user in a global variable Pin
desanti22-Sep-17 4:12
desanti22-Sep-17 4:12 
AnswerRe: MVC entity framework web page - How to store logged user in a global variable Pin
Richard Deeming22-Sep-17 4:51
mveRichard Deeming22-Sep-17 4:51 
GeneralRe: MVC entity framework web page - How to store logged user in a global variable Pin
desanti22-Sep-17 5:55
desanti22-Sep-17 5:55 
GeneralRe: MVC entity framework web page - How to store logged user in a global variable Pin
Richard Deeming22-Sep-17 6:05
mveRichard Deeming22-Sep-17 6:05 
QuestionDigital Signatures Pin
Nathan Minier19-Sep-17 7:08
professionalNathan Minier19-Sep-17 7:08 
QuestionLogin form php,mysql,ajax Pin
Dalee1716-Sep-17 14:55
Dalee1716-Sep-17 14:55 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.