def run(cls, _input: Decodable, **kwargs) -> Optional[bytes]: """Decodes Base91 encoded bytes-like object or ASCII string. See http://base91.sourceforge.net/ :param _input: Base91 encoded (bytes) string :param kwargs: :keyword charset: Optional custom alphabet of 91 characters :return: `None` if `_input` couldn't be decoded, else decoded bytes string """ charset = kwargs.get("charset", CHARSET) assert len(charset) == 91 try: if not isinstance(_input, str): _input = str_from_bytes(_input).strip() except: return None if ( re.search( "[^" + charset + "]", _input, ) is not None ): return None if charset != CHARSET: _input = _input.translate(str.maketrans(charset, CHARSET)) try: return convert_to_bytes(base91.decode(_input)) except Exception: return None
def insert_position(sqlite, call, comm, typ): # Decode comment data = base91.decode(comm) (adc_vsol, adc_vbat, pac_vsol, pac_vbat, pac_pbat, pac_psol, light_intensity, gps_lock, gps_sats, gps_ttff, gps_pdop, gps_alt, gps_lat, gps_lon, sen_i1_press, sen_e1_press, sen_e2_press, sen_i1_temp, sen_e1_temp, sen_e2_temp, sen_i1_hum, sen_e1_hum, sen_e2_hum, dummy2, stm32_temp, si4464_temp, reset, _id, gps_time, sys_time, sys_error) = struct.unpack('HHHHhhHBBBBHiiIIIhhhBBBBhhHIIII', data[:72]) # Insert rxtime = int(datetime.now(timezone.utc).timestamp()) sqlite.cursor().execute( """INSERT INTO position (call,rxtime,org,adc_vsol,adc_vbat,pac_vsol,pac_vbat,pac_pbat,pac_psol,light_intensity,gps_lock,gps_sats,gps_ttff,gps_pdop,gps_alt,gps_lat,gps_lon,sen_i1_press,sen_e1_press,sen_e2_press,sen_i1_temp,sen_e1_temp,sen_e2_temp,sen_i1_hum,sen_e1_hum,sen_e2_hum,sys_error,stm32_temp,si4464_temp,reset,id,sys_time,gps_time) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)""", (call, rxtime, typ, adc_vsol, adc_vbat, pac_vsol, pac_vbat, pac_pbat, pac_psol, light_intensity, gps_lock, gps_sats, gps_ttff, gps_pdop, gps_alt, gps_lat, gps_lon, sen_i1_press, sen_e1_press, sen_e2_press, sen_i1_temp, sen_e1_temp, sen_e2_temp, sen_i1_hum, sen_e1_hum, sen_e2_hum, sys_error, stm32_temp, si4464_temp, reset, _id, sys_time, gps_time)) sqlite.commit() # Debug print('Received %s packet packet Call=%s Reset=%d ID=%d' % (typ, call, reset, _id))
def insert_position(db, call, comm, typ): try: # Decode comment data = base91.decode(comm) (adc_vsol, adc_vbat, pac_vsol, pac_vbat, pac_pbat, pac_psol, light_intensity, gps_lock, gps_sats, gps_ttff, gps_pdop, gps_alt, gps_lat, gps_lon, sen_i1_press, sen_e1_press, sen_e2_press, sen_i1_temp, sen_e1_temp, sen_e2_temp, sen_i1_hum, sen_e1_hum, sen_e2_hum, dummy2, stm32_temp, si4464_temp, reset, _id, gps_time, sys_time, sys_error) = struct.unpack( 'HHHHhhHBBBBHiiIIIhhhBBBBhhHIIII', data[:72]) # Insert rxtime = int(datetime.now(timezone.utc).timestamp()) db.cursor().execute( """INSERT INTO `position` (`call`,`rxtime`,`org`,`adc_vsol`,`adc_vbat`,`pac_vsol`,`pac_vbat`,`pac_pbat`,`pac_psol`,`light_intensity`,`gps_lock`, `gps_sats`,`gps_ttff`,`gps_pdop`,`gps_alt`,`gps_lat`,`gps_lon`,`sen_i1_press`,`sen_e1_press`,`sen_e2_press`,`sen_i1_temp`,`sen_e1_temp`, `sen_e2_temp`,`sen_i1_hum`,`sen_e1_hum`,`sen_e2_hum`,`sys_error`,`stm32_temp`,`si4464_temp`,`reset`,`id`,`sys_time`,`gps_time`) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)""", (call, rxtime, typ, adc_vsol, adc_vbat, pac_vsol, pac_vbat, pac_pbat, pac_psol, light_intensity, gps_lock, gps_sats, gps_ttff, gps_pdop, gps_alt, gps_lat, gps_lon, sen_i1_press, sen_e1_press, sen_e2_press, sen_i1_temp, sen_e1_temp, sen_e2_temp, sen_i1_hum, sen_e1_hum, sen_e2_hum, sys_error, stm32_temp, si4464_temp, reset, _id, sys_time, gps_time)) db.commit() # Debug print('Received %s packet packet Call=%s Reset=%d ID=%d' % (typ, call, reset, _id)) except struct.error: print('Received erroneous %s packet Call=%s' % (typ, call))
def base91_decode(cipher, print_info=""): if ("" != print_info): print("--------" + print_info.center(30) + "--------: ", end="") try: return base91.decode(cipher) except: return None
def bguess(encoded): try: print("[+] base91 : ->", base91.decode(encoded), "\n") except: print("[-] base91 : -> Invalid\n") try: print("[+] base85 : ->", base64.b85decode(encoded), "\n") except: print("[-] base85 : -> Invalid\n") try: print("[+] ASCII85 : -> ", base64.a85decode(encoded), "\n") except: print("[-] ASCII85 : -> Invalid\n") try: print("[+] base64 : ->", base64.b64decode(encoded), "\n") except: print("[-] base64 : -> Invalid\n") try: print("[+] base62 : ->", base62.decode(encoded), "\n") except: print("[-] base62 : -> Invalid\n") try: print("[+] base58 : ->", base58.b58decode(encoded), "\n") except: print("[-] base58 : -> \n") try: print("[+] base32 : ->", base64.b32decode(encoded), "\n") except: print("[-] base32 : -> Invalid\n") try: print("[+] base16 : ->", base64.b16decode(encoded), "\n") except: print("[-] base16 : -> Invalid\n")
def decode(self, ctext: T) -> Optional[U]: """ Performs Base91 decoding """ try: return base91.decode(ctext).decode("utf-8") except Exception: return None
def run(s): mm = s.strip().encode("utf8") output = "" try: output += "base16:" + base64.b16decode(mm).decode("utf8") except: output += "base16:失败" try: output += "\r\nbase24:" + pybase24.decode24(mm) except: output += "\r\nbase24:失败,pybase24解密貌似代码有问题" try: output += "\r\nbase32:" + base64.b32decode(mm).decode("utf8") except: output += "\r\nbase32:失败" try: output += "\r\nbase36" + str(base36.dumps(int(mm, 10))) except: output += "\r\nbase36:失败" try: output += "\r\nbase58:" + base58.b58decode(mm).decode("utf8") except: output += "\r\nbase58:失败" try: output += "\r\nbase62:" + base62.decodebytes( mm.decode("utf8")).decode("utf8") except: output += "\r\nbase62:失败" try: output += "\r\nbase64:" + base64.b64decode(mm).decode("utf8") except: output += "\r\nbase64:失败" try: output += "\r\nbase85:" + base64.b85decode(mm).decode("utf8") except: output += "\r\nbase85:失败" try: output += "\r\nbase91:" + base91.decode(mm) except: output += "\r\nbase91:失败" try: output += "\r\nbase92:" + base92.b92decode(mm).decode("utf8") except: output += "\r\nbase92:失败" try: output += "\r\nbase128:" + base128.decode(mm).decode("utf8") except: output += "\r\nbase128:失败" return output
def b91decode(src, table): if len(table) != 91: return 'Table length error' try: dest = base91.decode(src.translate(str.maketrans(table, b91table))) except Exception as e: return e try: dest = dest.decode() except UnicodeDecodeError as identifier: pass return dest
def process_line(self, receiver, line): data = decode(line[6:]) packet_type = line[2] image_id = data[0] packet_id = data[1] * 0x100 + data[2] w = data[3] h = data[4] flags = data[5] mcu_offset = data[6] mcu_index = data[7] * 0x100 + data[8] print("-> got packet %4s %4s %s" % (image_id, packet_id, packet_type)) hash = "%04s%02s" % (image_id, packet_id) if hash not in self.packets: self.packets[hash] = {} if hash not in self.headers: self.headers[hash] = data[0:9] elif data[0:9] != self.headers[hash]: print("header error", data[0:9], self.headers[hash]) if image_id not in self.receivers: self.receivers[image_id] = ['SSDV over APRS'] self.packets[hash][packet_type] = data[9:] if receiver not in self.receivers[image_id]: self.receivers[image_id] += [receiver] keys = "".join(list(self.packets[hash].keys())) if keys == "IJ": packet = self.merge(self.headers[hash], self.packets[hash]['I'], self.packets[hash]['J']) self.upload(packet, self.receivers[image_id]) elif keys == "IK": data = ''.join([ chr(self.packets[hash]['I'][i] ^ self.packets[hash]['K'][i]) for i in range(len(self.packets[hash]['K'])) ]) packet = self.merge(self.headers[hash], self.packets[hash]['I'], data) self.upload(packet, self.receivers[image_id]) elif keys == "KJ": data = ''.join([ chr(self.packets[hash]['J'][i] ^ self.packets[hash]['K'][i]) for i in range(len(self.packets[hash]['K'])) ]) packet = self.merge(self.headers[hash], data, self.packets[hash]['J']) self.upload(packet, self.receivers[image_id]) elif len(keys) == 3: # verify crc pass
def scrypt_hash(password, salt, n, r, p, dklen): # We use the scrypt executable to generate the key in Base-91 format. os_command = [ "scrypt-kdf", password, salt, str(n), str(r), str(p), str(dklen * 8) ] returned_string = subprocess.check_output(os_command).decode() # The returned string consists of the following elements, separated by "-" # key salt logN r p # Key and salt are in base91 format returned_hash = returned_string.split("-")[0] byte_string = base91.decode(returned_hash) return byte_string
def received_data(data): # Parse line and detect data # Position (.*)\>APECAN(.*?):\/([0-9]{6}h)(.{13})(.*?)\|(.*)\| # Image (.*)\>APECAN(.*?):\/([0-9]{6}h)(.{13})I(.*) # Log (.*)\>APECAN(.*?):\/([0-9]{6}h)(.{13})L(.*) all = re.search("(.*)\>APECAN(.*?):\/([0-9]{6}h)(.{13})", data) pos = re.search("(.*)\>APECAN(.*?):\/([0-9]{6}h)(.{13})(.*?)\|(.*)\|", data) dat = re.search("(.*)\>APECAN(.*?):\/([0-9]{6}h)(.{13})(I|J|L)(.*)", data) if all: # Debug print('='*100) print(data) print('-'*100) call = all.group(1).split(' ')[-1] rxer = all.group(2).split(',')[-1] if not len(rxer): rxer = args.call tim = all.group(3) posi = all.group(4) if pos: # Position packet (with comment and telementry) comm = pos.group(5) tel = pos.group(6) position.insert_position(sqlite, call, tim, posi, comm, tel) elif dat: # Data packet typ = dat.group(5) data_b91 = dat.group(6) data = base91.decode(data_b91) # Decode Base91 if typ is 'I' or typ is 'J': # Image packet image.insert_image(sqlite, rxer, call, tim, posi, data, typ, args.server, args.grouping) elif typ is 'L': # Log packet position.insert_log(sqlite, call, data)
def b91dec(data: str) -> bytes: return bytes(base91.decode(data))
def insert_image(db, receiver, call, data_b91): global imageProcessor, imageData, imageDataLcl, w data = base91.decode(data_b91) if len(data) != 174: return # APRS message has invalid type or length (or both) cur = db.cursor() # Decode various meta data imageID = data[0] packetID = (data[1] << 8) | data[2] data = binascii.hexlify(data[3:]).decode("ascii") # Encode callsign (ensure callsign has no more than 6 chars) bcall = call.split('-') # Split callsign and SSID if len(bcall) == 1: # No SSID available, so take the callsign bcall = bcall[0][0:6] elif (len(bcall[0]) < 5): # Callsign has 4 chars, so take it with the SSID bcall = bcall[0] + bcall[1][0:2] elif ( len(bcall[0]) < 6 ): # Callsign has 5 chars, so take it with the last digit of the SSID bcall = bcall[0] + bcall[1][-1] else: bcall = bcall[0][ 0:6] # Callsign has 6 chars, so take the call without SSID data = ('68%08x%02x%04x' % (encode_callsign(bcall), imageID, packetID)) + data data += "%08x" % (binascii.crc32(binascii.unhexlify(data)) & 0xffffffff) timd = int(datetime.now().timestamp()) # Find image ID (or generate new one) _id = None cur.execute( "SELECT `id`,`packetID` FROM `image` WHERE `call` = %s AND `imageID` = %s AND `rxtime`+5*60 >= %s ORDER BY `rxtime` DESC LIMIT 1", (call, imageID, timd)) fetch = cur.fetchall() if len(fetch): _id = fetch[0][0] lastPacketId = fetch[0][1] if _id is None: # Generate ID cur.execute("SELECT `id`+1 FROM `image` ORDER BY `id` DESC LIMIT 1") fetch = cur.fetchall() if len(fetch): _id = fetch[0][0] else: # No entries in the database _id = 0 # Debug print('Received image packet Call=%s ImageID=%d PacketID=%d ServerID=%d' % (call, imageID, packetID, _id)) # Insert into database cur.execute( """ INSERT IGNORE INTO `image` (`call`,`rxtime`,`imageID`,`packetID`,`data`,`id`) VALUES (%s,%s,%s,%s,%s,%s)""", (call, timd, imageID, packetID, data, _id)) if w + 1 < time.time(): db.commit() with lock: imageData = imageDataLcl imageDataLcl = {} w = time.time() allData = '' cur.execute( "SELECT `data` FROM `image` WHERE `id` = %s ORDER BY `packetID`", (_id, )) for data, in cur.fetchall(): allData += '55' + data + (144 * '0') imageDataLcl[_id] = (call, binascii.unhexlify(allData)) if imageProcessor is None: imageProcessor = threading.Thread(target=imgproc) imageProcessor.start()
async def on_reaction_add(reaction, user): # Stop the bot from going when it adds its own reactions if user == dbot.user: return # Just to show in the console which reaction is being sent print(reaction) # If the message that was reacted on was one sent by the bot, guaranteeing it's a game if reaction.message.author == dbot.user: # Game is over and anyone can delete the game board and reactions by reacting the X emoji if reaction.emoji == '🇽' and base91.decode( reaction.message.embeds[0].footer.text).decode( "utf-8") == "Game over!": await delete_game(reaction) else: # decode footer from base91 footer = base91.decode( reaction.message.embeds[0].footer.text).decode("utf-8") output, user2 = string_to_array(footer) # if the user is the same one that started the game if user2 == user.mention: original = output rows = output.shape[0] cols = output.shape[1] output2 = np.zeros(shape=(4, 4)) if reaction.emoji == '🇽': # Game is still going and original user can decide to delete game await delete_game(reaction) await reaction.message.remove_reaction(emoji=reaction, member=user) return # Rotate arrays to all be facing to the left to make actions on them easier elif reaction.emoji == '⬅': output = np.rot90(output, 0) elif reaction.emoji == '➡': output = np.rot90(output, 2) elif reaction.emoji == '⬆': output = np.rot90(output, 1) elif reaction.emoji == '⬇': output = np.rot90(output, 3) else: await reaction.message.remove_reaction(emoji=reaction, member=user) return # Move everything to the left 4 times to be sure to get everything for i in range(0, 3): output2 = np.zeros(shape=(4, 4)) for x in range(0, cols): for y in range(0, rows): if y != 0: if output[x][y - 1] == 0: output2[x][y - 1] = output[x][y] else: output2[x][y] = output[x][y] else: output2[x][y] = output[x][y] output = output2 # Combine adjacent equal tiles output3 = np.zeros(shape=(4, 4)) for x in range(0, cols): for y in range(0, rows): if y != 0: if output2[x][y - 1] == output2[x][y]: output3[x][y - 1] = output2[x][y] * 2 output2[x][y] = 0 else: output3[x][y] = output2[x][y] else: output3[x][y] = output2[x][y] output = output3 # Move over two more times and check if the board has a 2048 in it or if it's completely full found_win = False found_end = True for i in range(0, 1): output3 = np.zeros(shape=(4, 4)) for x in range(0, cols): for y in range(0, rows): if y != 0: if output[x][y - 1] == 0: output3[x][y - 1] = output[x][y] else: output3[x][y] = output[x][y] else: output3[x][y] = output[x][y] if output3[x][y] == 2048: found_win = True if output3[x][y] == 0: found_end = False output = output3 output2 = output3 e = discord.Embed(title="%s's Game!" % user) # Undo the rotations from before if reaction.emoji == '⬅': output2 = np.rot90(output2, 0) if reaction.emoji == '➡': output2 = np.rot90(output2, 2) if reaction.emoji == '⬆': output2 = np.rot90(output2, 3) if reaction.emoji == '⬇': output2 = np.rot90(output2, 1) # If there's a 2048 on the board, the player won! Add the win gif if found_win is True: e = discord.Embed() e.add_field(name="%s got the 2048 tile!" % user, value="You did it!!") e.set_image( url= "https://media1.giphy.com/media/l2SpR4slaePsGG49O/giphy.gif" ) e.set_footer(text=base91.encode(b"Game over!")) await reaction.message.edit(embed=e) for emoji in ['⬆', '⬇', '⬅', '➡']: await reaction.message.remove_reaction( emoji=emoji, member=dbot.user) await reaction.message.add_reaction('🇽') # If the array changed from how it was before and if there are any empty spaces on the board, add a random tile elif np.array_equal(output2, original) is False and found_end is False: if smoother == False: found = False while found is not True: first_2 = randint(0, 3) second_2 = randint(0, 3) if output2[first_2][second_2] == 0: found = True output2[first_2][second_2] = randint(1, 2) * 2 string, string2 = array_to_string(output2, user.mention) print(string) e.add_field(name="Try to get the 2048 tile!", value=string2) e.set_footer(text=base91.encode(bytes(string, 'utf-8'))) await reaction.message.edit(embed=e) # Check if there are valid moves and if not, end the game if check_valid(output2) is False: print("end") # If there are no 0's, check if there are any valid moves. If there aren't, say the game is over. e = discord.Embed() e.add_field( name="%s is unable to make any more moves." % user, value=":cry:") e.set_image( url= "https://media2.giphy.com/media/joNVQCtuecqHK/giphy.gif" ) e.set_footer(text=base91.encode(b"Game over!")) await reaction.message.edit(embed=e) for emoji in ['⬆', '⬇', '⬅', '➡']: await reaction.message.remove_reaction( emoji=emoji, member=dbot.user) await reaction.message.add_reaction('🇽') if smoother == True: found = False while found is not True: first_2 = randint(0, 3) second_2 = randint(0, 3) if output2[first_2][second_2] != 0: None else: found = True output2[first_2][second_2] = randint(1, 2) * 2 string, string2 = array_to_string( output2, user.mention) e = discord.Embed() e.add_field(name="Try to get the 2048 tile!", value=string2) e.set_footer( text=base91.encode(bytes(string, 'utf-8'))) await reaction.message.edit(embed=e) elif check_valid(output2) is False: print("end") # If there are no 0's, check if there are any valid moves. If there aren't, say the game is over. e = discord.Embed() e.add_field(name="%s is unable to make any more moves." % user, value=":cry:") e.set_image( url= "https://media2.giphy.com/media/joNVQCtuecqHK/giphy.gif" ) e.set_footer(text=base91.encode(b"Game over!")) await reaction.message.edit(embed=e) for emoji in ['⬆', '⬇', '⬅', '➡']: await reaction.message.remove_reaction( emoji=emoji, member=dbot.user) await reaction.message.add_reaction('🇽') else: print("else") # They made a valid move, but it didn't change anything, so don't add a new tile string, string2 = array_to_string(output2, user.mention) print(string) e.add_field(name="Try to get the 2048 tile!", value=string2) e.set_footer(text=base91.encode(bytes(string, 'utf-8'))) await reaction.message.edit(embed=e) # Remove reaction await reaction.message.remove_reaction(emoji=reaction, member=user)
import base91 from pyzbar.pyzbar import decode from PIL import Image x_1_image = Image.open("test444.png") result = decode(x_1_image) text = result[0].data print(text) decoded = base91.decode(text) print(decoded)
def base91decode(importx, infilepath, outfilepath, outputformat, raw, exportx): if importx == 'file': f = open(infilepath, 'r') raw = f.read() f.close() elif importx == 'print': raw = raw else: print('\033[1;31m[-]\033[0m Unknown error.') return False out = str(base91.decode(raw)) if outputformat == 'base64': output = base64.b64decode(out) elif outputformat == 'base32': output = base64.b32decode(out) elif outputformat == 'base16': output = base64.b16decode(out) elif outputformat == 'base58': output = base58.b58decode(out) elif outputformat == 'base85': print('\033[1;31m[-]\033[0m Option not available yet') elif outputformat == 'hex': output = out.decode('hex') elif outputformat == 'dec': print('\033[1;31m[-]\033[0m Option not available yet') elif outputformat == 'octal': print('\033[1;31m[-]\033[0m Option not available yet') elif outputformat == 'binary': output = text_from_bits(out) else: print('\033[1;31m[-]\033[0m Unknown error.') return False if exportx == 'file': f = open(outfilepath, 'w') f.write(output) f.close() return True elif exportx == 'print': return output else: print('\033[1;31m[-]\033[0m Unknown error.') return False
def decode(txt): print("[+]input is ", end="") print(txt) print( "==============================================================================" ) #base16 try: base16_decode = base64.b16decode(txt) print("[成功]base16 decode: ", end="") print(base16_decode) print() except Exception as e: print("[失败]base16 decode: ", end="") print(e) #base32 try: base32_decode = base64.b32decode(txt) print("[成功]base32 decode: ", end="") print(base32_decode) print() except Exception as e: print("[失败]base32 decode: ", end="") print(e) #base36 try: base36_decode = base36.loads(txt) print("[成功]base36 decode: ", end="") print(base36_decode) print() except Exception as e: print("[失败]base36 decode: ", end="") print(e) #base58 try: base58_decode = base58.b58decode(txt) print("[成功]base58 decode: ", end="") print(base58_decode) print() except Exception as e: print("[失败]base58 decode: ", end="") print(e) #base62 try: base62_c_string = bytes.decode(txt) base62_decode = base62.decodebytes(base62_c_string) print("[成功]base62 decode: ", end="") print(base62_decode) print() except Exception as e: print("[失败]base62 decode: ", end="") print(e) #base64 try: base64_decode = base64.b64decode(txt) print("[成功]base64 decode: ", end="") print(base64_decode) print() except Exception as e: print("[失败]base64 decode: ", end="") print(e) #base85 try: base85_decode = base64.a85decode(txt).decode() print("[成功]base85 decode: ", end="") print(base85_decode) print() except Exception as e: print("[失败]base85 decode: ", end="") print(e) #base91 try: base91_decode = base91.decode(str(txt, encoding="utf-8")).decode() print("[成功]base91 decode: ", end="") print(base91_decode) print() except Exception as e: print("[失败]base91 decode: ", end="") print(e) #base92 try: base92_decode = py3base92.decode(str(txt, encoding="utf-8")) print("[成功]base92 decode: ", end="") print(base92_decode) print() except Exception as e: print("[-]base92 decode: ", end="") print(e)
def decode_base(self, encoded_base): def contains_replacement_char(res): return True if u'\ufffd' in res else False encoding_type = [] results = [] if len(encoded_base) != 0: try: base16_decode = base64.b16decode(encoded_base, casefold=False).decode( 'utf-8', 'replace') if not contains_replacement_char(base16_decode): encoding_type.append('Base16') results.append(base16_decode) if not self.api_call: print( colored('\n[>] Decoding as Base16: ', 'blue') + colored(base16_decode, 'green')) except: pass try: base32_decode = base64.b32decode(encoded_base, casefold=False, map01=None).decode( 'utf-8', 'replace') if not contains_replacement_char(base32_decode): encoding_type.append('Base32') results.append(base32_decode) if not self.api_call: print( colored('\n[>] Decoding as Base32: ', 'blue') + colored(base32_decode, 'green')) except: pass try: base36_decode = base36.dumps(encoded_base).decode( 'utf-8', 'replace') if not contains_replacement_char(base36_decode): encoding_type.append('Base36') results.append(base36_decode) if not self.api_call: print( colored('\n[>] Decoding as Base36: ', 'blue') + colored(base36_decode, 'green')) except: pass try: base58_decode = base58.b58decode(encoded_base.encode()).decode( 'utf-8', 'replace') if not contains_replacement_char(base58_decode): encoding_type.append('Base58') results.append(base58_decode) if not self.api_call: print( colored('\n[>] Decoding as Base58: ', 'blue') + colored(base58_decode, 'green')) except: pass try: base62_decode = base62.decodebytes(encoded_base).decode( 'utf-8', 'replace') if not contains_replacement_char(base62_decode): encoding_type.append('Base62') results.append(base62_decode) if not self.api_call: print( colored('\n[>] Decoding as Base62: ', 'blue') + colored(base62_decode, 'green')) except: pass try: base64_decode = base64.b64decode(encoded_base).decode( 'utf-8', 'replace') if not contains_replacement_char(base64_decode): encoding_type.append('Base64') results.append(base64_decode) if not self.api_call: print( colored('\n[>] Decoding as Base64: ', 'blue') + colored(base64_decode, 'green')) except: pass try: base64url_decode = base64.urlsafe_b64decode( encoded_base + '=' * (4 - len(encoded_base) % 4)).decode( 'utf-8', 'replace') if not contains_replacement_char(base64url_decode): encoding_type.append('Base64URL') results.append(base64url_decode) if not self.api_call: print( colored('\n[>] Decoding as Base64URL: ', 'blue') + colored(base64url_decode, 'green')) except: pass try: base85_decode = base64.b85decode(encoded_base).decode( 'utf-8', 'replace') if not contains_replacement_char(base85_decode): encoding_type.append('Base85') results.append(base85_decode) if not self.api_call: print( colored('\n[>] Decoding as Base85: ', 'blue') + colored(base85_decode, 'green')) except: pass try: ascii85_decode = base64.a85decode(encoded_base).decode( 'utf-8', 'replace') if not contains_replacement_char(ascii85_decode): encoding_type.append('Ascii85') results.append(ascii85_decode) if not self.api_call: print( colored('\n[>] Decoding as Ascii85: ', 'blue') + colored(ascii85_decode, 'green')) except: pass try: base91_decode = base91.decode(encoded_base).decode( 'utf-8', 'replace') if not contains_replacement_char(base91_decode): encoding_type.append('Base91') results.append(base91_decode) if not self.api_call: print( colored('\n[>] Decoding as Base91: ', 'blue') + colored(base91_decode, 'green')) except: pass try: base92_decode = base92.decode(encoded_base) if not contains_replacement_char(base92_decode): encoding_type.append('Base92') results.append(base92_decode) if not self.api_call: print( colored('\n[>] Decoding as Base92: ', 'blue') + colored(base92_decode, 'green')) except: pass if not results and not self.api_call: quit(colored('\n[!] Not a valid encoding.\n', 'red')) for x in range(len(results)): """ It runs through all the results and compares them with a regex pattern of 'alphabets, numbers, and special characters' thus ending up with the right result as false results will contain invalid characters. """ if re.match('[A-Za-z0-9$&+,:;=?@#|\'<>.^*()%!_-]', results[x]): if not self.api_call: print( colored('\n[-] The Encoding Scheme Is ', 'blue') + colored(encoding_type[x], 'green')) if self.output != None: open(self.output, 'a').write(results[x] + '\n') else: return (results[x], encoding_type[x])
#!/usr/bin/env python # -*- coding:utf-8 -*- #@Time : 2019/12/5 0005 21:22 #@Author : tb_youth #@FileName: base91_demo.py #@SoftWare: PyCharm #@Blog : https://blog.csdn.net/tb_youth import base91 s = '@iH<,{bdR2H;i6*Tm,Wx2izpx2!' print(base91.decode(s).decode('ascii'))
def base_decode(n): m = '' flag = False try: if re.search('[a-e]', n): m = base64.b16decode(n, True) else: m = base64.b16decode(n) except binascii.Error: pass else: flag = True print("base16deocde:", m) return flag #''''''''''''''''''''''''''''''''' try: m = base64.b32decode(n) except binascii.Error: pass else: flag = True print("base32deocde:", m) return flag #''''''''''''''''''''''''''''''''' try: m = base58.b58decode(n) except ValueError: pass else: m = str(m)[2:-1] if '\\x' in m: pass else: flag = True print("base58deocde:", m) mm = str(base91.decode(n)) if '\\x' not in mm: print("maybe base91decode:", mm) return flag #''''''''''''''''''''''''''''''''' try: m = base62.decodebytes(n) except ValueError: pass else: m = str(m) if '\\x' in m: pass else: flag = True print("base62deocde:", m) return flag #''''''''''''''''''''''''''''''''' try: m = base64.b64decode(n) except binascii.Error: pass else: m = str(m) if '\\x' in m: pass else: flag = True print("base64deocde:", m) return flag #''''''''''''''''''''''''''''''''' try: m = base64.b85decode(n) except ValueError: pass else: m = str(m) if '\\x' in m: pass else: print("base_b85deocde:", m) flag = True return flag #''''''''''''''''''''''''''''''''' try: m = base64.a85decode(n) except ValueError: pass else: m = str(m) if '\\x' in m: pass else: print("base_a85deocde:", m) flag = True return flag #''''''''''''''''''''''''''''''''' try: m = base91.decode(n) except ValueError: pass else: m = str(m) if '\\x' in m: pass else: print("base91deocde:", m) flag = True return flag #''''''''''''''''''''''''''''''''' try: m = base92.decode(n) except ValueError: pass else: flag = True print("base92deocde:", m) return flag #''''''''''''''''''''''''''''''''' try: c = base36.loads(n) assert type(c) == int m = base36.dumps(c) except ValueError: pass else: flag = True print("base36deocde:", m) return flag # ''''''''''''''''''''''''''''''''' try: b128 = base128.base128(chars=None, chunksize=7) n_str = bytes(n, encoding="utf8") c = list(b128.encode(n_str)) m = b''.join(b128.decode(c)) except ValueError: pass else: flag = True print("base128deocde:", m) return flag return flag
def decode_base(self): # declaring the encoding type array to store encoding types which haven't caused errors encoding_type = [] # declaring the results array to store results which haven't caused errors results = [] # checking if input is not empty if len(self.encoded_base) > 1: # decoding as base16 try: base16_decode = base64.b16decode(self.encoded_base, casefold=False) encoding_type.append("Base16") results.append(base16_decode) print(colored("\n[>] Decoding as Base16: ", "blue")+colored(str(base16_decode), "green")) except: pass # decoding as base32 try: base32_decode = base64.b32decode(self.encoded_base, casefold=False, map01=None) encoding_type.append("Base32") results.append(base32_decode) print(colored("\n[>] Decoding as Base32: ", "blue")+colored(str(base32_decode), "green")) except: pass # decoding as base36 try: base36_decode = base36.dumps(self.encoded_base) encoding_type.append("Base36") results.append(base36_decode) print(colored("\n[>] Decoding as Base36: ", "blue")+colored(str(base36_decode), "green")) except: pass # decoding as base58 try: base58_decode = base58.b58decode(self.encoded_base) encoding_type.append("Base58") results.append(base58_decode) print(colored("\n[>] Decoding as Base58: ", "blue")+colored(str(base58_decode), "green")) except: pass # decoding as base62 try: base62_decode = base62.encode(int(self.encoded_base)) encoding_type.append("Base62") results.append(base62_decode) print(colored("\n[>] Decoding as Base62: ", "blue")+colored(str(base62_decode), "green")) except: pass # decoding as base64 try: base64_decode = base64.b64decode(self.encoded_base) encoding_type.append("Base64") results.append(base64_decode) print(colored("\n[>] Decoding as Base64: ", "blue")+colored(str(base64_decode), "green")) except: pass # decoding as base64url try: base64url_decode = base64.urlsafe_b64decode(self.encoded_base + '=' * (4 - len(self.encoded_base) % 4)) encoding_type.append("Base64Url") results.append(base64url_decode) print(colored("\n[>] Decoding as Base64Url: ", "blue")+colored(str(base64url_decode), "green")) except: pass # decoding as base85 try: base85_decode = base64.b85decode(self.encoded_base) encoding_type.append("Base85") results.append(base85_decode) print(colored("\n[>] Decoding as Base85: ", "blue")+colored(str(base85_decode), "green")) except: pass # decoding as base91 try: base91_decode = base91.decode(self.encoded_base) encoding_type.append("Base91") results.append(base91_decode) print(colored("\n[>] Decoding as Base91: ", "blue")+colored(str(base91_decode), "green")) except: pass # decoding as base92 try: base92_decode = base92.decode(self.encoded_base) encoding_type.append("Base92") results.append(base92_decode) print(colored("\n[>] Decoding as Base92: ", "blue")+colored(str(base92_decode), "green")) except: pass # algorithm to identify which type of base encoding the input is for x in range(len(results)): # identifying the encoding type with regex pattern matching if re.match("^[A-Za-z0-9_ ]*$", results[x]): # printing the predicted encoding type print(colored("\nThe accurate base encoding type is probably ", "red")+colored(encoding_type[x], "green"))
def B91(s,flg=1): if (flg !=0): return(base91.decode(s)) else: return(base91.encode(bytes(s.encode("utf-8"))))
def received_data(data): global jsons, old_filename, current_filename, send_to_server, buf, imgbuf if str(type(data)) == "<class 'aprs.classes.Frame'>": # APRS-IS call = str(data.source) aprs = data.text[3:] receiver = 'APRS-IS/' + str(data.path.pop()) else: # serial or stdin # Parse line and detect data m = re.search("(.*)\>APECAN(.*):\{\{I(.*)", data) if m: try: call = m.group(1) aprs = m.group(3) receiver = 'bla' except: return # message format incorrect (probably no APRS message or line cut off too short) else: m = re.search("\[(.*)\]\[(.*)\] DATA \> (.*)", data) try: aprs = m.group(3) except: return if args.log is not None: logfile.write(data) # Log data to file data = base91.decode(aprs) # Decode Base91 # Calculate CRC for SSDV server crc = binascii.crc32(data) & 0xffffffff # Create message for SSDV server (and save to array) ssdv = '55' + binascii.hexlify(data) + ('%08x' % crc) + (64 * '0') if len(data) != 219: return # APRS message sampled too short if (data[7] + data[6] * 256) == 0: buf = '' buf += binascii.unhexlify(ssdv) command = ['./ssdv', '-d'] process = Popen(command, stdin=PIPE, stdout=PIPE, stderr=PIPE) process.stdin.write(buf) jpg, dummy = process.communicate() imgbuf = StringIO(jpg) if send_to_server is False: return else: if len(jsons) >= args.grouping: req = urllib2.Request(args.server) req.add_header('Content-Type', 'application/json') json = "{\"type\":\"packets\",\"packets\":[" + ",".join( jsons) + "]}" # Group all SSDV packets into a big JSON jsons = [] try: error = True while error: try: result = urllib2.urlopen(req, "".join( json.split(' '))) # Send packets to server print 'Send to SSDV data server: OK' error = False except urllib2.URLError, error: print 'Send to SSDV data server: failed (connection error :( trying again...)' except urllib2.HTTPError, error: # The server did not like our packets :( print 'Send to SSDV data server: failed (the server did not like our packets :( )' print error.read()
def decode_base(self, encoded_base): """ contains_replacement_char() checks whether the decoded base contains an unknown unicode, ie: invalid character. these are replaced with 'replacement character', which is '�' and 'U+FFFD' in unicode. """ def contains_replacement_char(res): return True if u'\ufffd' in res else False # to store the encoding schemes which haven't caused errors encoding_type = [] # to store the decoded results which haven't caused errors results = [] # checking if input is not empty if len(encoded_base) != 0: # decoding as base16 try: base16_decode = base64.b16decode(encoded_base, casefold=False).decode( 'utf-8', 'replace') if not contains_replacement_char(base16_decode): encoding_type.append('Base16') results.append(base16_decode) if not self.api_call: print( colored('\n[>] Decoding as Base16: ', 'blue') + colored(base16_decode, 'green')) except: pass # decoding as base32 try: base32_decode = base64.b32decode(encoded_base, casefold=False, map01=None).decode( 'utf-8', 'replace') if not contains_replacement_char(base32_decode): encoding_type.append('Base32') results.append(base32_decode) if not self.api_call: print( colored('\n[>] Decoding as Base32: ', 'blue') + colored(base32_decode, 'green')) except: pass # decoding as base36 try: base36_decode = base36.dumps(encoded_base).decode( 'utf-8', 'replace') if not contains_replacement_char(base36_decode): encoding_type.append('Base36') results.append(base36_decode) if not self.api_call: print( colored('\n[>] Decoding as Base36: ', 'blue') + colored(base36_decode, 'green')) except: pass # decoding as base58 try: base58_decode = base58.b58decode(encoded_base.encode()).decode( 'utf-8', 'replace') if not contains_replacement_char(base58_decode): encoding_type.append('Base58') results.append(base58_decode) if not self.api_call: print( colored('\n[>] Decoding as Base58: ', 'blue') + colored(base58_decode, 'green')) except: pass # decoding as base62 try: base62_decode = base62.encode(int(encoded_base)).decode( 'utf-8', 'replace') if not contains_replacement_char(base62_decode): encoding_type.append('Base62') results.append(base62_decode) if not self.api_call: print( colored('\n[>] Decoding as Base62: ', 'blue') + colored(base62_decode, 'green')) except: pass # decoding as base64 try: base64_decode = base64.b64decode(encoded_base).decode( 'utf-8', 'replace') if not contains_replacement_char(base64_decode): encoding_type.append('Base64') results.append(base64_decode) if not self.api_call: print( colored('\n[>] Decoding as Base64: ', 'blue') + colored(base64_decode, 'green')) except: pass # decoding as base64url try: base64url_decode = base64.urlsafe_b64decode( encoded_base + '=' * (4 - len(encoded_base) % 4)).decode( 'utf-8', 'replace') if not contains_replacement_char(base64url_decode): encoding_type.append('Base64URL') results.append(base64url_decode) if not self.api_call: print( colored('\n[>] Decoding as Base64URL: ', 'blue') + colored(base64url_decode, 'green')) except: pass # decoding as base85 try: base85_decode = base64.b85decode(encoded_base).decode( 'utf-8', 'replace') if not contains_replacement_char(base85_decode): encoding_type.append('Base85') results.append(base85_decode) if not self.api_call: print( colored('\n[>] Decoding as Base85: ', 'blue') + colored(base85_decode, 'green')) except: pass # decoding as base91 try: base91_decode = base91.decode(encoded_base).decode( 'utf-8', 'replace') if not contains_replacement_char(base91_decode): encoding_type.append('Base91') results.append(base91_decode) if not self.api_call: print( colored('\n[>] Decoding as Base91: ', 'blue') + colored(base91_decode, 'green')) except: pass # decoding as base92 try: base92_decode = base92.decode(encoded_base).decode( 'utf-8', 'replace') if not contains_replacement_char(base92_decode): encoding_type.append('Base92') results.append(base92_decode) if not self.api_call: print( colored('\n[>] Decoding as Base92: ', 'blue') + colored(base92_decode, 'green')) except: pass if not results and not self.api_call: quit(colored('\n[!] Not a valid encoding.\n', 'red')) # algorithm to identify which type of base encoding the input is for x in range(len(results)): """ It runs through all the results and compares them with a regex pattern of 'alphabets, numbers, and special characters' thus ending up with the right result as false results will contain invalid characters. """ if re.match('[A-Za-z0-9$&+,:;=?@#|\'<>.^*()%!_-]', results[x]): if not self.api_call: # printing the predicted encoding type print( colored('\n[-] The Encoding Scheme Is ', 'blue') + colored(encoding_type[x], 'green')) # generating the wordlist/output file with the decoded bases if self.output != None: open(self.output, 'a').write(results[x] + '\n') else: # return a tuple with the decoded base and encoding scheme if it's an api call return (results[x], encoding_type[x])
def insert_image(sqlite, receiver, call, data_b91): global imageProcessor, imageData, w data = base91.decode(data_b91) if len(data) != 174: return # APRS message has invalid type or length (or both) cur = sqlite.cursor() # Decode various meta data imageID = data[0] packetID = (data[1] << 8) | data[2] data = binascii.hexlify(data[3:]).decode("ascii") # Encode callsign (ensure callsign has no more than 6 chars) bcall = call.split('-') # Split callsign and SSID if len(bcall) == 1: # No SSID available, so take the callsign bcall = bcall[0][0:6] elif (len(bcall[0]) < 5): # Callsign has 4 chars, so take it with the SSID bcall = bcall[0] + bcall[1][0:2] elif ( len(bcall[0]) < 6 ): # Callsign has 5 chars, so take it with the last digit of the SSID bcall = bcall[0] + bcall[1][-1] else: bcall = bcall[0][ 0:6] # Callsign has 6 chars, so take the call without SSID data = ('68%08x%02x%04x' % (encode_callsign(bcall), imageID, packetID)) + data data += "%08x" % (binascii.crc32(binascii.unhexlify(data)) & 0xffffffff) timd = int(datetime.now().timestamp()) # Find image ID (or generate new one) _id = None cur.execute( "SELECT id,packetID FROM image WHERE call = ? AND imageID = ? AND rxtime+15*60 >= ? ORDER BY rxtime DESC LIMIT 1", (call, imageID, timd)) fetch = cur.fetchall() if len(fetch): _id = fetch[0][0] lastPacketId = fetch[0][1] if _id is None or lastPacketId > packetID: # Generate ID cur.execute("SELECT id+1 FROM image ORDER BY id DESC LIMIT 1") fetch = cur.fetchall() if len(fetch): _id = fetch[0][0] else: # No entries in the database _id = 0 # Debug print('Received image packet Call=%s ImageID=%d PacketID=%d ServerID=%d' % (call, imageID, packetID, _id)) # Insert into database cur.execute( """ INSERT OR IGNORE INTO image (call,rxtime,imageID,packetID,data,id) VALUES (?,?,?,?,?,?)""", (call, timd, imageID, packetID, data, _id)) if w + 0.5 < time.time(): sqlite.commit() w = time.time() with lock: cur.execute( "SELECT GROUP_CONCAT('55' || data || '" + (144 * '0') + "', '') FROM image WHERE id = ? GROUP BY id ORDER BY packetID", (_id, )) data = cur.fetchall()[0][0] imageData[_id] = (call, binascii.unhexlify(data)) if imageProcessor is None: imageProcessor = threading.Thread(target=imgproc) imageProcessor.start()
#!/usr/bin/python import base91 b91 = 'x5~Wh("vG"[[#9Bct5vW{oiZR|54uWs%!M3}tZ6y)=}#tDoSe+i9!+NWHH1[!eg@GLRDIo~%u;{(bCEU9H3|+v@AKy^Bm~`LSAv5*&EW{xI"[[)yg_WXCt{oiZR|AzXLs%_lAH@k6y(ggzbsOON/i9!+NWiGA' dec = base91.decode(b91) f = open('log.txt','wb') f.write(dec) f.close() for i in range(16): tim = dec[8*i+0] + 256 * dec[8*i+1] lat = dec[8*i+2] + 256 * dec[8*i+3] lon = dec[8*i+4] + 256 * dec[8*i+5] alt = dec[8*i+6] + 256 * dec[8*i+7] month = tim / 4464 day = (tim-month*4464) / 144 hour = (tim-month*4464-day*144) / 6 minute = tim-month*4464-day*144-hour*6 lat = (float(lat*180)/65535)-90 lon = (float(lon*360)/65535)-180 print '%02d.%02d. %02d:%02d lat=%.3f, lon=%.3f alt=%d' % (day+1,month+1,hour,minute,lat,lon,alt)
def BASE(): cypher_text = '' plain_text = '' #接收post的数据 data = request.get_data() data = data.decode('utf-8') data = json.loads(data) text = data['text'] #输入字符串 typed = data['typed'] #输入base(num),即base的类型 operator = data['operator'] #加密或者解密 # print(text) try: if text and typed and operator: if operator == 'encode': #加密算法 plain_text = text.encode(encoding='utf-8') if typed == 'BASE64': cypher_text = base64.b64encode(plain_text) elif typed == 'BASE32': cypher_text = base64.b32encode(plain_text) elif typed == 'BASE58': cypher_text = base58.b58encode(plain_text) elif typed == 'BASE91': cypher_text = base91.encode(plain_text) # elif num_of_base == '92': # cypher_text = base92.encode(plain_text) elif typed == 'BASE36': cypher_text = base36.loads(plain_text) # elif num_of_base=='16': # cypher_text = hex(plain_text) elif typed == 'BASE62': cypher_text = base62.encodebytes(plain_text) elif typed == 'BASE85': cypher_text = base64.a85encode(plain_text) if type(cypher_text) == bytes: resu = { 'code': 200, 'result': cypher_text.decode('utf-8'), 'length': len(cypher_text.decode('utf-8')) } #如果输出是字节流格式 else: resu = { 'code': 200, 'result': cypher_text, 'length': len(cypher_text) } #如果输出是字符串形式 return json.dumps(resu, ensure_ascii=False) elif operator == 'decode': #解密算法 cypher_text = text if typed == 'BASE64': plain_text = base64.b64decode(cypher_text) elif typed == 'BASE32': plain_text = base64.b32decode(cypher_text) elif typed == 'BASE58': plain_text = base58.b58decode(cypher_text) elif typed == 'BASE91': plain_text = base91.decode(cypher_text) # elif num_of_base == '92': # plain_text = base92.decode(cypher_text) elif typed == 'BASE36': plain_text = base36.dumps(cypher_text) # elif num_of_base=='16': # plain_text = int(cypher_text) elif typed == 'BASE62': plain_text = base62.decodebytes(cypher_text) elif typed == 'BASE85': plain_text = base64.a85decode(cypher_text) if type(plain_text) == bytes: resu = { 'code': 200, 'result': plain_text.decode('utf-8'), 'length': len(plain_text.decode('utf-8')) } # 如果输出是字节流格式 else: resu = { 'code': 200, 'result': plain_text, 'length': len(plain_text) } # 如果输出是字符串形式 #resu = {'code': 200, 'cypher_text':plain_text.decode('utf-8') } return json.dumps(resu, ensure_ascii=False) else: resu = {'code': 10001, 'result': '参数不能为空!'} return json.dumps(resu, ensure_ascii=False) except: resu = {'code': 10000, 'result': '输入字符集错误。'} return json.dumps(resu, ensure_ascii=False)
def base91_d(txt): import base91 return base91.decode(txt.decode('utf8')).decode('utf8')
def base_all(): cypher_text = '' plain_text = '' text = request.values.get('text') #输入字符串 num_of_base = request.values.get('num_of_base') #输入base(num),即base的类型 encode_or_decode = request.values.get('encode_or_decode') #加密或者解密 try: if text and num_of_base and encode_or_decode: if encode_or_decode == 'encode': #加密算法 plain_text = text.encode(encoding='utf-8') if num_of_base == '64': cypher_text = base64.b64encode(plain_text) elif num_of_base == '32': cypher_text = base64.b32encode(plain_text) elif num_of_base == '58': cypher_text = base58.b58encode(plain_text) elif num_of_base == '91': cypher_text = base91.encode(plain_text) # elif num_of_base == '92': # cypher_text = base92.encode(plain_text) elif num_of_base == '36': cypher_text = base36.loads(plain_text) # elif num_of_base=='16': # cypher_text = hex(plain_text) elif num_of_base == '62': cypher_text = base62.encodebytes(plain_text) elif num_of_base == '85': cypher_text = base64.a85encode(plain_text) if type(cypher_text) == bytes: resu = { 'code': 200, 'result': cypher_text.decode('utf-8'), 'length': len(cypher_text.decode('utf-8')) } #如果输出是字节流格式 else: resu = { 'code': 200, 'result': cypher_text, 'length': len(cypher_text) } #如果输出是字符串形式 return json.dumps(resu, ensure_ascii=False) elif encode_or_decode == 'decode': #解密算法 cypher_text = text if num_of_base == '64': plain_text = base64.b64decode(cypher_text) elif num_of_base == '32': plain_text = base64.b32decode(cypher_text) elif num_of_base == '58': plain_text = base58.b58decode(cypher_text) elif num_of_base == '91': plain_text = base91.decode(cypher_text) # elif num_of_base == '92': # plain_text = base92.decode(cypher_text) elif num_of_base == '36': plain_text = base36.dumps(cypher_text) # elif num_of_base=='16': # plain_text = int(cypher_text) elif num_of_base == '62': plain_text = base62.decodebytes(cypher_text) elif num_of_base == '85': plain_text = base64.a85decode(cypher_text) if type(plain_text) == bytes: resu = { 'code': 200, 'result': plain_text.decode('utf-8'), 'length': len(plain_text.decode('utf-8')) } # 如果输出是字节流格式 else: resu = { 'code': 200, 'result': plain_text, 'length': len(plain_text) } # 如果输出是字符串形式 #resu = {'code': 200, 'cypher_text':plain_text.decode('utf-8') } return json.dumps(resu, ensure_ascii=False) else: resu = {'code': 10001, 'message': '参数不能为空!'} return json.dumps(resu, ensure_ascii=False) except: resu = {'code': 10000, 'message': '输入字符集错误。'} return json.dumps(resu, ensure_ascii=False)
def main(): usage = "[*] Usage: %prog <-e|-d> <-c|--Caesar> <-m|--method Method> -t TEXT " parser = OptionParser(version="1.0.0", usage=usage) # base16 parser.add_option("-m", "--method", dest="method", action="store", metavar="METHOD", help="which method") parser.add_option("-e", "--encrypt", dest="deal", action="store_true", default="True", help="encrypt") parser.add_option("-d", "--decrypt", dest="deal", action="store_false", help="decrypt") parser.add_option("-t", "--text", dest="text", type="string", metavar="Text", help="input text") parser.add_option("-c", "--Caesar", dest="caesar", action="store_true", help="Caesar Cipher") (options, args) = parser.parse_args() if options.caesar == True: print("[*] Finish!!") print() for cnt in range(26): print("[*] " + caesar(options.text, cnt)) sys.exit() # encrypt if options.deal == True: if options.method in ["b16", "base16"]: print("[*] Finish!!") print() print("[*] " + base64.b16encode(options.text.encode('utf-8'))) sys.exit() elif options.method in ["b32", "base32"]: print("[*] Finish!!") print() print("[*] " + base64.b32encode(options.text.encode("utf-8"))) sys.exit() elif options.method in ["b64", "base64"]: print("[*] Finish!!") print() print("[*] " + base64.b64encode(options.text.encode("utf-8"))) sys.exit() elif options.method in ["b85a", "base85a"]: print("[*] Finish!!") print() print("[*] " + base64.a85encode(options.text.encode("utf-8"))) sys.exit() elif options.method in ["b85b", "base85b"]: print("[*] Finish!!") print() print("[*] " + base64.b85encode(options.text.encode("utf-8"))) sys.exit() elif options.method in ["b91", "base91"]: print("[*] Finish!!") print() print("[*] " + base91.encode(options.text.encode("utf-8"))) sys.exit() elif options.method in ["b92", "base92"]: print("[*] Finish!!") print() print("[*] " + base92.encode(options.text.encode("utf-8"))) sys.exit() elif options.method in ["b36", "base36"]: print("[*] Finish!!") print() print("[*] " + base36.loads(options.text)) sys.exit() elif options.method in ["b58", "base58"]: print("[*] Finish!!") print() print("[*] " + base58.b58encode(options.text)) sys.exit() elif options.method in ["b62", "base62"]: print("[*] Finish!!") print() print("[*] " + base62.encode(int(options.text))) sys.exit() else: if options.method in ["b16", "base16"]: print("[*] Finish!!") print() print("[*] " + base64.b16decode(options.text.encode("utf-8"))) sys.exit() elif options.method in ["b32", "base32"]: print("[*] Finish!!") print() print() print("[*] " + base64.b32decode(options.text.encode("utf-8"))) sys.exit() elif options.method in ["b64", "base64"]: print("[*] Finish!!") print() print("[*] " + base64.b64decode(options.text.encode("utf-8"))) sys.exit() elif options.method in ["b85a", "base85a"]: print("[*] Finish!!") print() print("[*] " + base64.a85decode(options.text.encode("utf-8"))) sys.exit() elif options.method in ["b85b", "base85b"]: print("[*] Finish!!") print() print("[*] " + base64.b85decode(options.text.encode("utf-8"))) sys.exit() elif options.method in ["b91", "base91"]: print("[*] Finish!!") print() print("[*] " + base91.decode(options.text)) sys.exit() elif options.method in ["b92", "base92"]: print("[*] Finish!!") print() print("[*] " + base92.decode(options.text.encode("utf-8"))) sys.exit() elif options.method in ["b36", "base36"]: print("[*] Finish!!") print() print("[*] " + base36.dumps(int(options.text))) sys.exit() elif options.method in ["b58", "base58"]: print("[*] Finish!!") print() print("[*] " + base58.b58decode(options.text)) sys.exit() elif options.method in ["b62", "base62"]: print("[*] Finish!!") print() print("[*] " + base62.decode(options.text)) sys.exit()