Advertisement
rfmonk

hmac_pickle.py

Jan 31st, 2014
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.87 KB | None | 0 0
  1. #!/usr/bin/env python
  2.  
  3. # this is from The Python
  4. # Standard Library by example
  5. # ISBN13: 9780321767349
  6.  
  7. import hashlib
  8. import hmac
  9. try:
  10.     import cPickle as pickle
  11. except:
  12.     import pickle
  13. import pprint
  14. from StringIO import StringIO
  15.  
  16.  
  17. def make_digest(message):
  18.     "Return a digest for the message."
  19.     hash = hmac.new('secret-shared-key', message, hashlib.sha1)
  20.     return hash.hexdigest()
  21.  
  22.  
  23. class SimpleObject(object):
  24.     """A very simple class to demonstrate checking digests
  25.    before unpickling.
  26.    """
  27.     def __init__(self, name):
  28.         self.name = name
  29.  
  30.     def __str__(self):
  31.         return self.name
  32.  
  33. # Simulate a writable socket or pipe with StringIO
  34. out_s = StringIO()
  35.  
  36. # Write a valid object to the stream:
  37. # digest\nlength\npickle
  38. o = SimpleObject('digest matches')
  39. pickled_data = pickle.dumps(o)
  40. digest = make_digest(pickled_data)
  41. header = '%s %s' % (digest, len(pickled_data))
  42. print 'WRITING:', header
  43. out_s.write(header + '\n')
  44. out_s.write(pickled_data)
  45.  
  46. # Write an invalid object to the stream
  47. o = SimpleObject('digest does not match')
  48. pickled_data = pickle.dumps(o)
  49. digest = make_digest('not the pickled data at all')
  50. header = '%s %s' % (digest, len(pickled_data))
  51. print '\nWRITING:', header
  52. out_s.write(header + '\n')
  53. out_s.write(pickled_data)
  54. out_s.flush()
  55.  
  56. # Simulate a readable socket or pipe with StringIO
  57. in_s = StringIO(out_s.getvalue())
  58.  
  59. # Read the data
  60. while True:
  61.     first_line = in_s.readline()
  62.     if not first_line:
  63.         break
  64.     incoming_digest, incoming_length = first_line.split(' ')
  65.     incoming_length = int(incoming_length)
  66.     print '\nREAD:', incoming_digest, incoming_length
  67.  
  68.     incoming_pickled_data = in_s.read(incoming_length)
  69.  
  70. actual_digest = make_digest(incoming_pickled_data)
  71. print 'ACTUAL:', actual_digest
  72.  
  73. if incoming_digest != actual_digest:
  74.     print 'WARNING: Data corruption'
  75. else:
  76.     obj = pickle.loads(incoming_pickled_data)
  77.     print 'OK:', obj
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement