Created
April 21, 2015 05:04
-
-
Save wizardofozzie/ffe533f1b61e95c8f48c to your computer and use it in GitHub Desktop.
pbkdf_two.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import hmac | |
import hashlib | |
import struct | |
is_python2 = True | |
def pbkdf_two(passwd, salt, iters=2048, keylen=64, digestmod=hashlib.sha512): | |
import hmac | |
import struct | |
import hashlib | |
dgsz = digestmod().digest_size if callable(digestmod) else digestmod.digest_size | |
pwd, salt = [x if isinstance(x, bytes) else bytes(x, 'utf-8') for x in (passwd, salt)] | |
if keylen is None: keylen = dgsz | |
# Helper function which copies each iteration for h, where h is an hmac seeded with password | |
def pbhelper(h, salt, itercount, blocksize): | |
import struct | |
def prf(h, data): | |
hm = h.copy() | |
hm.update(data) | |
return hm.digest() | |
U = prf(h, salt + struct.pack('>i', blocksize)) | |
T = U | |
for j in range(2, itercount+1): | |
U = prf(h, U) | |
T = "".join([chr( ord(x) ^ ord(y) ) for (x, y) in zip( T, U )]) \ | |
if is_python2 else bytes([x ^ y for (x, y) in zip(T, U)]) # XORing | |
return T | |
L = int(keylen/dgsz) if (keylen%dgsz) else int(keylen/dgsz)+1 # L - number of output blocks to produce | |
#if keylen % dgsz != 0: L += 1 | |
h = hmac.new(key=passwd, msg=None, digestmod=digestmod ) | |
T = b"" | |
for i in range(1, L+1): | |
T += pbhelper(h, salt, iters, i) | |
return T[:keylen] | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment