nakagami / micropg

PostgreSQL database driver for MicroPython
MIT License
26 stars 2 forks source link

AttributeError: 'module' object has no attribute 'md5' #2

Closed jedo-tm closed 2 years ago

jedo-tm commented 2 years ago

When I run this micropython code on a micropython device (esp32-20220117-v1.18.bin )

import micropg
c=micropg.connect(host='192.168.xxx.yyy', database='database',user='username',password='secret')

I get this error

Traceback (most recent call last):
  File "<stdin>", line 5, in <module>
  File "/lib/micropg.py", line 789, in connect
  File "/lib/micropg.py", line 385, in __init__
  File "/lib/micropg.py", line 704, in _open
  File "/lib/micropg.py", line 653, in process_messages
  File "/lib/micropg.py", line 418, in _process_messages
AttributeError: 'module' object has no attribute 'md5'

I have configured postgres to use md5 method on the the subnet

/etc/postgresql/12/main/pg_hba.conf

# IPv4 local connections:

host    all             all             127.0.0.1/32            md5
host    all             all             192.168.1.1/16          md5

I have tested on with python and psycopg2 on a linux computer - here I can connect and insert data to the postgress database

nakagami commented 2 years ago

Probably hashlib.md5 is not available in your micropython.

https://docs.micropython.org/en/latest/library/hashlib.html

MicroPython v1.12-1 on 2020-02-09; linux version
Use Ctrl-D to exit, Ctrl-E for paste mode
>>> import hashlib
>>> hashlib.md5
<class 'md5'>
>>>
jedo-tm commented 2 years ago

Well that was spot on.

As the link describe It seems that md5 support is only available for certain micropython. I tried downgrading to esp32 V1.12. but that didn't work either. Would you happen to know an ( easy :) ) workaround for this?

nakagami commented 2 years ago

I found this post.

https://forum.micropython.org/viewtopic.php?t=3424

This might be helpful to you https://forum.micropython.org/viewtopic.php?t=3424#p19964

In that case, you will need to modify micropg.py

jedo-tm commented 2 years ago

Thanks

I got it working with the code from Lemariva as you suggested. The only thing I changed in that code was the last two lines so that the digest function returns raw

   #return '{:032x}'.format(int.from_bytes(raw, 'big'))
    return raw

Subsequently I changed these two lines in mircropg

                    #h1 = binascii.hexlify(hashlib.md5(self.password.encode('ascii') + self.user.encode("ascii")).digest())
                    #h2 = binascii.hexlify(hashlib.md5(h1 + salt).digest())
                    h1 = binascii.hexlify(digest(self.password.encode('ascii') + self.user.encode("ascii")))
                    h2 = binascii.hexlify(digest(h1 + salt))