demo_dynamic.py 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  1. """
  2. demo_dynamic.py v2
  3. This program demonstrates Python's use of the dynamic
  4. language support additions to LTC, namely access to LTC
  5. constants, struct and union sizes, and the binding of a
  6. math package to LTC. Also provided are simple code
  7. fragments to illustrate how one might write a Python
  8. wrapper for LTC and how an app might call the wrapper.
  9. This or a similar model should work for Ruby and other
  10. dynamic languages.
  11. This instance uses Python's ctypes and requires a single
  12. .dylib linking together LTC and a math library. Building
  13. a single .dylib is needed because LTC wants a fairly tight
  14. relationship between itself and the mathlib. (ctypes can
  15. load multiple .dylibs, but it does not support this level
  16. of tight coupling between otherwise independent libraries.)
  17. My .dylib was created on OSX/macOS with the following:
  18. sudo make -j5 -f makefile.shared \
  19. CFLAGS="-DUSE_TFM -DTFM_DESC -I/usr/local/include" \
  20. EXTRALIBS=/usr/local/lib/libtfm.a install
  21. Reminder: you don't need to bind in a math library unless
  22. you are going to use LTC functions that need a
  23. mathlib. For example, public key crypto requires
  24. a mathlib; hashing and symmetric encryption do not.
  25. This code was written for Python 2.7.
  26. Larry Bugbee
  27. March 2014 v1
  28. August 2017 v2
  29. """
  30. from ctypes import *
  31. from ctypes.util import find_library
  32. # switches to enable/disable selected output
  33. SHOW_ALL_CONSTANTS = True
  34. SHOW_ALL_SIZES = True
  35. SHOW_SELECTED_CONSTANTS = True
  36. SHOW_SELECTED_SIZES = True
  37. SHOW_BUILD_OPTIONS_ALGS = True
  38. SHOW_SHA256_EXAMPLE = True
  39. SHOW_CHACHA_EXAMPLE = True
  40. print
  41. print(' demo_dynamic.py')
  42. #---------------------------------------------------------------
  43. # load the .dylib
  44. libname = 'tomcrypt'
  45. libpath = find_library(libname)
  46. print
  47. print(' path to library %s: %s' % (libname, libpath))
  48. LTC = cdll.LoadLibrary(libpath)
  49. print(' loaded: %s' % LTC)
  50. print
  51. #---------------------------------------------------------------
  52. # get list of all supported constants followed by a list of all
  53. # supported sizes. One alternative: these lists may be parsed
  54. # and used as needed.
  55. if SHOW_ALL_CONSTANTS:
  56. print '-'*60
  57. print ' all supported constants and their values:'
  58. # get size to allocate for constants output list
  59. str_len = c_int(0)
  60. ret = LTC.crypt_list_all_constants(None, byref(str_len))
  61. print ' need to allocate %d bytes \n' % str_len.value
  62. # allocate that size and get (name, size) pairs, each pair
  63. # separated by a newline char.
  64. names_sizes = c_buffer(str_len.value)
  65. ret = LTC.crypt_list_all_constants(names_sizes, byref(str_len))
  66. print names_sizes.value
  67. print
  68. if SHOW_ALL_SIZES:
  69. print '-'*60
  70. print ' all supported sizes:'
  71. # get size to allocate for sizes output list
  72. str_len = c_int(0)
  73. ret = LTC.crypt_list_all_sizes(None, byref(str_len))
  74. print ' need to allocate %d bytes \n' % str_len.value
  75. # allocate that size and get (name, size) pairs, each pair
  76. # separated by a newline char.
  77. names_sizes = c_buffer(str_len.value)
  78. ret = LTC.crypt_list_all_sizes(names_sizes, byref(str_len))
  79. print names_sizes.value
  80. print
  81. #---------------------------------------------------------------
  82. # get individually named constants and sizes
  83. # print selected constants
  84. if SHOW_SELECTED_CONSTANTS:
  85. print '-'*60
  86. print '\n selected constants:'
  87. names = [
  88. 'ENDIAN_LITTLE',
  89. 'ENDIAN_64BITWORD',
  90. 'PK_PUBLIC',
  91. 'MAX_RSA_SIZE',
  92. 'CTR_COUNTER_BIG_ENDIAN',
  93. ]
  94. for name in names:
  95. const_value = c_int(0)
  96. rc = LTC.crypt_get_constant(name, byref(const_value))
  97. value = const_value.value
  98. print ' %-25s %d' % (name, value)
  99. # print selected sizes
  100. if SHOW_SELECTED_SIZES:
  101. print '-'*60
  102. print '\n selected sizes:'
  103. names = [
  104. 'rijndael_key',
  105. 'rsa_key',
  106. 'symmetric_CTR',
  107. 'twofish_key',
  108. 'ecc_point',
  109. 'gcm_state',
  110. 'sha512_state',
  111. ]
  112. for name in names:
  113. size_value = c_int(0)
  114. rc = LTC.crypt_get_size(name, byref(size_value))
  115. value = size_value.value
  116. print ' %-25s %d' % (name, value)
  117. #---------------------------------------------------------------
  118. #---------------------------------------------------------------
  119. # LibTomCrypt exposes one interesting string that can be accessed
  120. # via Python's ctypes module, "crypt_build_settings", which
  121. # provides a list of this build's compiler switches and supported
  122. # algorithms. If someday LTC exposes other interesting strings,
  123. # they can be found with:
  124. # nm /usr/local/lib/libtomcrypt.dylib | grep " D "
  125. def get_named_string(lib, name):
  126. return c_char_p.in_dll(lib, name).value
  127. if SHOW_BUILD_OPTIONS_ALGS:
  128. print '-'*60
  129. print 'This is a string compiled into LTC showing compile '
  130. print 'options and algorithms supported by this build \n'
  131. print get_named_string(LTC, 'crypt_build_settings')
  132. print
  133. #---------------------------------------------------------------
  134. #---------------------------------------------------------------
  135. # here is an example of how Python code can be written to access
  136. # LTC's implementation of SHA256 and ChaCha,
  137. # - - - - - - - - - - - - -
  138. # definitions
  139. def _get_size(name):
  140. size = c_int(0)
  141. rc = LTC.crypt_get_size(name, byref(size))
  142. if rc != 0:
  143. raise Exception('LTC.crypt_get_size(%s) rc = %d' % (name, rc))
  144. return size.value
  145. def _get_constant(name):
  146. constant = c_int(0)
  147. rc = LTC.crypt_get_constant(name, byref(constant))
  148. if rc != 0:
  149. raise Exception('LTC.crypt_get_constant(%s) rc = %d' % (name, rc))
  150. return constant.value
  151. CRYPT_OK = _get_constant('CRYPT_OK')
  152. class SHA256(object):
  153. def __init__(self):
  154. self.state = c_buffer(_get_size('sha256_state'))
  155. LTC.sha256_init(byref(self.state))
  156. def update(self, data):
  157. LTC.sha256_process(byref(self.state), data, len(data))
  158. def digest(self):
  159. md = c_buffer(32)
  160. LTC.sha256_done(byref(self.state), byref(md))
  161. return md.raw
  162. class ChaCha(object):
  163. def __init__(self, key, rounds):
  164. self.state = c_buffer(_get_size('chacha_state'))
  165. self.counter = c_int(1)
  166. err = LTC.chacha_setup(byref(self.state), key, len(key), rounds)
  167. def set_iv32(self, iv):
  168. err = LTC.chacha_ivctr32(byref(self.state), iv, len(iv), byref(self.counter))
  169. if err != CRYPT_OK:
  170. raise Exception('LTC.chacha_ivctr32() err = %d' % err)
  171. def crypt(self, datain):
  172. dataout = c_buffer(len(datain))
  173. err = LTC.chacha_crypt(byref(self.state), datain, len(datain), byref(dataout))
  174. if err != CRYPT_OK:
  175. raise Exception('LTC.chacha_crypt() err = %d' % err)
  176. return dataout.raw
  177. # - - - - - - - - - - - - -
  178. # a SHA256 app fragment...
  179. # from wrapper import * # uncomment in real life
  180. if SHOW_SHA256_EXAMPLE:
  181. print '-'*60
  182. data = 'hello world'
  183. sha256 = SHA256()
  184. sha256.update(data)
  185. md = sha256.digest()
  186. template = '\n the SHA256 digest for "%s" is %s \n'
  187. print template % (data, md.encode('hex'))
  188. # - - - - - - - - - - - - -
  189. # a ChaCha app fragment...
  190. if SHOW_CHACHA_EXAMPLE:
  191. print '-'*60
  192. key = 'hownowbrowncow\x00\x00' # exactly 16 or 32 bytes
  193. rounds = 12 # common values: 8, 12, 20
  194. iv = '123456789012' # exactly 12 bytes
  195. plain = 'Kilroy was here, there, and everywhere!'
  196. cha = ChaCha(key, rounds)
  197. cha.set_iv32(iv)
  198. cipher = cha.crypt(plain)
  199. template = '\n ChaCha%d ciphertext for "%s" is "%s" \n'
  200. print template % (rounds, plain, cipher.encode('hex'))
  201. #---------------------------------------------------------------
  202. #---------------------------------------------------------------
  203. #---------------------------------------------------------------