11
22
33"""
4- demo_dynamic.py v2
4+ demo_dynamic.py v2b
55
66 This program demonstrates Python's use of the dynamic
77 language support additions to LTC, namely access to LTC
3333 mathlib. For example, public key crypto requires
3434 a mathlib; hashing and symmetric encryption do not.
3535
36- This code was written for Python 2.7.
36+ This code was written for Python 2.7 with the ctypes standard
37+ library.
3738
3839 Larry Bugbee
3940 March 2014 v1
40- August 2017 v2
41+ August 2017 v2b
4142
4243"""
4344
@@ -195,6 +196,13 @@ def _get_constant(name):
195196 raise Exception ('LTC.crypt_get_constant(%s) rc = %d' % (name , rc ))
196197 return constant .value
197198
199+ def _err2str (err ):
200+ # define return type
201+ errstr = LTC .error_to_string
202+ errstr .restype = c_char_p
203+ # get and return err string
204+ return errstr (err )
205+
198206CRYPT_OK = _get_constant ('CRYPT_OK' )
199207
200208class SHA256 (object ):
@@ -213,15 +221,17 @@ def __init__(self, key, rounds):
213221 self .state = c_buffer (_get_size ('chacha_state' ))
214222 self .counter = c_int (1 )
215223 err = LTC .chacha_setup (byref (self .state ), key , len (key ), rounds )
224+ if err != CRYPT_OK :
225+ raise Exception ('LTC.chacha_setup(), err = %d, "%s"' % (err , _err2str (err )))
216226 def set_iv32 (self , iv ):
217227 err = LTC .chacha_ivctr32 (byref (self .state ), iv , len (iv ), byref (self .counter ))
218228 if err != CRYPT_OK :
219- raise Exception ('LTC.chacha_ivctr32() err = %d' % err )
229+ raise Exception ('LTC.chacha_ivctr32(), err = %d, "%s" ' % ( err , _err2str ( err )) )
220230 def crypt (self , datain ):
221231 dataout = c_buffer (len (datain ))
222232 err = LTC .chacha_crypt (byref (self .state ), datain , len (datain ), byref (dataout ))
223233 if err != CRYPT_OK :
224- raise Exception ('LTC.chacha_crypt() err = %d' % err )
234+ raise Exception ('LTC.chacha_crypt(), err = %d, "%s" ' % ( err , _err2str ( err )) )
225235 return dataout .raw
226236
227237# - - - - - - - - - - - - -
@@ -254,8 +264,15 @@ def crypt(self, datain):
254264 cha .set_iv32 (iv )
255265 cipher = cha .crypt (plain )
256266
257- template = '\n ChaCha%d ciphertext for "%s" is "%s" \n '
267+ template = '\n ChaCha%d ciphertext for "%s" is "%s"'
258268 print template % (rounds , plain , cipher .encode ('hex' ))
269+
270+ # reset to decrypt
271+ cha .set_iv32 (iv )
272+ decrypted = cha .crypt (cipher )
273+
274+ template = ' ChaCha%d decoded text for "%s" is "%s" \n '
275+ print template % (rounds , plain , decrypted )
259276
260277
261278
0 commit comments