-
Notifications
You must be signed in to change notification settings - Fork 34
Expand file tree
/
Copy pathcommon.py
More file actions
82 lines (65 loc) · 2.52 KB
/
Copy pathcommon.py
File metadata and controls
82 lines (65 loc) · 2.52 KB
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
""" Common helper functions for cryptoauthlib examples """
import argparse
import os
import base64
import sys
# Maps common name to the specific name used internally
atca_names_map = {'i2c': 'i2c', 'hid': 'kithid', 'sha': 'sha20x', 'ecc': 'eccx08'}
try:
FileNotFoundError
except NameError:
FileNotFoundError = IOError
def setup_example_runner(module):
"""
Common helper function that sets up the script entry for all examples
"""
example = os.path.basename(module).split('.')[0]
try:
with open(example + '.md', 'r') as f:
details = f.read()
except FileNotFoundError:
details = example.upper() + ' Example'
parser = argparse.ArgumentParser(description=details,
formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('-i', '--iface', default='hid', choices=['i2c', 'hid'], help='Interface type (default: hid)')
parser.add_argument('-d', '--device', default='ecc', choices=['ecc', 'sha'], help='Device type (default: ecc)')
parser.add_argument('-p', '--params', nargs='*', help='Interface Parameters in the form key=value')
return parser
def parse_interface_params(list):
"""
Parse a variable list of key=value args into a dictionary suitable for kwarg usage
"""
return {} if list is None else dict([s.split('=') for s in list])
def pretty_print_hex(a, l=16, indent=''):
"""
Format a list/bytes/bytearray object into a formatted ascii hex string
"""
lines = []
a = bytearray(a)
for x in range(0, len(a), l):
lines.append(indent + ' '.join(['{:02X}'.format(y) for y in a[x:x+l]]))
return '\n'.join(lines)
def convert_ec_pub_to_pem(raw_pub_key):
"""
Convert to the key to PEM format. Expects bytes
"""
public_key_der = bytearray.fromhex('3059301306072A8648CE3D020106082A8648CE3D03010703420004') + raw_pub_key
public_key_b64 = base64.b64encode(public_key_der).decode('ascii')
public_key_pem = (
'-----BEGIN PUBLIC KEY-----\n'
+ '\n'.join(public_key_b64[i:i + 64] for i in range(0, len(public_key_b64), 64)) + '\n'
+ '-----END PUBLIC KEY-----'
)
return public_key_pem
def check_if_rpi():
"""
Does a basic check to see if the script is running on a Raspberry Pi
"""
is_rpi = False
try:
with open('/sys/firmware/devicetree/base/model', 'r') as f:
if f.readline().startswith('Raspberry'):
is_rpi = True
except FileNotFoundError:
is_rpi = False
return is_rpi