0

I'm trying to import base64 on the SEEED Xiao ESP32-C3 which is running circuitpython version 8 beta 6. However, when I use import base64 or import ubase64 I see the error ImportError: no module named 'base64' which is the same for ubase64. The only option was to use !pip install circuitpython-base64 which does not include b32decode. I read that base64 comes with Python by default which does not seem to be the case here. Is there any workaround?

hcheung
  • 3,377
  • 3
  • 11
  • 23
Aditya Desai
  • 1
  • 1
  • 3

2 Answers2

1

circuitpython-base64 does include b32decode! If you want to take a look at the source it is here. After running pip install circuitpython-base64, the following script should work.

import circuitpython_base64 as base64

bytes_to_encode = b"Aladdin:open sesame"
print(repr(bytes_to_encode))

base32_string = base64.b32encode(bytes_to_encode)
print(repr(base32_string))

decoded_bytes = base632.b32decode(base32_string)
print(repr(decoded_bytes))
Dacoolinus
  • 388
  • 1
  • 10
  • Thank you for your reply. I've looked into the library found here: https://circuitpython.org/libraries and have downloaded version 8.x as I'm using CircuitPython version 8 beta 6. I copied and moved the .mpy file from the bundle into /lib on the device and tried the above program but I still see the same error as above. – Aditya Desai Jan 28 '23 at 07:11
0

Reffering to: https://learn.adafruit.com/circuitpython-totp-otp-2fa-authy-authenticator-friend/software

I found that I can use the defined base 32 decoding function to decode a given base32 encoded value:

def base32_decode(encoded):
    missing_padding = len(encoded) % 8
    if missing_padding != 0:
        encoded += '=' * (8 - missing_padding)
    encoded = encoded.upper()
    chunks = [encoded[i:i + 8] for i in range(0, len(encoded), 8)]
    out = []
    for chunk in chunks:
        bits = 0
        bitbuff = 0
        for c in chunk:
            if 'A' <= c <= 'Z':
                n = ord(c) - ord('A')
            elif '2' <= c <= '7':
                n = ord(c) - ord('2') + 26
            elif c == '=':
                continue
            else:
                raise ValueError("Not base32")
            # 5 bits per 8 chars of base32
            bits += 5
            # shift down and add the current value
            bitbuff <<= 5
            bitbuff |= n
            # great! we have enough to extract a byte
            if bits >= 8:
                bits -= 8
                byte = bitbuff >> bits  # grab top 8 bits
                bitbuff &= ~(0xFF << bits)  # and clear them
                out.append(byte)  # store what we got
return out


# Testing the function:
print("Base32 test: ", bytes(base32_decode("IFSGCZTSOVUXIIJB")))
# should be "Adafruit!!"
Aditya Desai
  • 1
  • 1
  • 3