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