Python itself has base64 encryption module, but written in C, encapsulated as. So file, unable to view the source code, in the spirit of learning, the implementation of their own, the algorithm
Principle reference on BASE64 coding algorithm.
The code is as follows:
#Coding:utf8ImportstringImportBase64#encode a 64-bit array because it's converted to 6-byte characters, so 64 bits is enough.Letters = List (string.letters) + list (string.digits) + ['+','/']defmy_base64_encodestring (INPUT_STR):#take an ASCII or Unicode value for each byte, and then convert to 2 binaryStr_ascii_list = ['{: 0>8}'. Format (str (ord (i))). Replace ('0b',"')) forIinchInput_str] Output_str="' #The number of times required to do an integer multiple of 3 not enoughEqual_num =0 whilestr_ascii_list:temp_list= Str_ascii_list[:3] ifLen (temp_list)! = 3: whileLen (temp_list) < 3: Equal_num+ = 1temp_list+= ['0'*8] Temp_str="'. Join (temp_list)#three 8-byte binary conversions to 4 6-byte binaryTemp_str_list = [Temp_str[x:x+6] forXinch[0, 6, 12, 18]] #Binary into 10 binarytemp_str_list = [Int (x, 2) forXinchTemp_str_list]#determine if the character to be filled is handled accordingly ifequal_num:temp_str_list= temp_str_list[0:4-Equal_num] Output_str+="'. Join ([letters[x] forXinchTemp_str_list]) Str_ascii_list= Str_ascii_list[3:] Output_str= Output_str +'='*Equal_num#print (OUTPUT_STR) returnOutput_strdefmy_base64_decodestring (INPUT_STR):#Index each byte, then convert to 2 binaryStr_ascii_list = ['{: 0>6}'. Format (str (Letters.index (i)). Replace ('0b',"')) forIinchInput_strifI! ='='] Output_str="'Equal_num= Input_str.count ('=') whilestr_ascii_list:temp_list= Str_ascii_list[:4] Temp_str="'. Join (temp_list)#8-bit enough ifLen (TEMP_STR)% 8! =0:temp_str= Temp_str[0:-1*equal_num*2] #4 6-byte binary conversions to three 8-byte binaryTemp_str_list = [Temp_str[x:x+8] forXinch[0, 8, 16]] #Binary into 10 binarytemp_str_list = [Int (x, 2) forXinchTemp_str_listifx] Output_str+="'. Join ([Chr (x) forXinchTemp_str_list]) Str_ascii_list= Str_ascii_list[4:] #print (OUTPUT_STR) returnOutput_strif __name__=="__main__": Input_str='11 I'Input_str='mthmije=' #my_base64_encodestring (INPUT_STR)my_base64_decodestring (INPUT_STR)Pass
Please correct me if there is any omission.
Python implements Base64 algorithm encryption