demo_dynamic.py 8.1 KB

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