def wait(watch_mode, target_id, reddit): subreddit = reddit.subreddit('all') rootLogger.info('Entering wait mode...') target_id_decoded = base36.loads(target_id) if not watch_mode else None min_distance = 270 if has_libs: ids, times = np.array([]), np.array([]) to_predict = np.array(target_id_decoded).reshape(1, -1) else: ids, times, to_predict = [None] * 3 # fix assignment warning while True: max_id, time_id = None, None while not max_id: max_id = max([base36.loads(s.id) for s in subreddit.new(limit=2)], default=0) time_id = time.time() if watch_mode: rootLogger.info('Last ID: {lastid}'.format( lastid=base36.dumps(max_id), )) hint = max_id + 1500 rootLogger.info('Try to capture {}'.format(base36.dumps(hint))) quit(0) if has_libs: ids = np.append(ids, max_id) times = np.append(times, time_id) # rootLogger.info('id {di} found'.format(di=base36.dumps(max_id))) if has_libs and len(ids) > 1: X, y = ids.reshape(-1, 1), times.reshape(-1, 1) reg = LinearRegression().fit(X, y) pred = reg.predict(to_predict) # ndarray pred = datetime.datetime.fromtimestamp(pred[0][0]) # datetime elif has_libs: pred = 'Cannot calculate (need two or more ids)' else: pred = 'Cannot calculate (need missing libraries)' distance = target_id_decoded - max_id rootLogger.info( 'Last ID: {lastid} - Distance: {d} - ETA: {eta}'.format( lastid=base36.dumps(max_id), d=distance, eta=pred)) if distance <= 0: rootLogger.info('ID "{}" passed.'.format(target_id)) quit(1) elif distance <= min_distance: rootLogger.info('Exiting wait mode...') return else: tts = round(min(10, distance / 200), 2) rootLogger.info('Sleep for {} seconds...'.format(tts)) time.sleep(tts)
def on_message(self, ws, message): message = json.loads(message) for m in message: try: if base36.loads(m["id"]) > self.id: self.id = base36.loads(m["id"]) except: log.warning("Funky ID (non-base36) on message {}".format( json.dumps(m, indent=4))) if "data" in m and m["data"]["type"] == "ping": self.send_ping(ws, m["channel"]) elif m["channel"] == "/meta/connect" and m["successful"]: time.sleep(m["advice"]["interval"]) # always zero so whatever self.send_connect(ws) elif "data" in m and m["data"]["type"] == "line.create": d = m["data"]["subject"] server = get_server_from_groupme_group_id(d["group_id"]) if server == -1: log.debug("Groupme discarding message to unknown group {}". format(d["group_id"])) return if d["sender_id"] != "system" and int( d["sender_id"]) == groupme_user_id: log.debug("Groupme discarding self message") return coro = RecvMessage(d) future = asyncio.run_coroutine_threadsafe(coro, client_loop) future.result() elif "data" in m and m["data"]["type"] == "like.create": # these appear to be duplicated with the "favorite" messages pass elif "data" in m and m["data"]["type"] == "favorite": d = m["data"]["subject"]["line"] log.debug("Got favorite call") server = get_server_from_groupme_group_id(d["group_id"]) coro = update_discord_likes_from_groupme( server, d["favorited_by"], int(d["id"]), d["source_guid"]) future = asyncio.run_coroutine_threadsafe(coro, client_loop) future.result() elif "data" not in m and m.get( "successful", False) and m["channel"] == "/user/{}".format( groupme_user_id): # probably a ping response pass elif "data" not in m and m.get( "successful", False) and m["channel"] == "/meta/subscribe": # subscription success log.info("Subscription success to {}".format( m["subscription"])) else: log.warning("Groupme got unhandled message: {}".format( json.dumps(message, indent=4)))
def get_post_id(idstr): num_id = None pid_parts = idstr.split('_') if len(pid_parts) == 1: #print(idstr) num_id = base36.loads(pid_parts[0]) elif len(pid_parts) == 2: # print(pid_parts[1]) num_id = base36.loads(pid_parts[1]) else: print('Error: The parent ID \'' + idstr + '\' is not valid.') sys.exit(1) return num_id
def run(s): mm = s.encode("utf8") output = "" output += "base16:" + base64.b16encode(mm).decode("utf8") try: output += "\r\nbase24:" + pybase24.encode24(mm) except: output += "\r\nbase24:失败" output += "\r\nbase32:" + base64.b32encode(mm).decode("utf8") try: output += "\r\nbase36:" + str(base36.loads(mm)) except: output += "\r\nbase36:失败" output += "\r\nbase58:" + base58.b58encode(mm).decode("utf8") output += "\r\nbase62:" + base62.encodebytes(mm) output += "\r\nbase64:" + base64.b64encode(mm).decode("utf8") output += "\r\nbase85:" + base64.b85encode(mm).decode("utf8") output += "\r\nbase91:" + base91.encode(mm) try: output += "\r\nbase92:" + base92.b92encode(mm).decode("utf8") except: output += "\r\nbase92:失败" try: output += "\r\nbase128:" + base128.encode(mm).decode("utf8") except: output += "\r\nbase128:失败" return output
def loop(self): '''Request the newest Posts from a subreddit and post them to a Discord server Using webhook. Remembers ID of last post and will not post a submission twice. Will not post anything on the first run.''' sub = self.reddit.subreddit(self.subreddit) posts = list(sub.new(limit=self.fetch_size))[::-1] if self.last_id == -1: print("initial loop or unusable buffer yo") self.last_id = base36.loads(posts[-1].id) return for post in posts: if base36.loads(post.id) > self.last_id: self.hook(post.url) print(f't3_{post.id}: {post.url}') self.last_id = base36.loads(posts[-1].id)
def __init__(self, target_id, payload): super().__init__() self.username = payload.username self.subreddit = payload.subreddit self.client = payload.client assert any([self.username, self.subreddit]), 'No username nor subreddit provided!' # preferenza per subreddit se fornito self.where_to_post = self.subreddit or 'u_{}'.format(self.username) self.target_id = target_id self.target_id_decoded = base36.loads(target_id)
def fetch(self, messages, uid): res = [] next = uid and messages.getnext(0) for index, id in self._seqMessageSetToSeqDict(messages, uid).items(): message = service.users().messages().get(userId='me', id=id, format='raw').execute() msg_str = base64.urlsafe_b64decode( message['raw'].encode('ASCII')).decode() res.append((index, MaildirMessage(base36.loads(id), msg_str, []))) return res
def set_all_object(self, name, obj, dosync=True): """ Set a generic object in storage """ if self.objtype not in self.storage: self.storage[self.objtype] = {} self.storchild[name] = base36.loads(obj.id) # Check if we should sync the data if dosync: self.storage.sync()
def run(self): global id_taken rootLogger.info('{} started'.format(self.name)) sub = self.client.subreddit(self.where_to_post) title = self.target_id.upper() while True: try: post = sub.submit(title=title, selftext='This is not the one') except Exception as e: rootLogger.error( '{}, while submitting, terminated for an exception: {}'. format(self.name, e)) return distance = self.target_id_decoded - base36.loads(post.id) rootLogger.info('Distance: {d}, posted ID: {i}'.format(d=distance, i=post.id)) if distance > 0: try: post.delete() except Exception as e: rootLogger.error( '{}, while deleting > 0, terminated for an exception: {}' .format(self.name, e)) return else: continue elif distance == 0: rootLogger.info('Congrats! You won your ID "{}"'.format( self.target_id)) id_taken = True # è thread_safe grazie all'unicità degli ID try: post.edit('You did it! You did it!'.upper()) except Exception as e: rootLogger.error( '{}, while editing == 0, terminated for an exception: {}' .format(self.name, e)) finally: return elif distance < 0: rootLogger.info('ID "{}" passed'.format(self.target_id)) try: post.delete() except Exception as e: rootLogger.error( '{}, while deleting < 0, terminated for an exception: {}' .format(self.name, e)) finally: return
def public(request, promid): # convert id to integers promid = base36.loads(promid) # GET promise detail based on promid passed in URL cursor = connection.cursor() query = ''' SELECT promorid_id, au1.email promoremail, promorapprdate, promeeid_id, au2.email promeeemail, promeeapprdate, privacy, status, details, cdate, mdate FROM promise p JOIN auth_user au1 ON p.promorid_id = au1.id JOIN auth_user au2 ON p.promeeid_id = au2.id WHERE p.privacy = 'public' AND p.promid = %s''' cursor.execute(query, [promid]) row = cursor.fetchone() if row: (promorid, promoremail, promorapprdate, promeeid, promeeemail, promeeapprdate, privacy, status, details, cdate, mdate) = row else: return redirect('/404/error/') params = { 'status': status, 'details': details, 'privacy': privacy, 'current': timezone.now(), 'cdate': cdate, 'mdate': mdate, #'promid': promid, } template = 'public.html' return render(request, template, params)
def populate_all_posts_and_comments(self): """ Backpopulate all posts and comments """ reddit_api = get_admin_api().reddit # fetch and base36 decode the latest post id newest_post_id = base36.loads(next(reddit_api.front.new()).id) # create a celery chord by batching a backpopulate and merging results results = (celery.group( populate_posts_and_comments.si(post_ids) for post_ids in chunks( range(newest_post_id + 1), chunk_size=settings.ELASTICSEARCH_INDEXING_CHUNK_SIZE, )) | populate_posts_and_comments_merge_results.s()) raise self.replace(results)
def process_reddit_post(post): is_self = post.get("is_self") if is_self is None or is_self: return None url = post.get("url") if url is None or url == "": return None reddit_submission = RedditSubmission() reddit_submission.id = base36.loads(post["id"]) reddit_submission.subreddit = post.get("subreddit") reddit_submission.title = post.get("title") reddit_submission.score = post.get("score") reddit_submission.created_utc = datetime.datetime.fromtimestamp( int(post["created_utc"])) reddit_submission.url = url return reddit_submission
def Base36(mode, data): if mode == 0: print("[Info]Encryption is in progress......") try: data_result = base36.dumps(int(data)) return "[Success]Your cipher_text is:" + data_result except: print( "[Fail]Encryption failed! Please check the information you gave!" ) elif mode == 1: print("[Info]Decryption is in progress......") try: data_result = str(base36.loads(data)) return "[Success]Your plain_text is:" + data_result except: print( "[Fail]Decryption failed! Please check the information you gave!" ) else: print("[ERROR]Invalid Mode!(encode->0/decode->1)")
def handle(self, *args, **options): """Populate posts and comments from reddit""" if options["post"]: task = tasks.populate_posts_and_comments.delay( [base36.loads(post_id) for post_id in options["post"]] ) else: task = tasks.populate_all_posts_and_comments.delay() self.stdout.write( "Started celery task {task} to backpopulate posts and comments".format( task=task ) ) self.stdout.write("Waiting on task...") results = task.get() # Results will look like this: # results = { # 'posts': 1734, # 'comments': 3547, # "failures": [ # {"thing_type": "comment", "thing_id": "c4", "reason": "errors happen"}, # {"thing_type": "post", "thing_id": "b9i", "reason": "more than you want them to"} # ] # } self.stdout.write("Successes:") self.stdout.write(f"Posts: {results['posts']}") self.stdout.write(f"Comments: {results['comments']}") failures = results["failures"] if failures: self.stdout.write("") self.stdout.write("Failures:") self.stdout.write("thing_type thing_id reason") for failure in results["failures"]: self.stdout.write( f"{failure['thing_type']:<12} {failure['thing_id']:<10} {failure['reason']}" ) sys.exit(1)
def Base36(_mode=mode, _data=data): return base36.dumps(int(_data)) if mode == 0 else str( base36.loads(_data))
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)
type=str, help= 'The ID you want to capture. If not specified, will start in watch mode' ) parser.add_argument( '-c', '--config', type=str, help= 'JSON configuration file with your credentials. Defaults to config.json', default='config.json') parser.add_argument('-w', '--watch', action='store_true', help='Force watch mode instead of grabbing') args = parser.parse_args() _watch_mode = bool(args.watch) or not bool(args.post_id) post_id = None if not _watch_mode: post_id = args.post_id.lower() assert len( post_id) == 6, 'Wrong ID format, must specify 6 base36 chars' _ = base36.loads(post_id) # assert valid base36 format config_fp = pathlib.Path(str(args.config)) assert config_fp.exists(), 'Cannot find {}'.format(config_fp) rootLogger.info('"{}" set for configuration...'.format(args.config)) main(_watch_mode, config_fp, target_id=post_id)
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()
def from_base36(b36_id): un_base36 = base36.loads(b36_id) return Status.query.filter(Status.id == un_base36).one_or_None()
def manage(request, promid, emailEncrypt): emailDecrypted = Encryption.decrypt(emailEncrypt) currentUrl = request.path promIdB36 = promid # convert ids to integers promid = base36.loads(promid) #assert False, promid # VERIFY emailDecrypted passed in URL cursor = connection.cursor() query = ''' SELECT promorid_id, au1.email promoremail, promorapprdate, promeeid_id, au2.email promeeemail, promeeapprdate, privacy, status, details, cdate, mdate FROM promise p JOIN auth_user au1 ON p.promorid_id = au1.id JOIN auth_user au2 ON p.promeeid_id = au2.id WHERE p.promid = %s''' cursor.execute(query, [promid]) row = cursor.fetchone() if row: (promorid, promoremail, promorapprdate, promeeid, promeeemail, promeeapprdate, privacy, status, details, cdate, mdate) = row else: return redirect('/404/error/') # Who is this? the promisor, or promisee? if emailDecrypted == promoremail: who = 'promisor' other = 'promisee' otherEmail = promeeemail otherId = promeeid elif emailDecrypted == promeeemail: who = 'promisee' other = 'promisor' otherEmail = promoremail otherId = promorid else: return redirect('/404/error/') # if form was submitted, alter database and redirect back here if request.POST: do = request.POST['do'].lower() # do = 'approve' # do = 'deny' # do = 'fulfilled' # do = 'broken' if do == 'deny': # mark promise for DELETION current = timezone.now() promise.objects.filter(promid=promid).update(mdate=current, status='delete') elif who == 'promisor' and do == 'approve' and promorapprdate == None: if promeeapprdate: status = 'pending' else: status = 'draft' # redundant, but keep it for clarity #set database promorapprdate to now #update mdate too #promorapprdate to now current = timezone.now() promise.objects.filter(promid=promid).update( promorapprdate=current, mdate=current, status=status) promorapprdate = current elif who == 'promisee' and do == 'approve' and promeeapprdate == None: if promorapprdate: status = 'pending' else: status = 'draft' # redundant, but keep it for clarity #if promorapprdate change status #set database promeeapprdate to now #promeeapprdate to now current = timezone.now() promise.objects.filter(promid=promid).update( promeeapprdate=current, mdate=current, status=status) promeeapprdate = current elif who == 'promisee' and status == 'pending' and (do == 'broken' or do == 'fulfilled'): status = do current = timezone.now() promise.objects.filter(promid=promid).update(mdate=current, status=status) mdate = current # ###################################################################### # if promise changed to active or complete, notify other party # ###################################################################### if status in ['pending', 'broken', 'fulfilled']: host = request.get_host() otherEmailEncrypt = Encryption.encrypt(otherEmail) otherUrl = host + '/' + promIdB36 + '/' + otherEmailEncrypt # if status changed to active/pending, send notification email to other if status == 'pending': EmailActive.sendEmail(otherEmail, emailDecrypted, otherUrl, other) # if promisee just activated the promise, send them a Reference email so they can come back later if who == 'promisee': currentHostUrl = host + currentUrl EmailActive.sendEmail(emailDecrypted, otherEmail, currentHostUrl, 'promiseeReference') else: # If status marked complete, send notification email to other/promisor EmailComplete.sendEmail(otherEmail, emailDecrypted, otherUrl, status) # redirect to current url so refresh won't ask to post again return redirect(currentUrl) # endif request.POST: title = 'Manage promise' message = '' #mdate = mdate.isoformat() buttontype = None if status == 'delete': # DELETE promise from database promise.objects.filter(promid=promid).delete() message += 'Promise does not exist anymore.' elif who == 'promisor': if status == 'draft' and promorapprdate is None: message += ('Promise not active. Click to approve this promise.\n' 'You can also delete this promise.') # button for promisor to approve buttontype = 'approve' elif status == 'draft' and promeeapprdate is None: message += ( 'Promise not active. Promisee has not yet approved. We will notify you ' 'when the promisee has approved.') # refresh button buttontype = 'refresh' elif status == 'pending': message += ('Promise is active and pending. Awaiting promisee to ' 'make decision.') # refresh button buttontype = 'refresh' elif status == 'broken' or status == 'fulfilled': message += ('This promise was marked as "' + status.capitalize() + '" ' + onOrAt(mdate) + ' <span data-utc="' + mdate.isoformat() + '" class="localtime"></span>.') elif who == 'promisee': if status == 'draft' and promeeapprdate is None: message += ('Promise not active. Click to approve this promise.\n' 'You can also delete this promise.') # button for promisee to approve buttontype = 'approve' elif status == 'draft' and promorapprdate is None: message += ( 'Promise not active. Promisor has not yet approved. We will notify you ' 'when the promisor has approved.') # refresh button buttontype = 'refresh' elif status == 'pending': # BUTTONS for Promise broken, or Promise fulfilled buttontype = 'complete' # if promisee just Approved the promise, tell them we sent them an email, else don't tell them difference = datetime.datetime.now(pytz.utc) - promeeapprdate if difference.seconds <= 20: message += ( 'Promise is now active! We just sent you an email. When the promisor has kept (or broken) ' 'this promise, click on the link in the email to come back here.' ) else: message += ( 'Promise is not yet complete. Click "Fulfilled" or "Broken" whenever you are ready.' ) elif status == 'broken' or status == 'fulfilled': #mdate = "2008-09-15T15:53:00+01:00" message = ('You marked this promise as "' + status.capitalize() + '" ' + onOrAt(mdate) + ' <span data-utc="' + mdate.isoformat() + '" class="localtime"></span>.') #assert False, message params = { 'promid': promid, 'status': status.capitalize(), 'details': details, 'cdate': cdate, 'title': title, 'message': message, 'buttontype': buttontype, 'current_url': currentUrl, } template = 'manage.html' return render(request, template, params)
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 get_prep_value(self, value): """Converts from base36 to base10 for the DB""" if value is not None: return base36.loads(value) return value
def base_all(): cypher_text = '' plain_text = '' text = request.values.get('text') num_of_base = request.values.get('num_of_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 render_template('base-base64.html', result=resu) 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 render_template('base-base64.html', result=resu) else: resu = {'code': 10001, 'message': 'args can not be blank!'} return render_template('base-base64.html', result=resu) except: resu = {'code': 10000, 'message': 'input error'} return render_template('base-base64.html', result=resu)
def decode36(val): return base36.loads(val)
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 test_dumps_and_loads_zero(): assert base36.dumps(0) == '0' assert base36.loads('0') == 0
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 test_dumps_and_loads(number, value): assert base36.dumps(number) == value assert base36.dumps(-number) == '-' + value assert base36.loads(value) == number assert base36.loads('-' + value) == -number