demo_dynamic.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  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. ------
  29. This code was originally written for Python 2.7 with the
  30. ctypes standard library. This version is modified to run
  31. under both Python 2.7 and 3.6.
  32. Arguably the biggest change for Python3 has to do with
  33. strings. Under Python2, native strings are ASCII bytes and
  34. passing them to LTC is natural and requires no conversion.
  35. Under Python3 all native strings are Unicode which requires
  36. they be converted to bytes before use by LTC.
  37. Note the following for Python3.
  38. - ASCII keys, IVs and other string arguments must be
  39. 'bytes'. Define them with a 'b' prefix or convert
  40. via the 'bytes()' function.
  41. - "strings" returned from LTC are bytes and conversion
  42. to Unicode might be necessary for proper printing.
  43. If so, use <string>.decode('utf-8').
  44. - The Python2 'print' statement becomes a function in
  45. Python3 which requires parenthesis, eg. 'print()'.
  46. NB: Unicode is achieved under Python2 by either defining
  47. a Unicode string with a 'u' prefix or passing ASCII
  48. strings thru the 'unicode()' function.
  49. Larry Bugbee
  50. March 2014 v1
  51. August 2017 v2b
  52. """
  53. import sys
  54. from ctypes import *
  55. from ctypes.util import find_library
  56. # switches to enable/disable selected output
  57. SHOW_ALL_CONSTANTS = True
  58. SHOW_ALL_SIZES = True
  59. SHOW_SELECTED_CONSTANTS = True
  60. SHOW_SELECTED_SIZES = True
  61. SHOW_BUILD_OPTIONS_ALGS = True
  62. SHOW_SHA256_EXAMPLE = True
  63. SHOW_CHACHA_EXAMPLE = True
  64. print(' ')
  65. print(' demo_dynamic.py')
  66. def inprint(s, indent=0):
  67. "prints strings indented, including multline strings"
  68. for line in s.split('\n'):
  69. print(' '*indent + line)
  70. #-------------------------------------------------------------------------------
  71. # load the .dylib
  72. libname = 'tomcrypt'
  73. libpath = find_library(libname)
  74. print(' ')
  75. print(' path to library %s: %s' % (libname, libpath))
  76. LTC = cdll.LoadLibrary(libpath)
  77. print(' loaded: %s' % LTC)
  78. print(' ')
  79. #-------------------------------------------------------------------------------
  80. # get list of all supported constants followed by a list of all
  81. # supported sizes. One alternative: these lists may be parsed
  82. # and used as needed.
  83. if SHOW_ALL_CONSTANTS:
  84. print('-'*60)
  85. print(' all supported constants and their values:')
  86. # get size to allocate for constants output list
  87. str_len = c_int(0)
  88. ret = LTC.crypt_list_all_constants(None, byref(str_len))
  89. print(' need to allocate %d bytes to build list \n' % str_len.value)
  90. # allocate that size and get (name, size) pairs, each pair
  91. # separated by a newline char.
  92. names_sizes = c_buffer(str_len.value)
  93. ret = LTC.crypt_list_all_constants(names_sizes, byref(str_len))
  94. print(names_sizes.value.decode("utf-8"))
  95. print(' ')
  96. if SHOW_ALL_SIZES:
  97. print('-'*60)
  98. print(' all supported sizes:')
  99. # get size to allocate for sizes output list
  100. str_len = c_int(0)
  101. ret = LTC.crypt_list_all_sizes(None, byref(str_len))
  102. print(' need to allocate %d bytes to build list \n' % str_len.value)
  103. # allocate that size and get (name, size) pairs, each pair
  104. # separated by a newline char.
  105. names_sizes = c_buffer(str_len.value)
  106. ret = LTC.crypt_list_all_sizes(names_sizes, byref(str_len))
  107. print(names_sizes.value.decode("utf-8"))
  108. print(' ')
  109. #-------------------------------------------------------------------------------
  110. # get individually named constants and sizes
  111. if SHOW_SELECTED_CONSTANTS:
  112. print('-'*60)
  113. print('\n selected constants:')
  114. names = [
  115. b'ENDIAN_LITTLE',
  116. b'ENDIAN_64BITWORD',
  117. b'PK_PUBLIC',
  118. b'LTC_MILLER_RABIN_REPS',
  119. b'CTR_COUNTER_BIG_ENDIAN',
  120. ]
  121. for name in names:
  122. const_value = c_int(0)
  123. rc = LTC.crypt_get_constant(name, byref(const_value))
  124. value = const_value.value
  125. print(' %-25s %d' % (name.decode("utf-8"), value))
  126. print(' ')
  127. if SHOW_SELECTED_SIZES:
  128. print('-'*60)
  129. print('\n selected sizes:')
  130. names = [
  131. b'rijndael_key',
  132. b'rsa_key',
  133. b'symmetric_CTR',
  134. b'twofish_key',
  135. b'ecc_point',
  136. b'gcm_state',
  137. b'sha512_state',
  138. ]
  139. for name in names:
  140. size_value = c_int(0)
  141. rc = LTC.crypt_get_size(name, byref(size_value))
  142. value = size_value.value
  143. print(' %-25s %d' % (name.decode("utf-8"), value))
  144. print(' ')
  145. #-------------------------------------------------------------------------------
  146. #-------------------------------------------------------------------------------
  147. # LibTomCrypt exposes one interesting string that can be accessed
  148. # via Python's ctypes module, "crypt_build_settings", which
  149. # provides a list of this build's compiler switches and supported
  150. # algorithms. If someday LTC exposes other interesting strings,
  151. # they can be found with:
  152. # nm /usr/local/lib/libtomcrypt.dylib | grep " D "
  153. def get_named_string(lib, name):
  154. return c_char_p.in_dll(lib, name).value.decode("utf-8")
  155. if SHOW_BUILD_OPTIONS_ALGS:
  156. print('-'*60)
  157. print('This is a string compiled into LTC showing compile')
  158. print('options and algorithms supported by this build \n')
  159. # print(get_named_string(LTC, 'crypt_build_settings'))
  160. inprint(get_named_string(LTC, 'crypt_build_settings'), 4)
  161. #-------------------------------------------------------------------------------
  162. #-------------------------------------------------------------------------------
  163. # here is an example of how Python code can be written to access
  164. # LTC's implementation of SHA256 and ChaCha,
  165. # - - - - - - - - - - - - -
  166. # definitions
  167. from binascii import hexlify, unhexlify
  168. def _err2str(err):
  169. # define return type
  170. errstr = LTC.error_to_string
  171. errstr.restype = c_char_p
  172. # get and return err string
  173. return errstr(err)
  174. def _get_size(name):
  175. size = c_int(0)
  176. rc = LTC.crypt_get_size(bytes(name), byref(size))
  177. if rc != 0:
  178. raise Exception('LTC.crypt_get_size(%s) rc = %d' % (name, rc))
  179. return size.value
  180. def _get_constant(name):
  181. constant = c_int(0)
  182. rc = LTC.crypt_get_constant(bytes(name), byref(constant))
  183. if rc != 0:
  184. raise Exception('LTC.crypt_get_constant(%s) rc = %d' % (name, rc))
  185. return constant.value
  186. CRYPT_OK = _get_constant(b'CRYPT_OK')
  187. class SHA256(object):
  188. def __init__(self):
  189. self.state = c_buffer(_get_size(b'sha256_state'))
  190. LTC.sha256_init(byref(self.state))
  191. def update(self, data):
  192. LTC.sha256_process(byref(self.state), data, len(data))
  193. def digest(self):
  194. md = c_buffer(32)
  195. LTC.sha256_done(byref(self.state), byref(md))
  196. return md.raw
  197. class ChaCha(object):
  198. def __init__(self, key, rounds):
  199. self.state = c_buffer(_get_size(b'chacha_state'))
  200. self.counter = c_int(1)
  201. err = LTC.chacha_setup(byref(self.state), key, len(key), rounds)
  202. if err != CRYPT_OK:
  203. raise Exception('LTC.chacha_setup(), err = %d, "%s"' % (err, _err2str(err)))
  204. def set_iv32(self, iv):
  205. err = LTC.chacha_ivctr32(byref(self.state), iv, len(iv), byref(self.counter))
  206. if err != CRYPT_OK:
  207. raise Exception('LTC.chacha_ivctr32(), err = %d, "%s"' % (err, _err2str(err)))
  208. def crypt(self, datain):
  209. dataout = c_buffer(len(datain))
  210. err = LTC.chacha_crypt(byref(self.state), datain, len(datain), byref(dataout))
  211. if err != CRYPT_OK:
  212. raise Exception('LTC.chacha_crypt(), err = %d, "%s"' % (err, _err2str(err)))
  213. return dataout.raw
  214. # - - - - - - - - - - - - -
  215. # a SHA256 app fragment
  216. if SHOW_SHA256_EXAMPLE:
  217. print('-'*60)
  218. data = b'hello world' # we want bytes, not Unicode
  219. sha256 = SHA256()
  220. sha256.update(data)
  221. md = sha256.digest()
  222. template = '\n the SHA256 digest for "%s" is %s \n'
  223. print(template % (data, hexlify(md)))
  224. # - - - - - - - - - - - - -
  225. # a ChaCha app fragment
  226. if SHOW_CHACHA_EXAMPLE:
  227. print('-'*60)
  228. key = b'hownowbrowncow\x00\x00' # exactly 16 or 32 bytes
  229. rounds = 12 # common values: 8, 12, 20
  230. iv = b'123456789012' # exactly 12 bytes
  231. plain = b'Kilroy was here, there, and everywhere!'
  232. cha = ChaCha(key, rounds)
  233. cha.set_iv32(iv)
  234. cipher = cha.crypt(plain)
  235. template = '\n ChaCha%d ciphertext for "%s" is "%s"'
  236. print(template % (rounds, plain, hexlify(cipher)))
  237. cha.set_iv32(iv) # reset to decrypt
  238. decrypted = cha.crypt(cipher)
  239. template = ' ChaCha%d decoded text for "%s" is "%s" \n'
  240. print(template % (rounds, plain, decrypted.decode("utf-8")))
  241. # Footnote: Keys should be erased fm memory as soon as possible after use,
  242. # and that includes Python. For a tip on how to do that in Python, see
  243. # http://buggywhip.blogspot.com/2010/12/erase-keys-and-credit-card-numbers-in.html
  244. #-------------------------------------------------------------------------------
  245. #-------------------------------------------------------------------------------
  246. #-------------------------------------------------------------------------------