1

I'm hashing things with uhashlib in micropython on the pi pico. Here's an example:

import sys
import os
import uhashlib
import time

time_now = "blergh"
hash_test = uhashlib.sha256(time_now).digest()

print(time_now)
print(hash_test)

This outputs:

blergh
b'Y|\x84W\xa1\x1d\x86cb~\x0bL\x1e\\\x92\xcd-\x93\x05\xddz\x0e\xe1\x9f\x9a\xc1H6\x93\xd8\x0c8'

...which, clearly, isn't super useful. I've tried a bunch of things, but I can't figure out how to convert from the bytes (b'...') in micropython. Anyone have ideas/methods?

Kuba hasn't forgotten Monica
  • 95,931
  • 16
  • 151
  • 313
syzygetic
  • 25
  • 6
  • what is your question? also you may want [`.hexdigest()`](https://docs.python.org/3/library/hashlib.html#simple-hashing) – ti7 Apr 01 '21 at 20:08
  • hexdigest is what I would use for hashlib (python), but uhashlib (micropython) doesn't support it. The question is exactly what you understood, though, I'm getting bytecode when I want a hexdigest. – syzygetic Apr 01 '21 at 20:23
  • I've also tried ubinascii.hexlify(hash.digest()) , but no dice there - I'm wondering if this is simply broken in micropython right now? – syzygetic Apr 01 '21 at 20:30
  • Note that "bytecode" is not an appropriate term to use here. Yes, it's made of bytes, and yes, you could refer to it as a code - but that term is used to refer to bytes that can be executed by some interpreted language, whereas what you have here is purely data. – jasonharper Apr 01 '21 at 21:39

2 Answers2

3

Use ubinascii.hexlify and jump through hoops.

ubinascii.hexlify() returns bytes. By decoding the bytes to a str and then converting that str to an int (with base16), we can then pass the value to hex(). There is no hex attribute for bytes in micropython.

The below has been fully tested on the Raspberry Pi Pico running micropython 1.14. I suspect earlier versions would also work, as long as they possess both of the module dependencies.

import ubinascii, uhashlib

hs = uhashlib.sha256(b'blergh')

def hexdigest(sha):
    return hex(int(ubinascii.hexlify(sha.digest()).decode(), 16))

hx = hexdigest(hs) #0x597c8457a11d8663627e0b4c1e5c92cd2d9305dd7a0ee19f9ac1483693d80c38

OneMadGypsy
  • 4,640
  • 3
  • 10
  • 26
2

You should be able to directly decode any bytes to hex with the .hex() method on it!

>>> b"blerg".hex()
'626c657267'

I don't have uhashlib, but this works with the stock hashlib!

>>> hashlib.sha256(b"blergh").digest().hex()
'597c8457a11d8663627e0b4c1e5c92cd2d9305dd7a0ee19f9ac1483693d80c38'
>>> hashlib.sha256(b"blergh").hexdigest()
'597c8457a11d8663627e0b4c1e5c92cd2d9305dd7a0ee19f9ac1483693d80c38'
ti7
  • 16,375
  • 6
  • 40
  • 68