Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1"""OpenBSD Blowfish password hashing. 

2 

3This module implements the OpenBSD Blowfish password hashing 

4algorithm, as described in "A Future-Adaptable Password Scheme" by 

5Niels Provos and David Mazieres. 

6 

7This system hashes passwords using a version of Bruce Schneier's 

8Blowfish block cipher with modifications designed to raise the cost 

9of off-line password cracking. The computation cost of the algorithm 

10is parametised, so it can be increased as computers get faster. 

11 

12Passwords are hashed using the hashpw() routine: 

13 

14 hashpw(password, salt) -> hashed_password 

15 

16Salts for the the second parameter may be randomly generated using the 

17gensalt() function: 

18 

19 gensalt(log_rounds = 12) -> random_salt 

20 

21The parameter "log_rounds" defines the complexity of the hashing. The 

22cost increases as 2**log_rounds. 

23 

24Passwords can be checked against a hashed copy using the checkpw() routine: 

25 

26 checkpw(password, hashed_password) -> boolean (true if matched) 

27 

28Passwords and salts for the hashpw and gensalt functions are text strings 

29that must not contain embedded nul (ASCII 0) characters. 

30 

31This module also operates as a key derivation function (KDF) to transform a 

32password and salt into bytes suitable for use as cryptographic key material: 

33 

34 kdf(password, salt, desired_length, rounds) -> key 

35 

36This will generate a key of "desired_length" in bytes (NB. not bits). For the 

37KDF mode the "rounds" parameter is the literal rounds, not the logarithm as 

38for gensalt. For the KDF case, "salt" and "password" may be binary strings 

39containing embedded nul characters. Note also that the "salt" for the KDF 

40should just be a random sequence of bytes (e.g. as generated by os.urandom) 

41and not one prepared with gensalt(). 

42 

43The KDF mode is recommended for generating symmetric cipher keys, IVs, hash 

44and MAC keys, etc. It should not be used a keystream for encryption itself. 

45""" 

46 

47import os 

48from bcrypt._bcrypt import * 

49 

50def gensalt(log_rounds = 12): 

51 """Generate a random text salt for use with hashpw(). "log_rounds" 

52 defines the complexity of the hashing, increasing the cost as 

53 2**log_rounds.""" 

54 return encode_salt(os.urandom(16), min(max(log_rounds, 4), 31)) 

55