aboutsummaryrefslogtreecommitdiff
path: root/tools/ssl-keygen.py
blob: 555b379c49d21ad9832fe54991c97335d74291c3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#!/usr/bin/env python3

import argparse
import sys
import os.path
import subprocess
from functools import partial

def generate_private_key(out_pem='privateKey.pem'):
    subprocess.run(['openssl', 'genrsa', '-out', out_pem, '4096'], check=True)

def generate_public_key(in_pem='privateKey.pem', out_pem='publicKey.pem'):
    subprocess.run(['openssl', 'rsa', '-in', in_pem, '-pubout', '-out', out_pem], check=True)

def hexdump(array_type, array_name, length_type, in_pem, out_h):
    n = 0
    
    print("// Autogenerated hex dump of OpenSSL public key, do not edit", file=out_h)
    print("{} {}[] = {{".format(array_type, array_name), file=out_h)

    for line in iter(partial(in_pem.read, 16), b''):
        l = list(line)
        for n, i in enumerate(l):
            l[n] = '0x{:02X}'.format(i)

        print("    {},".format(", ".join(l)), file=out_h)

        n += 1

    print("};", file=out_h)
    print("{} {}_len = {};".format(length_type, array_name, n), file=out_h)

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='Generate OpenSSL key and hexdump')

    parser.add_argument('--private', default='privateKey.pem', type=str, help='Private key input')
    parser.add_argument('--public',  default='publicKey.pem',  type=str, help='Public key input')

    parser.add_argument('--output', type=argparse.FileType('wt'), default=sys.stdout, help='Output file')

    parser.add_argument('--array-type', type=str, default='const unsigned char', help='Array type')
    parser.add_argument('--length-type', type=str, default='const unsigned int', help='Length type')
    parser.add_argument('--array-name', type=str, default='a', help='Array name')

    args=parser.parse_args()

    # check if public key exists
    if not os.path.isfile(args.public):
        # if there is no private key, generate one
        if not os.path.isfile(args.private):
            generate_private_key(args.private)

        # export public key from private
        generate_public_key(args.private, args.public)

    with open(args.public, "rb") as public_pem:
        hexdump(args.array_type, args.array_name, args.length_type, public_pem, args.output)