Encodes data according to RFC4648. The data is first transformed to binary and appended with binary digits so that its length becomes a multiple of 6, then each 6 binary digits will match a character in the B64_CHARSET string. The number of appended binary digits would later determine
(data: bytes)
| 2 | |
| 3 | |
| 4 | def base64_encode(data: bytes) -> bytes: |
| 5 | """Encodes data according to RFC4648. |
| 6 | |
| 7 | The data is first transformed to binary and appended with binary digits so that its |
| 8 | length becomes a multiple of 6, then each 6 binary digits will match a character in |
| 9 | the B64_CHARSET string. The number of appended binary digits would later determine |
| 10 | how many "=" signs should be added, the padding. |
| 11 | For every 2 binary digits added, a "=" sign is added in the output. |
| 12 | We can add any binary digits to make it a multiple of 6, for instance, consider the |
| 13 | following example: |
| 14 | "AA" -> 0010100100101001 -> 001010 010010 1001 |
| 15 | As can be seen above, 2 more binary digits should be added, so there's 4 |
| 16 | possibilities here: 00, 01, 10 or 11. |
| 17 | That being said, Base64 encoding can be used in Steganography to hide data in these |
| 18 | appended digits. |
| 19 | |
| 20 | >>> from base64 import b64encode |
| 21 | >>> a = b"This pull request is part of Hacktoberfest20!" |
| 22 | >>> b = b"https://tools.ietf.org/html/rfc4648" |
| 23 | >>> c = b"A" |
| 24 | >>> base64_encode(a) == b64encode(a) |
| 25 | True |
| 26 | >>> base64_encode(b) == b64encode(b) |
| 27 | True |
| 28 | >>> base64_encode(c) == b64encode(c) |
| 29 | True |
| 30 | >>> base64_encode("abc") |
| 31 | Traceback (most recent call last): |
| 32 | ... |
| 33 | TypeError: a bytes-like object is required, not 'str' |
| 34 | """ |
| 35 | # Make sure the supplied data is a bytes-like object |
| 36 | if not isinstance(data, bytes): |
| 37 | msg = f"a bytes-like object is required, not '{data.__class__.__name__}'" |
| 38 | raise TypeError(msg) |
| 39 | |
| 40 | binary_stream = "".join(bin(byte)[2:].zfill(8) for byte in data) |
| 41 | |
| 42 | padding_needed = len(binary_stream) % 6 != 0 |
| 43 | |
| 44 | if padding_needed: |
| 45 | # The padding that will be added later |
| 46 | padding = b"=" * ((6 - len(binary_stream) % 6) // 2) |
| 47 | |
| 48 | # Append binary_stream with arbitrary binary digits (0's by default) to make its |
| 49 | # length a multiple of 6. |
| 50 | binary_stream += "0" * (6 - len(binary_stream) % 6) |
| 51 | else: |
| 52 | padding = b"" |
| 53 | |
| 54 | # Encode every 6 binary digits to their corresponding Base64 character |
| 55 | return ( |
| 56 | "".join( |
| 57 | B64_CHARSET[int(binary_stream[index : index + 6], 2)] |
| 58 | for index in range(0, len(binary_stream), 6) |
| 59 | ).encode() |
| 60 | + padding |
| 61 | ) |