changeset 4363:817d99d715fe

remove direct usage of deprecated sha module - use hashlib, if possible
author Thomas Waldmann <tw AT waldmann-edv DOT de>
date Fri, 03 Oct 2008 22:33:35 +0200
parents adec0c4861f7
children 5237eb242765
files MoinMoin/action/cache.py MoinMoin/action/info.py MoinMoin/config/multiconfig.py MoinMoin/log.py MoinMoin/macro/FootNote.py MoinMoin/parser/_ParserBase.py MoinMoin/parser/text_creole.py MoinMoin/parser/text_python.py MoinMoin/script/migration/text_moin158_wiki.py MoinMoin/script/migration/text_moin160a_wiki.py MoinMoin/script/migration/wikiutil160a.py MoinMoin/support/python_compatibility.py MoinMoin/user.py MoinMoin/userprefs/oid.py MoinMoin/util/moinoid.py MoinMoin/wikiutil.py
diffstat 16 files changed, 51 insertions(+), 43 deletions(-) [+]
line wrap: on
line diff
--- a/MoinMoin/action/cache.py	Fri Oct 03 21:18:49 2008 +0200
+++ b/MoinMoin/action/cache.py	Fri Oct 03 22:33:35 2008 +0200
@@ -27,8 +27,6 @@
     @license: GNU GPL, see COPYING for details.
 """
 
-import hmac, sha
-
 from MoinMoin import log
 logging = log.getLogger(__name__)
 
@@ -39,6 +37,7 @@
 from MoinMoin import config, caching
 from MoinMoin.util import filesys
 from MoinMoin.action import AttachFile
+from MoinMoin.support.python_compatibility import hmac_new
 
 action_name = __name__.split('.')[-1]
 
@@ -98,7 +97,7 @@
         raise AssertionError('cache_key called with unsupported parameters')
 
     hmac_data = hmac_data.encode('utf-8')
-    key = hmac.new(secret, hmac_data, sha).hexdigest()
+    key = hmac_new(secret, hmac_data).hexdigest()
     return key
 
 
--- a/MoinMoin/action/info.py	Fri Oct 03 21:18:49 2008 +0200
+++ b/MoinMoin/action/info.py	Fri Oct 03 22:33:35 2008 +0200
@@ -32,8 +32,8 @@
                       f.text(_("Page size: %d") % page.size()),
                       f.paragraph(0))
 
-        import sha
-        digest = sha.new(page.get_raw_body().encode(config.charset)).hexdigest().upper()
+        from MoinMoin.support.python_compatibility import hash_new
+        digest = hash_new('sha1', page.get_raw_body().encode(config.charset)).hexdigest().upper()
         request.write(f.paragraph(1),
                       f.rawHTML('%(label)s <tt>%(value)s</tt>' % {
                           'label': _("SHA digest of this page's content is:"),
--- a/MoinMoin/config/multiconfig.py	Fri Oct 03 21:18:49 2008 +0200
+++ b/MoinMoin/config/multiconfig.py	Fri Oct 03 22:33:35 2008 +0200
@@ -569,7 +569,8 @@
         Since each configured plugin path has unique plugins, we load the
         plugin packages as "moin_plugin_<sha1(path)>.plugin".
         """
-        import imp, sha
+        import imp
+        from MoinMoin.support.python_compatibility import hash_new
 
         plugin_dirs = [self.plugin_dir] + self.plugin_dirs
         self._plugin_modules = []
@@ -579,7 +580,7 @@
             imp.acquire_lock()
             try:
                 for pdir in plugin_dirs:
-                    csum = 'p_%s' % sha.new(pdir).hexdigest()
+                    csum = 'p_%s' % hash_new('sha1', pdir).hexdigest()
                     modname = '%s.%s' % (self.siteid, csum)
                     # If the module is not loaded, try to load it
                     if not modname in sys.modules:
--- a/MoinMoin/log.py	Fri Oct 03 21:18:49 2008 +0200
+++ b/MoinMoin/log.py	Fri Oct 03 22:33:35 2008 +0200
@@ -95,10 +95,6 @@
 
 import warnings
 
-# hashlib was added in python 2.5 - we can't use it as long as we do not require 2.5
-# sha is deprecated since 2.5, but still present in 2.6
-warnings.filterwarnings('ignore', r'the sha module is deprecated; use the hashlib module instead')
-
 # 'CacheNeedsUpdate' string exception in Page.py is supported for backwards compat reasons:
 warnings.filterwarnings('ignore', r'catching of string exceptions is deprecated', module='MoinMoin.Page')
 
--- a/MoinMoin/macro/FootNote.py	Fri Oct 03 21:18:49 2008 +0200
+++ b/MoinMoin/macro/FootNote.py	Fri Oct 03 22:33:35 2008 +0200
@@ -11,10 +11,9 @@
     @license: GNU GPL, see COPYING for details.
 """
 
-import sha
-
 from MoinMoin import config, wikiutil
 from MoinMoin.parser.text_moin_wiki import Parser as WikiParser
+from MoinMoin.support.python_compatibility import hash_new
 
 Dependencies = ["time"] # footnote macro cannot be cached
 
@@ -35,7 +34,7 @@
         idx = request.footnote_ctr
         request.footnote_ctr += 1
 
-        shahex = sha.new(args.encode(config.charset)).hexdigest()
+        shahex = hash_new('sha1', args.encode(config.charset)).hexdigest()
         backlink_id = "fndef-%s-%d" % (shahex, idx)
         fwdlink_id = "fnref-%s" % shahex
 
--- a/MoinMoin/parser/_ParserBase.py	Fri Oct 03 21:18:49 2008 +0200
+++ b/MoinMoin/parser/_ParserBase.py	Fri Oct 03 22:33:35 2008 +0200
@@ -24,9 +24,10 @@
 
 """
 
-import re, sha
+import re
 
 from MoinMoin import config, wikiutil
+from MoinMoin.support.python_compatibility import hash_new
 
 class FormatTextBase:
     pass
@@ -250,7 +251,7 @@
 
         result = [] # collects output
 
-        self._code_id = sha.new(self.raw.encode(config.charset)).hexdigest()
+        self._code_id = hash_new('sha1', self.raw.encode(config.charset)).hexdigest()
         result.append(formatter.code_area(1, self._code_id, self.parsername, self.show_nums, self.num_start, self.num_step))
 
         self.lastpos = 0
--- a/MoinMoin/parser/text_creole.py	Fri Oct 03 21:18:49 2008 +0200
+++ b/MoinMoin/parser/text_creole.py	Fri Oct 03 22:33:35 2008 +0200
@@ -228,10 +228,11 @@
 #        return self.formatter.smiley(node.content)
 
     def header_emit(self, node):
-        import sha
+        from MoinMoin.support.python_compatibility import hash_new
+
         pntt = '%s%s%d' % (self.formatter.page.page_name,
             self.get_text(node), node.level)
-        ident = "head-%s" % sha.new(pntt.encode(config.charset)).hexdigest()
+        ident = "head-%s" % hash_new('sha1', pntt.encode(config.charset)).hexdigest()
         return ''.join([
             self.formatter.heading(1, node.level, id=ident),
             self.formatter.text(node.content or ''),
--- a/MoinMoin/parser/text_python.py	Fri Oct 03 21:18:49 2008 +0200
+++ b/MoinMoin/parser/text_python.py	Fri Oct 03 22:33:35 2008 +0200
@@ -8,10 +8,11 @@
 """
 
 import StringIO
-import keyword, token, tokenize, sha
+import keyword, token, tokenize
 
 from MoinMoin import config, wikiutil
 from MoinMoin.parser._ParserBase import parse_start_step
+from MoinMoin.support.python_compatibility import hash_new
 
 _KEYWORD = token.NT_OFFSET + 1
 _TEXT = token.NT_OFFSET + 2
@@ -62,7 +63,7 @@
 
         self.result = [] # collects output
 
-        self._code_id = sha.new(self.raw.encode(config.charset)).hexdigest()
+        self._code_id = hash_new('sha1', self.raw.encode(config.charset)).hexdigest()
         self.result.append(formatter.code_area(1, self._code_id, 'ColorizedPython', self.show_num, self.num_start, self.num_step))
         self.formatter = formatter
         self.result.append(formatter.code_line(1))
--- a/MoinMoin/script/migration/text_moin158_wiki.py	Fri Oct 03 21:18:49 2008 +0200
+++ b/MoinMoin/script/migration/text_moin158_wiki.py	Fri Oct 03 22:33:35 2008 +0200
@@ -748,7 +748,7 @@
 
     def _heading_repl(self, word):
         """Handle section headings."""
-        import sha
+        from MoinMoin.support.python_compatibility import hash_new
 
         h = word.strip()
         level = 1
@@ -768,7 +768,7 @@
         if self.titles[pntt] > 1:
             unique_id = '-%d' % self.titles[pntt]
         result = self._closeP()
-        result += self.formatter.heading(1, depth, id="head-"+sha.new(pntt.encode(config.charset)).hexdigest()+unique_id)
+        result += self.formatter.heading(1, depth, id="head-"+hash_new('sha1', pntt.encode(config.charset)).hexdigest()+unique_id)
 
         return (result + self.formatter.text(title_text) +
                 self.formatter.heading(0, depth))
--- a/MoinMoin/script/migration/text_moin160a_wiki.py	Fri Oct 03 21:18:49 2008 +0200
+++ b/MoinMoin/script/migration/text_moin160a_wiki.py	Fri Oct 03 22:33:35 2008 +0200
@@ -767,7 +767,7 @@
 
     def _heading_repl(self, word):
         """Handle section headings."""
-        import sha
+        from MoinMoin.support.python_compatibility import hash_new
 
         h = word.strip()
         level = 1
@@ -786,7 +786,7 @@
         if self.titles[pntt] > 1:
             unique_id = '-%d' % self.titles[pntt]
         result = self._closeP()
-        result += self.formatter.heading(1, depth, id="head-"+sha.new(pntt.encode(config.charset)).hexdigest()+unique_id)
+        result += self.formatter.heading(1, depth, id="head-"+hash_new('sha1', pntt.encode(config.charset)).hexdigest()+unique_id)
 
         return (result + self.formatter.text(title_text) +
                 self.formatter.heading(0, depth))
--- a/MoinMoin/script/migration/wikiutil160a.py	Fri Oct 03 21:18:49 2008 +0200
+++ b/MoinMoin/script/migration/wikiutil160a.py	Fri Oct 03 22:33:35 2008 +0200
@@ -1598,10 +1598,9 @@
 
 def createTicket(request, tm=None):
     """Create a ticket using a site-specific secret (the config)"""
-    import sha
+    from MoinMoin.support.python_compatibility import hash_new
     ticket = tm or "%010x" % time.time()
-    digest = sha.new()
-    digest.update(ticket)
+    digest = hash_new('sha1', ticket)
 
     varnames = ['data_dir', 'data_underlay_dir', 'language_default',
                 'mail_smarthost', 'mail_from', 'page_front_page',
--- a/MoinMoin/support/python_compatibility.py	Fri Oct 03 21:18:49 2008 +0200
+++ b/MoinMoin/support/python_compatibility.py	Fri Oct 03 22:33:35 2008 +0200
@@ -81,13 +81,21 @@
 although it may not be 100% compatible.
 """
 try:
-    from hashlib import new as hash_new
+    import hashlib, hmac
+    hash_new = hashlib.new
+    def hmac_new(key, msg, digestmod=hashlib.sha1):
+        return hmac.new(key, msg, digestmod)
+
 except (NameError,  ImportError):
+    import sha
     def hash_new(name, string=''):
         if name in ('SHA1', 'sha1'):
-            import sha
             return sha.new(string)
         elif name in ('MD5', 'md5'):
             import md5
             return md5.new(string)
         raise ValueError("unsupported hash type")
+
+    def hmac_new(key, msg, digestmod=sha):
+        return hmac.new(key, msg, digestmod)
+
--- a/MoinMoin/user.py	Fri Oct 03 21:18:49 2008 +0200
+++ b/MoinMoin/user.py	Fri Oct 03 22:33:35 2008 +0200
@@ -22,7 +22,9 @@
 # add names here to hide them in the cgitb traceback
 unsafe_names = ("id", "key", "val", "user_data", "enc_password", "recoverpass_key")
 
-import os, time, sha, codecs, hmac, base64
+import os, time, codecs, base64
+
+from MoinMoin.support.python_compatibility import hash_new, hmac_new
 
 from MoinMoin import config, caching, wikiutil, i18n, events
 from MoinMoin.util import timefuncs, filesys, random_string
@@ -154,7 +156,7 @@
     if salt is None:
         salt = random_string(20)
     assert isinstance(salt, str)
-    hash = sha.new(pwd)
+    hash = hash_new('sha1', pwd)
     hash.update(salt)
 
     return '{SSHA}' + base64.encodestring(hash.digest() + salt).rstrip()
@@ -514,7 +516,7 @@
         password = password.encode('utf-8')
 
         if epwd[:5] == '{SHA}':
-            enc = '{SHA}' + base64.encodestring(sha.new(password).digest()).rstrip()
+            enc = '{SHA}' + base64.encodestring(hash_new('sha1', password).digest()).rstrip()
             if epwd == enc:
                 data['enc_password'] = encodePassword(password)
                 return True, True
@@ -523,7 +525,7 @@
         if epwd[:6] == '{SSHA}':
             data = base64.decodestring(epwd[6:])
             salt = data[20:]
-            hash = sha.new(password)
+            hash = hash_new('sha1', password)
             hash.update(salt)
             return hash.digest() == data[:20], False
 
@@ -983,7 +985,7 @@
     def generate_recovery_token(self):
         key = random_string(64, "abcdefghijklmnopqrstuvwxyz0123456789")
         msg = str(int(time.time()))
-        h = hmac.new(key, msg, sha).hexdigest()
+        h = hmac_new(key, msg).hexdigest()
         self.recoverpass_key = key
         self.save()
         return msg + '-' + h
@@ -1001,7 +1003,7 @@
         if stamp + 12*60*60 < time.time():
             return False
         # check hmac
-        h = hmac.new(self.recoverpass_key, str(stamp), sha).hexdigest()
+        h = hmac_new(self.recoverpass_key, str(stamp)).hexdigest()
         if h != parts[1]:
             return False
         self.recoverpass_key = ""
--- a/MoinMoin/userprefs/oid.py	Fri Oct 03 21:18:49 2008 +0200
+++ b/MoinMoin/userprefs/oid.py	Fri Oct 03 22:33:35 2008 +0200
@@ -9,7 +9,8 @@
 from MoinMoin import wikiutil, user
 from MoinMoin.widget import html
 from MoinMoin.userprefs import UserPrefBase
-import sha
+from MoinMoin.support.python_compatibility import hash_new
+
 try:
     from MoinMoin.auth.openidrp import OpenIDAuth
     from MoinMoin.util.moinoid import MoinOpenIDStore
@@ -45,7 +46,7 @@
             return
         openids = self.request.user.openids[:]
         for oid in self.request.user.openids:
-            name = "rm-%s" % sha.new(oid).hexdigest()
+            name = "rm-%s" % hash_new('sha1', oid).hexdigest()
             if name in self.request.form:
                 openids.remove(oid)
         if not openids and len(self.request.cfg.auth) == 1:
@@ -170,7 +171,7 @@
         _ = self.request.getText
         form = self._make_form()
         for oid in self.request.user.openids:
-            name = "rm-%s" % sha.new(oid).hexdigest()
+            name = "rm-%s" % hash_new('sha1', oid).hexdigest()
             form.append(html.INPUT(type="checkbox", name=name, id=name))
             form.append(html.LABEL(for_=name).append(html.Text(oid)))
             form.append(html.BR())
--- a/MoinMoin/util/moinoid.py	Fri Oct 03 21:18:49 2008 +0200
+++ b/MoinMoin/util/moinoid.py	Fri Oct 03 22:33:35 2008 +0200
@@ -5,7 +5,6 @@
     @license: GNU GPL, see COPYING for details.
 """
 
-from sha import sha
 from random import randint
 import time
 
@@ -15,6 +14,7 @@
 from openid.store import nonce
 
 from MoinMoin import caching
+from MoinMoin.support.python_compatibility import hash_new
 
 from MoinMoin import log
 logging = log.getLogger(__name__)
@@ -53,7 +53,7 @@
 
     def key(self, url):
         '''return cache key'''
-        return sha(url).hexdigest()
+        return hash_new('sha1', url).hexdigest()
 
     def storeAssociation(self, server_url, association):
         ce = caching.CacheEntry(self.request, 'openid', self.key(server_url),
@@ -104,7 +104,7 @@
 
     def useNonce(self, server_url, timestamp, salt):
         val = ''.join([str(server_url), str(timestamp), str(salt)])
-        csum = sha(val).hexdigest()
+        csum = hash_new('sha1', val).hexdigest()
         ce = caching.CacheEntry(self.request, 'openid-nonce', csum,
                                 scope='farm', use_pickle=False)
         if ce.exists():
--- a/MoinMoin/wikiutil.py	Fri Oct 03 21:18:49 2008 +0200
+++ b/MoinMoin/wikiutil.py	Fri Oct 03 22:33:35 2008 +0200
@@ -2439,7 +2439,7 @@
                              action you call when posting the form.
     """
 
-    import sha
+    from MoinMoin.support.python_compatibility import hash_new
     if tm is None:
         tm = "%010x" % time.time()
 
@@ -2456,7 +2456,7 @@
             action = 'None'
 
     secret = request.cfg.secrets['wikiutil/tickets']
-    digest = sha.new(secret)
+    digest = hash_new('sha1', secret)
 
     ticket = "%s.%s.%s" % (tm, pagename, action)
     digest.update(ticket)