Skip to content

replace base64_cipher.py with an easy to understand version #3244

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 8 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion DIRECTORY.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@
* [Atbash](https://github.com/TheAlgorithms/Python/blob/master/ciphers/atbash.py)
* [Base16](https://github.com/TheAlgorithms/Python/blob/master/ciphers/base16.py)
* [Base32](https://github.com/TheAlgorithms/Python/blob/master/ciphers/base32.py)
* [Base64 Cipher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/base64_cipher.py)
* [Base64 Encoding](https://github.com/TheAlgorithms/Python/blob/master/ciphers/base64_encoding.py)
* [Base85](https://github.com/TheAlgorithms/Python/blob/master/ciphers/base85.py)
* [Beaufort Cipher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/beaufort_cipher.py)
* [Brute Force Caesar Cipher](https://github.com/TheAlgorithms/Python/blob/master/ciphers/brute_force_caesar_cipher.py)
Expand Down Expand Up @@ -866,6 +866,7 @@
* [Covid Stats Via Xpath](https://github.com/TheAlgorithms/Python/blob/master/web_programming/covid_stats_via_xpath.py)
* [Crawl Google Results](https://github.com/TheAlgorithms/Python/blob/master/web_programming/crawl_google_results.py)
* [Crawl Google Scholar Citation](https://github.com/TheAlgorithms/Python/blob/master/web_programming/crawl_google_scholar_citation.py)
* [Currency Converter](https://github.com/TheAlgorithms/Python/blob/master/web_programming/currency_converter.py)
* [Current Stock Price](https://github.com/TheAlgorithms/Python/blob/master/web_programming/current_stock_price.py)
* [Current Weather](https://github.com/TheAlgorithms/Python/blob/master/web_programming/current_weather.py)
* [Daily Horoscope](https://github.com/TheAlgorithms/Python/blob/master/web_programming/daily_horoscope.py)
Expand Down
89 changes: 0 additions & 89 deletions ciphers/base64_cipher.py

This file was deleted.

114 changes: 114 additions & 0 deletions ciphers/base64_encoding.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
# Import the official implementation to check if ours is correct
from base64 import b64encode, b64decode

B64_CHARSET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"


def base64_encode(data: bytes) -> bytes:
"""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
how many "=" sign should be added, the padding.
For every 2 binary digits added, a "=" sign is added in the output.
We can add any binary digits to make it a multiple of 6, for instance, consider the
following example:
"AA" -> 0010100100101001 -> 001010 010010 1001
As can be seen above, 2 more binary digits should be added, so there's 4
possibilities here: 00, 01, 10 or 11.
That being said, Base64 encoding can be used in Steganography to hide data in these
appended digits.

>>> a = b"This pull request is part of Hacktoberfest20!"
>>> b = b"https://tools.ietf.org/html/rfc4648"
>>> c = b"A"
>>> base64_encode(a) == b64encode(a)
True
>>> base64_encode(b) == b64encode(b)
True
>>> base64_encode(c) == b64encode(c)
True
"""
binary_stream = "".join(bin(char)[2:].zfill(8) for char in data)

padding_needed = len(binary_stream) % 6 != 0

if padding_needed:
# The padding that will be added later
padding = b"=" * ((6 - len(binary_stream) % 6) // 2)

# Append binary_stream with arbitrary binary digits (0's by default) to make its
# length a multiple of 6.
binary_stream += "0" * (6 - len(binary_stream) % 6)
else:
padding = b""

# Encode every 6 binary digits to their corresponding Base64 character
return (
"".join(
B64_CHARSET[int(binary_stream[index : index + 6], 2)]
for index in range(0, len(binary_stream), 6)
).encode()
+ padding
)


def base64_decode(encoded_data: str) -> bytes:
"""Decodes data according to RFC4648.

This does the reverse operation of base64_encode.
We first transform the encoded data back to a binary stream, take off the
previously appended binary digits according to the padding, at this point we
would have a binary stream whose length is multiple of 8, the last step is
to convert every 8 bits to a byte.

>>> a = "VGhpcyBwdWxsIHJlcXVlc3QgaXMgcGFydCBvZiBIYWNrdG9iZXJmZXN0MjAh"
>>> b = "aHR0cHM6Ly90b29scy5pZXRmLm9yZy9odG1sL3JmYzQ2NDg="
>>> c = "QQ=="
>>> base64_decode(a) == b64decode(a)
True
>>> base64_decode(b) == b64decode(b)
True
>>> base64_decode(c) == b64decode(c)
True
"""
padding = encoded_data.count("=")

# Check if the encoded string contains non base64 characters
if padding:
assert all(
char in B64_CHARSET for char in encoded_data[:-padding]
), "Invalid base64 character(s) found."
else:
assert all(
char in B64_CHARSET for char in encoded_data
), "Invalid base64 character(s) found."

# Check the padding
assert len(encoded_data) % 4 == 0 and padding < 3, "Incorrect padding."

if padding:
# Remove padding if there is one
encoded_data = encoded_data[:-padding]

binary_stream = "".join(
bin(B64_CHARSET.index(char))[2:].zfill(6) for char in encoded_data
)[: -padding * 2]
else:
binary_stream = "".join(
bin(B64_CHARSET.index(char))[2:].zfill(6) for char in encoded_data
)

data = [
int(binary_stream[index : index + 8], 2)
for index in range(0, len(binary_stream), 8)
]

return bytes(data)


if __name__ == "__main__":
import doctest

doctest.testmod()