Archive

Posts Tagged ‘hashlib’

md5 sha Deprecated since version 2.5 Use the hashlib module instead.

July 30th, 2009 2 comments

今天在安装完xmpppy-0.5.0rc1 ,在运行的时候报md5和sha被hashlib替换,查了资料才发现,在Python2.6中使用md5, sha函数不推荐直接使用而是用hashlib替代。

md5

-import md5
-def HH(some): return md5.new(some)
+import hashlib
+def HH(some): return hashlib.md5(some)

sha

-import sha
-def HH(some): return sha.new(some)
+import hashlib
+def HH(some): return hashlib.sha1(some)

都包括 md5(), sha1(), sha224(), sha256(), sha384(), and sha512()

这里给出auth.py md5和sha的patch

diff –git a/xmpp/auth.py b/xmpp/auth.py
index 6e51d72..508718a 100755
— a/xmpp/auth.py
+++ b/xmpp/auth.py
@@ -21,11 +21,11 @@ Can be used both for client and transport authentication.

from protocol import *
from client import PlugIn
-import sha,base64,random,dispatcher,re
+import base64,random,dispatcher,re

-import md5
-def HH(some): return md5.new(some).hexdigest()
-def H(some): return md5.new(some).digest()
+import hashlib
+def HH(some): return hashlib.md5(some).hexdigest()
+def H(some): return hashlib.md5(some).digest()
def C(some): return ‘:’.join(some)

class NonSASL(PlugIn):
@@ -54,15 +54,15 @@ class NonSASL(PlugIn):

if query.getTag(‘digest’):
self.DEBUG(“Performing digest authentication”,’ok’)
-            query.setTagData(‘digest’,sha.new(owner.Dispatcher.Stream._document_attrs['id']+self.password).hexdigest())
+            query.setTagData(‘digest’,hashlib.sha1(owner.Dispatcher.Stream._document_attrs['id']+self.password).hexdigest())
if query.getTag(‘password’): query.delChild(‘password’)
method=’digest’
elif query.getTag(‘token’):
token=query.getTagData(‘token’)
seq=query.getTagData(‘sequence’)
self.DEBUG(“Performing zero-k authentication”,’ok’)
-            hash = sha.new(sha.new(self.password).hexdigest()+token).hexdigest()
-            for foo in xrange(int(seq)): hash = sha.new(hash).hexdigest()
+            hash = hashlib.sha1(hashlib.sha1(self.password).hexdigest()+token).hexdigest()
+            for foo in xrange(int(seq)): hash = hashlib.sha1(hash).hexdigest()
query.setTagData(‘hash’,hash)
method=’0k’
else:
@@ -81,7 +81,7 @@ class NonSASL(PlugIn):
def authComponent(self,owner):
“”" Authenticate component. Send handshake stanza and wait for result. Returns “ok” on success. “”"
self.handshake=0
-        owner.send(Node(NS_COMPONENT_ACCEPT+’ handshake’,payload=[sha.new(owner.Dispatcher.Stream._document_attrs['id']+self.password).hexdigest()]))
+        owner.send(Node(NS_COMPONENT_ACCEPT+’ handshake’,payload=[hashlib.sha1(owner.Dispatcher.Stream._document_attrs['id']+self.password).hexdigest()]))
owner.RegisterHandler(‘handshake’,self.handshakeHandler,xmlns=NS_COMPONENT_ACCEPT)
while not self.handshake:
self.DEBUG(“waiting on handshake”,’notify’)

参考:
1.  hashlib http://docs.python.org/library/hashlib.html#module-hashlib