2018-11-03 20:08:13 +00:00
|
|
|
import base64
|
|
|
|
|
2019-10-05 05:14:13 +00:00
|
|
|
|
2021-11-02 10:10:25 +00:00
|
|
|
def base16_encode(inp: str) -> bytes:
|
2020-11-23 07:31:43 +00:00
|
|
|
"""
|
|
|
|
Encodes a given utf-8 string into base-16.
|
2021-10-26 13:23:38 +00:00
|
|
|
|
2021-11-02 10:10:25 +00:00
|
|
|
>>> base16_encode('Hello World!')
|
2020-11-23 07:31:43 +00:00
|
|
|
b'48656C6C6F20576F726C6421'
|
2021-11-02 10:10:25 +00:00
|
|
|
>>> base16_encode('HELLO WORLD!')
|
2020-11-23 07:31:43 +00:00
|
|
|
b'48454C4C4F20574F524C4421'
|
2021-11-02 10:10:25 +00:00
|
|
|
>>> base16_encode('')
|
2020-11-23 07:31:43 +00:00
|
|
|
b''
|
|
|
|
"""
|
2021-10-26 13:23:38 +00:00
|
|
|
# encode the input into a bytes-like object and then encode b16encode that
|
|
|
|
return base64.b16encode(inp.encode("utf-8"))
|
|
|
|
|
|
|
|
|
2021-11-02 10:10:25 +00:00
|
|
|
def base16_decode(b16encoded: bytes) -> str:
|
2021-10-26 13:23:38 +00:00
|
|
|
"""
|
|
|
|
Decodes from base-16 to a utf-8 string.
|
|
|
|
|
2021-11-02 10:10:25 +00:00
|
|
|
>>> base16_decode(b'48656C6C6F20576F726C6421')
|
2021-10-26 13:23:38 +00:00
|
|
|
'Hello World!'
|
2021-11-02 10:10:25 +00:00
|
|
|
>>> base16_decode(b'48454C4C4F20574F524C4421')
|
2021-10-26 13:23:38 +00:00
|
|
|
'HELLO WORLD!'
|
2021-11-02 10:10:25 +00:00
|
|
|
>>> base16_decode(b'')
|
2021-10-26 13:23:38 +00:00
|
|
|
''
|
|
|
|
"""
|
|
|
|
# b16decode the input into bytes and decode that into a human readable string
|
|
|
|
return base64.b16decode(b16encoded).decode("utf-8")
|
2019-10-05 05:14:13 +00:00
|
|
|
|
2018-11-03 20:08:13 +00:00
|
|
|
|
2019-10-05 05:14:13 +00:00
|
|
|
if __name__ == "__main__":
|
2020-11-23 07:31:43 +00:00
|
|
|
import doctest
|
|
|
|
|
|
|
|
doctest.testmod()
|