Mini Hashlib Replacement for Jython and Python below 2.5

By Brian

Python Logo I’m back! I’d like to resume things here by giving you a solution to a problem others seem to have had (after searching online). It seems that Jython, a popular implementation of Python in Java, does not have Python 2.5’s hashlib module. This posed a problem to me when I was coding a small Jython application that needed one-way hashing.

Python has now-deprecated md5 and sha modules, so I was able to write a small wrapper for the hexdigest() functionality of the md5 and sha1 objects in hashlib. You are welcome to use the code all you’d like, and feel free to expand on it and send back the changes. Source is after the jump…

#!/usr/bin/env python
#
# minihashlib - A miniature wrapper that provides the hexdigest() method
# for Python versions less than 2.5 (eg. ones that dont have hashlib).
# This wraps around the deprecated md5 and sha Python libraries. This
# code is public domain - there is no license except that you must leave
# this header.
#
# Copyright (C) 2008 Brian Nez
#
import md5
import sha
class hashlib(object):
	"""Emulate a tiny subset of the full hashlib module."""
	class md5(object):
		def __init__(self, string):
			self.string = string
		def hexdigest(self):
			return md5.new(self.string).hexdigest()
	class sha1(object):
		def __init__(self, string):
			self.string = string
		def hexdigest(self):
			return sha.new(self.string).hexdigest()

You can use this code safely in Python 2.5 and Jython by having the following lines of code in your application:

try:
	import hashlib # regular hashlib
except ImportError:
	from minihashlib import hashlib # fallback implementation

Leave a Reply