Cryptography

1. Simple Hashing

Use the hashlib library for hashing functions like MD5 and SHA-1

   1 import hashlib
   2 
   3 text="Mary had a little lamb"
   4 
   5 md5 = hashlib.md5() 
   6 md5.update(text)
   7 
   8 sha1 = hashlib.sha1()
   9 sha1.update(text)
  10 
  11 print md5.digest()
  12 # Prints the (binary) digest. Actually it is unsuitable for display
  13 
  14 print md5.hexdigest()
  15 # 'e946adb45d4299def2071880d30136d4'
  16 
  17 print sha1.hexdigest()
  18 # 'bac9388d0498fb378e528d35abd05792291af182'
  19 
  20 print "MD5 = %d bits, SHA-1 = %d bits" % (len(md5.hexdigest()) * 4, len(sha1.hexdigest()) * 4)
  21 # 'MD5 = 128 bits, SHA-1 = 160 bits'
  22 # ... always!
  23 
  24 # One liners!
  25 print hashlib.sha1(text).hexdigest()
  26 # 'bac9388d0498fb378e528d35abd05792291af182'
  27 
  28 # Use update() when you are processing multiple blocks of data
  29 
  30 md5 = hashlib.md5()
  31 for x in open('/home/sandipb/.bashrc'): md5.update(x)
  32 print md5.hexdigest() # >>> '20ede33b79459b380c9c72a731f4cc04'
  33 #
  34 # Using the Linux tool
  35 # $ md5sum ~/.bashrc
  36 # 20ede33b79459b380c9c72a731f4cc04  /home/sandipb/.bashrc
  37 #
  38 

hashlib supports md5(), sha1(), sha224(), sha256(), sha384(), and sha512()

2. Hashing with a symmetric key

Using a shared secret/salt, the hashlib methods can be made more difficult to crack.

Use the hmac module for this.

   1 import hmac, hashlib
   2 
   3 text="Mary had a little lamb"
   4 secret="wolf"
   5 
   6 hash = hmac.new( secret, digestmod=hashlib.sha1)
   7 hash.update(text)
   8 print hash.hexdigest()
   9 # '01872dea0802454638b605093107b297c8f0e915'
  10 
  11 # or
  12 
  13 print hmac.new('wolf', text, hashlib.sha1).hexdigest()
  14 # '01872dea0802454638b605093107b297c8f0e915'
  15 

Python/Cryptography (last edited 2010-09-11 14:14:42 by SandipBhattacharya)