1#!/usr/bin/env python
2# $FreeBSD: stable/11/tests/sys/geom/class/eli/gentestvect.py 327856 2018-01-12 00:31:07Z asomers $
3
4from hashlib import pbkdf2_hmac
5import hashlib
6import itertools
7import string
8
9#From: https://stackoverflow.com/questions/14945095/how-to-escape-string-for-generated-c
10def cstring(s, encoding='ascii'):
11	if isinstance(s, unicode):
12		s = s.encode(encoding)
13
14	result = ''
15	for c in s:
16		if not (32 <= ord(c) < 127) or c in ('\\', '"'):
17			result += '\\%03o' % ord(c)
18		else:
19			result += c
20
21	return '"' + result + '"'
22
23intarr = lambda y: ', '.join(map(lambda x: str(ord(x)), y))
24
25_randfd = open('/dev/urandom', 'rb')
26_maketrans = string.maketrans('', '')
27def randgen(l, delchrs=None):
28	if delchrs is None:
29		return _randfd.read(l)
30
31	s = ''
32	while len(s) < l:
33		s += string.translate(_randfd.read(l - len(s)), _maketrans,
34		    delchrs)
35	return s
36
37def 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))
40
41if __name__ == '__main__':
42	import sys
43
44	if len(sys.argv) == 1:
45		hashfun = 'sha512'
46	else:
47		hashfun = sys.argv[1]
48
49	if hashfun not in hashlib.algorithms:
50		print 'Invalid hash function: %s' % `hashfun`
51		sys.exit(1)
52
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,
57		    10000, 1000)):
58			for passlen in xrange(8, 80, 8):
59				salt = randgen(saltl)
60				passwd = randgen(passlen, '\x00')
61				hmacout = pbkdf2_hmac(hashfun, passwd, salt,
62				    itr)
63				printhmacres(salt, passwd, itr, hmacout)
64