demo_dynamic.py 8.6 KB

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