summaryrefslogtreecommitdiff
path: root/FreeRTOS-Plus/Demo/AWS/Fleet_Provisioning_Windows_Simulator/Fleet_Provisioning_With_CSR_Demo/fleet_provisioning_demo_setup.py
blob: b90b804b87c7c31f492c3014f8df12c8bf47f4ae (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
60
61
62
63
#!/usr/bin/env python

import argparse
from cryptography import x509
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization

KEY_OUT_NAME = "corePKCS11_Claim_Key.dat"
CERT_OUT_NAME = "corePKCS11_Claim_Certificate.dat"


def convert_pem_to_der(cert_file, key_file):
    # Convert certificate from PEM to DER
    print("Converting format to DER format...")
    with open(key_file, "rb") as key:
        print("Starting key PEM to DER conversion.")
        pemkey = serialization.load_pem_private_key(key.read(), None, default_backend())
        key_der = pemkey.private_bytes(
            serialization.Encoding.DER,
            serialization.PrivateFormat.TraditionalOpenSSL,
            serialization.NoEncryption(),
        )
        with open(KEY_OUT_NAME, "wb") as key_out:
            key_out.write(key_der)
        print(
            f"Successfully converted key PEM to DER. Output file named: {KEY_OUT_NAME}"
        )

    print("Starting certificate pem conversion.")
    with open(cert_file, "rb") as cert:
        cert = x509.load_pem_x509_certificate(cert.read(), default_backend())
        with open(CERT_OUT_NAME, "wb") as cert_out:
            cert_out.write(cert.public_bytes(serialization.Encoding.DER))

        print(
            f"Successfully converted certificate PEM to DER. Output file named: {CERT_OUT_NAME}"
        )


def main(args):
    convert_pem_to_der(cert_file=args.cert_file, key_file=args.key_file)


if __name__ == "__main__":
    arg_parser = argparse.ArgumentParser(
        description="This script converts passed in PEM format certificates and keys into the binary DER format."
    )
    arg_parser.add_argument(
        "-c",
        "--cert_file",
        type=str,
        help="Specify the name of the generated certificate file.",
        required=True,
    )
    arg_parser.add_argument(
        "-k",
        "--key_file",
        type=str,
        help="Specify the name of the generated key file.",
        required=True,
    )
    args = arg_parser.parse_args()
    main(args)