99import ssl
1010import sys
1111import logging
12+ import binascii
1213
1314pkcs11 = None
1415
1516# Default engine and provider.
1617_ENGINE_PATH = "/usr/lib/engines-3/libpkcs11.so"
1718_MODULE_PATH = "/usr/lib/softhsm/libsofthsm2.so"
1819
20+ # Reference EC key for NXP's PlugNTrust
21+ _EC_REF_KEY = binascii .unhexlify (
22+ b"3041020100301306072a8648ce3d020106082a8648ce3d03010704273025"
23+ b"0201010420100000000000000000000000000000000000ffffffffa5a6b5"
24+ b"b6a5a6b5b61000"
25+ )
26+
1927
2028def wrap_socket (sock , ssl_params = {}):
2129 keyfile = ssl_params .get ("keyfile" , None )
@@ -25,9 +33,19 @@ def wrap_socket(sock, ssl_params={}):
2533 ciphers = ssl_params .get ("ciphers" , None )
2634 verify = ssl_params .get ("verify_mode" , ssl .CERT_NONE )
2735 hostname = ssl_params .get ("server_hostname" , None )
28- use_hsm = ssl_params .get ("use_hsm" , False )
36+ micropython = sys .implementation .name == "micropython"
37+
38+ if keyfile is not None and "token" in keyfile and micropython :
39+ # Create a reference EC key for NXP EdgeLock device.
40+ objid = int (keyfile .split ("=" )[1 ], 16 ).to_bytes (4 , "big" )
41+ keyfile = _EC_REF_KEY [0 :53 ] + objid + _EC_REF_KEY [57 :]
42+ # Load the certificate from the secure element (when supported).
43+ # import cryptoki
44+ # with cryptoki.open() as token:
45+ # cert = token.read(0x65, 412)
2946
30- if not use_hsm :
47+ if keyfile is None or "token" not in keyfile :
48+ # Use MicroPython/CPython SSL to wrap socket.
3149 ctx = ssl .SSLContext (ssl .PROTOCOL_TLS_CLIENT )
3250 if hasattr (ctx , "set_default_verify_paths" ):
3351 ctx .set_default_verify_paths ()
@@ -39,7 +57,7 @@ def wrap_socket(sock, ssl_params={}):
3957 if ciphers is not None :
4058 ctx .set_ciphers (ciphers )
4159 if cafile is not None or cadata is not None :
42- ctx .load_verify_locations (cafile , cadata )
60+ ctx .load_verify_locations (cafile = cafile , cadata = cadata )
4361 return ctx .wrap_socket (sock , server_hostname = hostname )
4462 else :
4563 # Use M2Crypto to load key and cert from HSM.
0 commit comments