Python/ciphers/base64_cipher.py

90 lines
2.4 KiB
Python
Raw Normal View History

def encode_base64(text):
r"""
>>> encode_base64('WELCOME to base64 encoding 😁')
'V0VMQ09NRSB0byBiYXNlNjQgZW5jb2Rpbmcg8J+YgQ=='
>>> encode_base64('AÅᐃ𐀏🤓')
'QcOF4ZCD8JCAj/CfpJM='
>>> encode_base64('A'*60)
'QUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFB\r\nQUFB'
"""
base64_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
byte_text = bytes(text, "utf-8") # put text in bytes for unicode support
2019-10-05 05:14:13 +00:00
r = "" # the result
c = -len(byte_text) % 3 # the length of padding
2019-10-05 05:14:13 +00:00
p = "=" * c # the padding
s = byte_text + b"\x00" * c # the text to encode
2019-10-05 05:14:13 +00:00
i = 0
while i < len(s):
if i > 0 and ((i / 3 * 4) % 76) == 0:
r = r + "\r\n" # for unix newline, put "\n"
2019-10-05 05:14:13 +00:00
n = (s[i] << 16) + (s[i + 1] << 8) + s[i + 2]
2019-10-05 05:14:13 +00:00
n1 = (n >> 18) & 63
n2 = (n >> 12) & 63
2019-10-05 05:14:13 +00:00
n3 = (n >> 6) & 63
n4 = n & 63
2019-10-05 05:14:13 +00:00
r += base64_chars[n1] + base64_chars[n2] + base64_chars[n3] + base64_chars[n4]
i += 3
2019-10-05 05:14:13 +00:00
return r[0 : len(r) - len(p)] + p
def decode_base64(text):
r"""
>>> decode_base64('V0VMQ09NRSB0byBiYXNlNjQgZW5jb2Rpbmcg8J+YgQ==')
'WELCOME to base64 encoding 😁'
>>> decode_base64('QcOF4ZCD8JCAj/CfpJM=')
'AÅᐃ𐀏🤓'
>>> decode_base64("QUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUF"
... "BQUFBQUFBQUFB\r\nQUFB")
'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA'
"""
base64_chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
s = ""
2019-10-05 05:14:13 +00:00
for i in text:
if i in base64_chars:
s += i
c = ""
else:
2019-10-05 05:14:13 +00:00
if i == "=":
c += "="
p = ""
if c == "=":
2019-10-05 05:14:13 +00:00
p = "A"
else:
if c == "==":
p = "AA"
2019-10-05 05:14:13 +00:00
r = b""
s = s + p
2019-10-05 05:14:13 +00:00
i = 0
while i < len(s):
2019-10-05 05:14:13 +00:00
n = (
(base64_chars.index(s[i]) << 18)
+ (base64_chars.index(s[i + 1]) << 12)
+ (base64_chars.index(s[i + 2]) << 6)
+ base64_chars.index(s[i + 3])
2019-10-05 05:14:13 +00:00
)
r += bytes([(n >> 16) & 255]) + bytes([(n >> 8) & 255]) + bytes([n & 255])
2019-10-05 05:14:13 +00:00
i += 4
2019-10-05 05:14:13 +00:00
return str(r[0 : len(r) - len(p)], "utf-8")
2019-10-05 05:14:13 +00:00
2018-10-28 21:36:51 +00:00
def main():
print(encode_base64("WELCOME to base64 encoding 😁"))
print(decode_base64(encode_base64("WELCOME to base64 encoding 😁")))
2018-10-28 21:36:51 +00:00
2019-10-05 05:14:13 +00:00
if __name__ == "__main__":
2018-10-28 21:36:51 +00:00
main()