1*e22ad7bcSEnji Cooper#!/usr/bin/env python 2*e22ad7bcSEnji Cooper 3*e22ad7bcSEnji Cooperfrom hashlib import pbkdf2_hmac 4*e22ad7bcSEnji Cooperimport hashlib 5*e22ad7bcSEnji Cooperimport itertools 6*e22ad7bcSEnji Cooperimport string 7*e22ad7bcSEnji Cooper 8*e22ad7bcSEnji Cooper#From: https://stackoverflow.com/questions/14945095/how-to-escape-string-for-generated-c 9*e22ad7bcSEnji Cooperdef cstring(s, encoding='ascii'): 10*e22ad7bcSEnji Cooper if isinstance(s, unicode): 11*e22ad7bcSEnji Cooper s = s.encode(encoding) 12*e22ad7bcSEnji Cooper 13*e22ad7bcSEnji Cooper result = '' 14*e22ad7bcSEnji Cooper for c in s: 15*e22ad7bcSEnji Cooper if not (32 <= ord(c) < 127) or c in ('\\', '"'): 16*e22ad7bcSEnji Cooper result += '\\%03o' % ord(c) 17*e22ad7bcSEnji Cooper else: 18*e22ad7bcSEnji Cooper result += c 19*e22ad7bcSEnji Cooper 20*e22ad7bcSEnji Cooper return '"' + result + '"' 21*e22ad7bcSEnji Cooper 22*e22ad7bcSEnji Cooperintarr = lambda y: ', '.join(map(lambda x: str(ord(x)), y)) 23*e22ad7bcSEnji Cooper 24*e22ad7bcSEnji Cooper_randfd = open('/dev/urandom', 'rb') 25*e22ad7bcSEnji Cooper_maketrans = string.maketrans('', '') 26*e22ad7bcSEnji Cooperdef randgen(l, delchrs=None): 27*e22ad7bcSEnji Cooper if delchrs is None: 28*e22ad7bcSEnji Cooper return _randfd.read(l) 29*e22ad7bcSEnji Cooper 30*e22ad7bcSEnji Cooper s = '' 31*e22ad7bcSEnji Cooper while len(s) < l: 32*e22ad7bcSEnji Cooper s += string.translate(_randfd.read(l - len(s)), _maketrans, 33*e22ad7bcSEnji Cooper delchrs) 34*e22ad7bcSEnji Cooper return s 35*e22ad7bcSEnji Cooper 36*e22ad7bcSEnji Cooperdef printhmacres(salt, passwd, itr, hmacout): 37*e22ad7bcSEnji Cooper print '\t{ %s, %d, %s, %d, %s, %d },' % (cstring(salt), len(salt), 38*e22ad7bcSEnji Cooper cstring(passwd), itr, cstring(hmacout), len(hmacout)) 39*e22ad7bcSEnji Cooper 40*e22ad7bcSEnji Cooperif __name__ == '__main__': 41*e22ad7bcSEnji Cooper import sys 42*e22ad7bcSEnji Cooper 43*e22ad7bcSEnji Cooper if len(sys.argv) == 1: 44*e22ad7bcSEnji Cooper hashfun = 'sha512' 45*e22ad7bcSEnji Cooper else: 46*e22ad7bcSEnji Cooper hashfun = sys.argv[1] 47*e22ad7bcSEnji Cooper 48*e22ad7bcSEnji Cooper if hashfun not in hashlib.algorithms: 49*e22ad7bcSEnji Cooper print 'Invalid hash function: %s' % `hashfun` 50*e22ad7bcSEnji Cooper sys.exit(1) 51*e22ad7bcSEnji Cooper 52*e22ad7bcSEnji Cooper print '/* Test Vectors for PBKDF2-%s */' % hashfun.upper() 53*e22ad7bcSEnji Cooper print '\t/* salt, saltlen, passwd, itr, hmacout, hmacoutlen */' 54*e22ad7bcSEnji Cooper for saltl in xrange(8, 64, 8): 55*e22ad7bcSEnji Cooper for itr in itertools.chain(xrange(100, 1000, 100), xrange(1000, 56*e22ad7bcSEnji Cooper 10000, 1000)): 57*e22ad7bcSEnji Cooper for passlen in xrange(8, 80, 8): 58*e22ad7bcSEnji Cooper salt = randgen(saltl) 59*e22ad7bcSEnji Cooper passwd = randgen(passlen, '\x00') 60*e22ad7bcSEnji Cooper hmacout = pbkdf2_hmac(hashfun, passwd, salt, 61*e22ad7bcSEnji Cooper itr) 62*e22ad7bcSEnji Cooper printhmacres(salt, passwd, itr, hmacout) 63