#!/usr/bin/env python3 # Writes vectors.h for tests/se/payload.c: two RSA keys (e = 65537), a message # and its m^d mod n for each, and SHA-256 digests. Seeded, so the output is # the same every run; vectors.h is checked in and this only needs rerunning # to change the vectors. import hashlib, os, random rnd = random.Random(0x5E) def is_prime(n): if n < 2: return False for p in [2,3,5,7,11,13,17,19,23,29,31,37]: if n % p == 0: return n == p d, s = n-1, 0 while d % 2 == 0: d//=2; s+=1 for _ in range(40): a = rnd.randrange(2, n-2) x = pow(a, d, n) if x in (1, n-1): continue for _ in range(s-1): x = x*x % n if x == n-1: break else: return False return True def prime(bits): while True: p = rnd.getrandbits(bits) | (1 << (bits-1)) | (1 << (bits-2)) | 1 if is_prime(p): return p def key(bits, e=65537): while True: p, q = prime(bits//2), prime(bits//2) phi = (p-1)*(q-1) if p != q and phi % e: n = p*q if n.bit_length() == bits: return n, pow(e, -1, phi) def arr(name, v, nbytes): b = v.to_bytes(nbytes, 'big') lines = ['static const unsigned char %s[%d] = {' % (name, nbytes)] for i in range(0, nbytes, 12): lines.append(' ' + ', '.join('0x%02X' % x for x in b[i:i+12]) + ',') lines.append('};') return '\n'.join(lines) out = [] for bits, tag in ((2048, 'k2048'), (1024, 'k1024')): n, d = key(bits) m = int.from_bytes(hashlib.sha256(tag.encode()).digest() * (bits // 256), 'big') % n s = pow(m, d, n) assert pow(s, 65537, n) == m nb = bits // 8 out += [arr(tag + '_mod', n, nb), arr(tag + '_exp', d, nb), arr(tag + '_msg', m, nb), arr(tag + '_sig', s, nb)] msg = bytes((i * 7 + 3) & 0xFF for i in range(200)) out.append(arr('sha_msg', int.from_bytes(msg, 'big'), 200)) out.append(arr('sha_msg_digest', int.from_bytes(hashlib.sha256(msg).digest(), 'big'), 32)) out.append(arr('sha_abc_digest', int.from_bytes(hashlib.sha256(b'abc').digest(), 'big'), 32)) open(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'vectors.h'), 'w').write('/* Generated by gen_vectors.py: RSA keys (e = 65537) with\n * m^d mod n, and SHA-256 digests, computed with Python integers and hashlib. */\n\n' + '\n\n'.join(out) + '\n')