Created
June 14, 2017 07:38
-
-
Save dongho-jung/f22bb89d53eabee0e8f50ad21fc73664 to your computer and use it in GitHub Desktop.
Base64 encode / decode own implmentation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from struct import * | |
base64table = """ | |
ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/ | |
"""[2:-2] | |
def base64encode(string, charset='utf-8'): | |
binariedString = ''.join(map(lambda x: bin(x)[2:].rjust(8,'0'),bytearray(string, charset))) | |
binariedString = binariedString + (6 - len(binariedString) % 6) * '0' | |
sixBits = [] | |
for i in range(0, len(binariedString), 6): | |
sixBits += [binariedString[i:i+6]] | |
encodedString = ''.join(map(lambda x: base64table[int(x,2)], sixBits)) | |
return encodedString | |
def base64decode(string, charset='utf-8'): | |
binariedString = string.rstrip('=') | |
binariedString = ''.join(map(lambda x: bin(base64table.find(x))[2:].rjust(6,'0'), binariedString)) | |
eightBits = [] | |
for i in range(0, len(binariedString), 8): | |
eightBits += [int(binariedString[i:i+8],2)] | |
decodedString = pack(len(eightBits)*'B',*eightBits).decode(charset) | |
return decodedString | |
if __name__ == "__main__": | |
print("base64encode TEST START...\n") | |
print(base64encode('안녕하세요 This is a test message ★')) | |
print(base64encode('the test')) | |
print(base64encode('이건 테스트 message 입니다. 東西南北 ◎【ⓙ€')) | |
print("\nbase64encode TEST END...\n\n\n") | |
print("base64decode TEST START...\n") | |
print(base64decode('dGhlIHRlc3Q==')) | |
print(base64decode(base64encode('안녕하세요 This is a test message ★'))) | |
print(base64decode('7J206rG0IO2FjOyKpO2KuCBtZXNzYWdlIOyeheuLiOuLpC4g5p2x6KW/5Y2X5YyXIOKXjuOAkOKTmeKCrA')) | |
print("\nbase64decode TEST END...") | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment