Skip to content

Instantly share code, notes, and snippets.

@davidlatwe
Last active November 11, 2020 11:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davidlatwe/e08044df3361c38b081d57f8a936f4db to your computer and use it in GitHub Desktop.
Save davidlatwe/e08044df3361c38b081d57f8a936f4db to your computer and use it in GitHub Desktop.
Monkey patch pymongo.auth for Houdini 18.5.351 to avoid "ValueError: unsupported hash type" when connecting MongoDB with Auth enabled (error raised on all version of MongoDB and all versions of PyMongo)
def patch():
import hmac
import hashlib
from pymongo import auth
def _hi(hash_name, data, salt, iterations):
"""A simple implementation of PBKDF2-HMAC.
This is grabed from pymongo.auth module
https://github.com/mongodb/mongo-python-driver/blob/master/pymongo/auth.py#L200-L218
Which was being used when the Python cannot import hashlib.pbkdf2_hmac.
And in this case, seems something wrong with Houdini's hashlib, both Python 2 & 3 build.
"""
mac = hmac.HMAC(data, None, getattr(hashlib, hash_name))
def _digest(msg, mac=mac):
"""Get a digest for msg."""
_mac = mac.copy()
_mac.update(msg)
return _mac.digest()
from_bytes = _from_bytes
to_bytes = _to_bytes
_u1 = _digest(salt + b'\x00\x00\x00\x01')
_ui = from_bytes(_u1, 'big')
for _ in range(iterations - 1):
_u1 = _digest(_u1)
_ui ^= from_bytes(_u1, 'big')
return to_bytes(_ui, mac.digest_size, 'big')
setattr(auth, "_hi", _hi)
print("Patching PyMongo ...")
patch()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment