4 from hashlib import pbkdf2_hmac
9 #From: https://stackoverflow.com/questions/14945095/how-to-escape-string-for-generated-c
10 def cstring(s, encoding='ascii'):
11 if isinstance(s, unicode):
12 s = s.encode(encoding)
16 if not (32 <= ord(c) < 127) or c in ('\\', '"'):
17 result += '\\%03o' % ord(c)
21 return '"' + result + '"'
23 intarr = lambda y: ', '.join(map(lambda x: str(ord(x)), y))
25 _randfd = open('/dev/urandom', 'rb')
26 _maketrans = string.maketrans('', '')
27 def randgen(l, delchrs=None):
29 return _randfd.read(l)
33 s += string.translate(_randfd.read(l - len(s)), _maketrans,
37 def printhmacres(salt, passwd, itr, hmacout):
38 print '\t{ %s, %d, %s, %d, %s, %d },' % (cstring(salt), len(salt),
39 cstring(passwd), itr, cstring(hmacout), len(hmacout))
41 if __name__ == '__main__':
44 if len(sys.argv) == 1:
49 if hashfun not in hashlib.algorithms:
50 print 'Invalid hash function: %s' % `hashfun`
53 print '/* Test Vectors for PBKDF2-%s */' % hashfun.upper()
54 print '\t/* salt, saltlen, passwd, itr, hmacout, hmacoutlen */'
55 for saltl in xrange(8, 64, 8):
56 for itr in itertools.chain(xrange(100, 1000, 100), xrange(1000,
58 for passlen in xrange(8, 80, 8):
60 passwd = randgen(passlen, '\x00')
61 hmacout = pbkdf2_hmac(hashfun, passwd, salt,
63 printhmacres(salt, passwd, itr, hmacout)