blob: be8d484017dfd8fd71561d8f7ee60a015a60bc7c [file] [log] [blame]
rjw1f884582022-01-06 17:20:42 +08001import filecmp
2import os
3
4g_key_table = None
5
6class hsm_param:
7 def __init__(self):
8 #you can add parameter required by your HSM here
9 self.m_ref_key_path = ""
10 self.m_key_id = 0
11 self.m_attr1 = 0
12 self.m_attr2 = 0
13 self.m_padding_dict = {"raw": 0, "pss": 1}
14 self.m_padding = 0 #default: raw
15
16def create_key_table():
17 global g_key_table
18 if None == g_key_table:
19 #create key table
20 #here is reference design, please customize
21 #this part according to your HSM spec.
22 script_folder, script_name = os.path.split(os.path.realpath(__file__))
23 key_folder = os.path.join(script_folder, "keys")
24 key_folder = os.path.join(key_folder, "hsm")
25 g_key_table = list()
26 #key1 parameter
27 key1_param = hsm_param()
28 key1_param.m_ref_key_path = os.path.join(key_folder, 'pubk1.pem')
29 key1_param.m_key_id = 0
30 key1_param.m_attr1 = 1
31 key1_param.m_attr2 = 1
32 g_key_table.append(key1_param)
33 #key2 parameter
34 key2_param = hsm_param()
35 key2_param.m_ref_key_path = os.path.join(key_folder, 'pubk2.pem')
36 key2_param.m_key_id = 1
37 key2_param.m_attr1 = 2
38 key2_param.m_attr2 = 2
39 g_key_table.append(key2_param)
40 return
41
42def query_key_table(key):
43 global g_key_table
44 create_key_table()
45 for key_table_entry in g_key_table:
46 if filecmp.cmp(key, key_table_entry.m_ref_key_path):
47 print "key index: " + hex(key_table_entry.m_key_id)
48 return key_table_entry
49 print "no valid key entry found in table"
50 return None
51
52def hsm_rsa_sign(data, key, padding, sig):
53 hsm_param_obj = None
54
55 #note that key is pubk actually, use it as index for
56 #HSM parameters such as key selection
57 hsm_param_obj = query_key_table(key)
58 if None == hsm_param_obj:
59 return -1
60 hsm_param_obj.m_padding = hsm_param_obj.m_padding_dict[padding]
61
62 print "========================"
63 print "HSM parameter:"
64 print " m_key_id = " + hex(hsm_param_obj.m_key_id)
65 print " m_padding = " + hex(hsm_param_obj.m_padding)
66 print " m_attr1 = " + hex(hsm_param_obj.m_attr1)
67 print " m_attr2 = " + hex(hsm_param_obj.m_attr2)
68 print "========================"
69
70 #place hsm request here -- start
71 #create dummy sig for now
72 sig_file = open(sig, 'wb')
73 for i in range(0, 256):
74 sig_file.write(chr(0))
75 sig_file.close()
76 #place hsm request here -- end
77 return 0
78