Decodes the given base16 encoded data into bytes. >>> base16_decode('48656C6C6F20576F726C6421') b'Hello World!' >>> base16_decode('48454C4C4F20574F524C4421') b'HELLO WORLD!' >>> base16_decode('') b'' >>> base16_decode('486') Traceback (most recent call last):
(data: str)
| 16 | |
| 17 | |
| 18 | def base16_decode(data: str) -> bytes: |
| 19 | """ |
| 20 | Decodes the given base16 encoded data into bytes. |
| 21 | |
| 22 | >>> base16_decode('48656C6C6F20576F726C6421') |
| 23 | b'Hello World!' |
| 24 | >>> base16_decode('48454C4C4F20574F524C4421') |
| 25 | b'HELLO WORLD!' |
| 26 | >>> base16_decode('') |
| 27 | b'' |
| 28 | >>> base16_decode('486') |
| 29 | Traceback (most recent call last): |
| 30 | ... |
| 31 | ValueError: Base16 encoded data is invalid: |
| 32 | Data does not have an even number of hex digits. |
| 33 | >>> base16_decode('48656c6c6f20576f726c6421') |
| 34 | Traceback (most recent call last): |
| 35 | ... |
| 36 | ValueError: Base16 encoded data is invalid: |
| 37 | Data is not uppercase hex or it contains invalid characters. |
| 38 | >>> base16_decode('This is not base64 encoded data.') |
| 39 | Traceback (most recent call last): |
| 40 | ... |
| 41 | ValueError: Base16 encoded data is invalid: |
| 42 | Data is not uppercase hex or it contains invalid characters. |
| 43 | """ |
| 44 | # Check data validity, following RFC3548 |
| 45 | # https://www.ietf.org/rfc/rfc3548.txt |
| 46 | if (len(data) % 2) != 0: |
| 47 | raise ValueError( |
| 48 | """Base16 encoded data is invalid: |
| 49 | Data does not have an even number of hex digits.""" |
| 50 | ) |
| 51 | # Check the character set - the standard base16 alphabet |
| 52 | # is uppercase according to RFC3548 section 6 |
| 53 | if not set(data) <= set("0123456789ABCDEF"): |
| 54 | raise ValueError( |
| 55 | """Base16 encoded data is invalid: |
| 56 | Data is not uppercase hex or it contains invalid characters.""" |
| 57 | ) |
| 58 | # For every two hexadecimal digits (= a byte), turn it into an integer. |
| 59 | # Then, string the result together into bytes, and return it. |
| 60 | return bytes(int(data[i] + data[i + 1], 16) for i in range(0, len(data), 2)) |
| 61 | |
| 62 | |
| 63 | if __name__ == "__main__": |
nothing calls this directly
no outgoing calls
no test coverage detected