Looking for help: how to verify if a Hive message is signed correctly in Python Beem. UPDATED!

The story so far.... my Python/Flask website now manages to fire up Hive Keychain thanks to help from @rishi556. I even manage to get the answer in the form of a json response back into the Python Flask back end:

As JSON that looks like this:

{
  "data": {
    "key": "posting",
    "message": "{\"signed_message\":{\"type\":\"login\",\"address\":\"brianoflondon\",\"page\":\"http://127.0.0.1:5000/podcaster/login\"},\"timestamp\":1613710433}",
    "method": "Posting",
    "request_id": 3,
    "type": "signBuffer",
    "username": "brianoflondon"
  },
  "error": null,
  "message": "Message signed succesfully.",
  "publicKey": "STM7B1eanwUQhXa8tdabTi2RxHnXWtyMBd6iJDZ3Z2QA6rKHQY2WJ",
  "request_id": 3,
  "result": "2031e828c6673b945a14489e23a90d5502238d56fb4df568e6ab88af703a9e3bba14ea410bed5afcb42b3d164c976a49645ee2848a8b65fbd9cc77cbc574ae2ffd",
  "success": true
}

Shhh don't tell anyone but right now the only bit my server looks at is the "success":true.

I've taken a look at the Beem Docs and even searched all of github, but there's minimal explanation here.

Can anyone else help with the python to do this?

Thanks in wondrous anticipation! I fully intent to make a very simple, reference and open source implementation of this kind of Hive Keychain interaction with Python Flask.

And huge thanks again to @crokkon:

I will publish the entire system including the javascript and the server side code when I get a chance.

#!/usr/bin/python
from beemgraphenebase.account import PublicKey
from beemgraphenebase.ecdsasig import verify_message
from binascii import hexlify, unhexlify

def validate_hivekeychain_ans(ans):
    """ takes in the answer from hivekeychain and checks everything """
    """ http://bit.ly/keychainpython """

    acc_name = ans['data']['username']
    pubkey = PublicKey(ans['publicKey'])
    enc_msg = ans['data']['message']
    signature = ans['result']

    msgkey = verify_message(enc_msg, unhexlify(signature))
    pk = PublicKey(hexlify(msgkey).decode("ascii"))
    if str(pk) == str(pubkey):
        print("SUCCESS: signature matches given pubkey")
        acc = Account(acc_name)
        match = False, 0
        for key in acc['posting']['key_auths']:
            match = match or ans['publicKey'] in key
        if match:
            print('Matches public key from Hive')
            mtime = json.loads(enc_msg)['timestamp']
            time_since = time.time() - mtime
            if time_since < 30:
                return True , time_since
            else:
                print("ERROR: answer took too long.")
    else:
        print("ERROR: message was signed with a different key")
        return False, 0

brianoflondon hive footer.png

Posted with STEMGeeks