I2C toy code
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 
 
 
 
 

254 linhas
5.8 KiB

  1. #!/usr/bin/env python
  2. import sys
  3. import os
  4. import hashlib
  5. def md5_for_file(path, block_size=256*128):
  6. '''
  7. Block size directly depends on the block size of your filesystem
  8. to avoid performances issues
  9. Here I have blocks of 4096 octets (Default NTFS)
  10. '''
  11. md5 = hashlib.md5()
  12. with open(path,'rb') as f:
  13. for chunk in iter(lambda: f.read(block_size), b''):
  14. md5.update(chunk)
  15. f.close()
  16. return md5.hexdigest()
  17. def read_until_ends(f, s):
  18. while True:
  19. l = f.readline()
  20. if l.strip().endswith(s):
  21. break
  22. return l
  23. def read_until_start(f, s):
  24. while True:
  25. l = f.readline()
  26. if l.startswith(s):
  27. break
  28. return l
  29. def read_hex(f):
  30. t = []
  31. while True:
  32. l = f.readline()
  33. if l.strip() == '':
  34. break
  35. t.extend(l.strip().split(' '))
  36. return t
  37. class NamedData(object):
  38. def __init__(self, name, data):
  39. self.name = name
  40. self.data = data
  41. def __str__(self):
  42. return " /* {0} */\n {1},\n {{ {2} }}\n".format(self.name, len(self.data), ', '.join('0x' + x for x in self.data))
  43. def read_part(f, s):
  44. name = read_until_start(f, s).strip().lstrip('# ').rstrip(':')
  45. data = read_hex(f)
  46. e = NamedData(name, data)
  47. return e
  48. class RsaKey(object):
  49. def __init__(self, n, e, d, p, q, dP, dQ, qInv):
  50. self.n = n
  51. self.e = e
  52. self.d = d
  53. self.p = p
  54. self.q = q
  55. self.dP = dP
  56. self.dQ = dQ
  57. self.qInv = qInv
  58. def __str__(self):
  59. return "{{\n{0},\n{1},\n{2},\n{3},\n{4},\n{5},\n{6},\n{7}\n}}\n".format(self.n, self.e, self.d, self.p, self.q, self.dP, self.dQ, self.qInv)
  60. def read_key(f):
  61. if ftype.version == 1:
  62. read_until_start(f, '# Private key')
  63. n = read_part(f, ftype.n)
  64. e = read_part(f, ftype.e)
  65. d = read_part(f, ftype.d)
  66. p = read_part(f, ftype.p)
  67. q = read_part(f, ftype.q)
  68. dP = read_part(f, ftype.dP)
  69. dQ = read_part(f, ftype.dQ)
  70. qInv = read_part(f, ftype.qInv)
  71. k = RsaKey(n, e, d, p, q, dP, dQ, qInv)
  72. return k
  73. class Data(object):
  74. def __init__(self, name, obj1, obj2, obj3):
  75. self.name = name
  76. self.obj1 = obj1
  77. self.obj2 = obj2
  78. self.obj3 = obj3
  79. def __str__(self):
  80. if self.obj3 == None:
  81. return "{{\n \"{0}\",\n{1},\n{2}\n}}\n,".format(self.name, self.obj1, self.obj2)
  82. else:
  83. return "{{\n \"{0}\",\n{1},\n{2},\n{3}\n}}\n,".format(self.name, self.obj1, self.obj2, self.obj3)
  84. def read_data(f):
  85. name = read_until_start(f, ftype.o).strip().lstrip('# ')
  86. obj1 = read_part(f, ftype.o1)
  87. obj2 = read_part(f, ftype.o2)
  88. if ftype.name == 'emsa':
  89. obj3 = None
  90. else:
  91. obj3 = read_part(f, ftype.o3)
  92. s = Data(name, obj1, obj2, obj3)
  93. return s
  94. class Example(object):
  95. def __init__(self, name, key, data):
  96. self.name = name
  97. self.key = key
  98. self.data = data
  99. def __str__(self):
  100. res = "{{\n \"{0}\",\n{1},\n{{".format(self.name, str(self.key))
  101. for idx, d in enumerate(self.data, 1):
  102. if idx == 2:
  103. res += '#ifdef LTC_TEST_EXT\n'
  104. res += str(d) + '\n'
  105. if idx == ftype.numcases:
  106. res += '#endif /* LTC_TEST_EXT */\n'
  107. res += '}\n},'
  108. return res
  109. def read_example(f):
  110. name = read_until_start(f, '# Example').strip().lstrip('# ')
  111. key = read_key(f)
  112. l = read_until_start(f, ftype.sod)
  113. d = []
  114. while l.strip().startswith(ftype.sod):
  115. if ftype.version == 1:
  116. f.seek(-len(l), os.SEEK_CUR)
  117. data = read_data(f)
  118. d.append(data)
  119. l = read_until_start(f, '#')
  120. e = Example(name, key, d)
  121. f.seek(-len(l), os.SEEK_CUR)
  122. return e
  123. class PkcsType(object):
  124. def __init__(self, name):
  125. if name == 'pss':
  126. self.o = '# RSASSA-PSS Signature Example'
  127. self.o1 = '# Message to be signed'
  128. self.o2 = '# Salt'
  129. self.o3 = '# Signature'
  130. elif name == 'oaep':
  131. self.o = '# RSAES-OAEP Encryption Example'
  132. self.o1 = '# Message to be encrypted'
  133. self.o2 = '# Seed'
  134. self.o3 = '# Encryption'
  135. elif name == 'emsa':
  136. self.o = '# PKCS#1 v1.5 Signature Example'
  137. self.o1 = '# Message to be signed'
  138. self.o2 = '# Signature'
  139. elif name == 'eme':
  140. self.o = '# PKCS#1 v1.5 Encryption Example'
  141. self.o1 = '# Message'
  142. self.o2 = '# Seed'
  143. self.o3 = '# Encryption'
  144. else:
  145. raise ValueError('Type unknown: ' + name)
  146. if name == 'pss' or name == 'oaep':
  147. self.version = 2
  148. self.numcases = 6
  149. self.n = '# RSA modulus n'
  150. self.e = '# RSA public exponent e'
  151. self.d = '# RSA private exponent d'
  152. self.p = '# Prime p'
  153. self.q = '# Prime q'
  154. self.dP = '# p\'s CRT exponent dP'
  155. self.dQ = '# q\'s CRT exponent dQ'
  156. self.qInv = '# CRT coefficient qInv'
  157. self.sod = '# --------------------------------'
  158. elif name == 'emsa' or name == 'eme':
  159. self.version = 1
  160. self.numcases = 20
  161. self.n = '# Modulus'
  162. self.e = '# Public exponent'
  163. self.d = '# Exponent'
  164. self.p = '# Prime 1'
  165. self.q = '# Prime 2'
  166. self.dP = '# Prime exponent 1'
  167. self.dQ = '# Prime exponent 2'
  168. self.qInv = '# Coefficient'
  169. self.sod = self.o
  170. self.name = name
  171. ftype = PkcsType(sys.argv[2])
  172. print('/* Generated from file: %s\n * with md5 hash: %s\n */\n' % (sys.argv[1], md5_for_file(sys.argv[1])))
  173. print('''
  174. typedef struct rsaKey {
  175. int n_l;
  176. unsigned char n[256];
  177. int e_l;
  178. unsigned char e[256];
  179. int d_l;
  180. unsigned char d[256];
  181. int p_l;
  182. unsigned char p[256];
  183. int q_l;
  184. unsigned char q[256];
  185. int dP_l;
  186. unsigned char dP[256];
  187. int dQ_l;
  188. unsigned char dQ[256];
  189. int qInv_l;
  190. unsigned char qInv[256];
  191. } rsaKey_t;
  192. typedef struct rsaData {
  193. const char* name;
  194. int o1_l;
  195. unsigned char o1[256];
  196. int o2_l;
  197. unsigned char o2[256];''')
  198. if ftype.name != 'emsa':
  199. print(''' int o3_l;
  200. unsigned char o3[256];''')
  201. print('''} rsaData_t;
  202. typedef struct testcase {
  203. const char* name;
  204. rsaKey_t rsa;
  205. #ifdef LTC_TEST_EXT
  206. rsaData_t data[%d];
  207. #else
  208. rsaData_t data[1];
  209. #endif /* LTC_TEST_EXT */
  210. } testcase_t;
  211. testcase_t testcases_%s[] =
  212. {''' % (ftype.numcases, sys.argv[2]))
  213. with open(sys.argv[1], 'rb') as f:
  214. ex = []
  215. while read_until_ends(f, '============================================='):
  216. if f.tell() == os.path.getsize(sys.argv[1]):
  217. break
  218. e = read_example(f)
  219. ex.append(e)
  220. for i in ex:
  221. print(i)
  222. f.close()
  223. print('};\n')