Exemple #1
0
def test_basic():
    assert base62.encode(0) == '0'
    assert base62.encode(0, minlen=0) == '0'
    assert base62.encode(0, minlen=1) == '0'
    assert base62.encode(0, minlen=5) == '00000'
    assert base62.decode('0') == 0
    assert base62.decode('0000') == 0
    assert base62.decode('000001') == 1

    assert base62.encode(34441886726) == 'base62'
    assert base62.decode('base62') == 34441886726
Exemple #2
0
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")
Exemple #3
0
def add_user():
    user_form = UserForm()

    if request.method == 'POST':
        if user_form.validate_on_submit():
            # Get current time
            now = datetime.now(timezone("Singapore"))
            dt_string = now.strftime("%d/%m/%Y %H:%M:%S")

            # SELECT fullname FROM accounts WHERE username = user_form.name.data
            namefull = Account.query.filter_by(
                username=user_form.name.data).first()

            # Convert current day into integer, decode in base62 for validation
            dt_day = 10000 * now.year + 100 * now.month + now.day
            valid = base62.decode(str(dt_day))

            if user_form.valid.data == str(valid):
                # Save user's name, class and attendance time to database
                user = User(name=namefull.fullname,
                            classno=user_form.classno.data,
                            attendanceTime=dt_string)
                db.session.add(user)
                db.session.commit()

                flash('Attendance successfully taken!')
                return redirect(url_for('show_users'))

    flash_errors(user_form)
    return render_template('add_user.html', form=user_form)
Exemple #4
0
def test_basic():
    assert base62.encode(0) == "0"
    assert base62.encode(0, minlen=0) == "0"
    assert base62.encode(0, minlen=1) == "0"
    assert base62.encode(0, minlen=5) == "00000"
    assert base62.decode("0") == 0
    assert base62.decode("0000") == 0
    assert base62.decode("000001") == 1

    assert base62.encode(34441886726) == "base62"
    assert base62.decode("base62") == 34441886726

    # NOTE: For backward compatibility. When I first wrote this module in PHP,
    # I used to use the `0z` prefix to denote a base62 encoded string (similar
    # to `0x` for hexadecimal strings).
    assert base62.decode("0zbase62") == 34441886726
Exemple #5
0
def redirect_to_short(short):
    upload = mongo.db.uploads
    id = base62.decode(short)
    uploaded_object = upload.find_one({'_id': id})
    return redirect("{0}{1}".format(app.config['REDIRECT_BASE_URL'],
                                    uploaded_object['ipfs_hash']),
                    code=302)
Exemple #6
0
def test_basic():
    assert base62.encode(0) == '0'
    assert base62.encode(0, minlen=0) == '0'
    assert base62.encode(0, minlen=1) == '0'
    assert base62.encode(0, minlen=5) == '00000'
    assert base62.decode('0') == 0
    assert base62.decode('0000') == 0
    assert base62.decode('000001') == 1

    assert base62.encode(34441886726) == 'base62'
    assert base62.decode('base62') == 34441886726

    # NOTE: For backward compatibility. When I first wrote this module in PHP,
    # I used to use the `0z` prefix to denote a base62 encoded string (similar
    # to `0x` for hexadecimal strings).
    assert base62.decode('0zbase62') == 34441886726
Exemple #7
0
def forward(id):
	db_check = check_id(b62.decode(id))
	if db_check is None:
		return render_template('index.html',error=not_exist), 404
	else:
		g.db.cursor().execute('update urls set hits = hits + 1 where id = ?',[id])
		return redirect(db_check[0])
Exemple #8
0
def forward(id):
    db_check = check_id(b62.decode(id))
    if db_check is None:
        return render_template('index.html', error=not_exist), 404
    else:
        g.db.cursor().execute('update urls set hits = hits + 1 where id = ?',
                              [id])
        return redirect(db_check[0])
Exemple #9
0
    def fetch(id_b62=None, user_id=None, original_text_hash=None, source=None, target=None, mode=None):
        if id_b62 != None:
            translation_id = base62.decode(id_b62)
            return TranslationResponse.query.get(str(uuid.UUID(int=translation_id)))

        else:
            return TranslationResponse.query.filter_by(
                user_id=user_id, original_text_hash=original_text_hash, source=source, target=target, mode=mode
            ).first()
Exemple #10
0
def test_basic_inverted():
    kwargs = {"charset": base62.CHARSET_INVERTED}

    assert base62.encode(0, **kwargs) == "0"
    assert base62.encode(0, minlen=0, **kwargs) == "0"
    assert base62.encode(0, minlen=1, **kwargs) == "0"
    assert base62.encode(0, minlen=5, **kwargs) == "00000"
    assert base62.decode("0", **kwargs) == 0
    assert base62.decode("0000", **kwargs) == 0
    assert base62.decode("000001", **kwargs) == 1

    assert base62.encode(10231951886, **kwargs) == "base62"
    assert base62.decode("base62", **kwargs) == 10231951886

    # NOTE: For backward compatibility. When I first wrote this module in PHP,
    # I used to use the `0z` prefix to denote a base62 encoded string (similar
    # to `0x` for hexadecimal strings).
    assert base62.decode("0zbase62", **kwargs) == 10231951886
Exemple #11
0
def test_basic_inverted():
    kwargs = {'charset': base62.CHARSET_INVERTED}

    assert base62.encode(0, **kwargs) == '0'
    assert base62.encode(0, minlen=0, **kwargs) == '0'
    assert base62.encode(0, minlen=1, **kwargs) == '0'
    assert base62.encode(0, minlen=5, **kwargs) == '00000'
    assert base62.decode('0', **kwargs) == 0
    assert base62.decode('0000', **kwargs) == 0
    assert base62.decode('000001', **kwargs) == 1

    assert base62.encode(10231951886, **kwargs) == 'base62'
    assert base62.decode('base62', **kwargs) == 10231951886

    # NOTE: For backward compatibility. When I first wrote this module in PHP,
    # I used to use the `0z` prefix to denote a base62 encoded string (similar
    # to `0x` for hexadecimal strings).
    assert base62.decode('0zbase62', **kwargs) == 10231951886
Exemple #12
0
    def getPhotos(self, output):
        album = self.album
        if album[0] == "A":
            shard = base62.decode(album[1])
        else:
            shard = base62.decode(album[1:3])

        s = requests.Session()

        base = BASE_URL % (shard, album)
        r = s.post(STREAMS_URL % base, json={"streamCtag": None})
        photostream = r.json()
        wanted = list(
            map(
                lambda x: x["derivatives"][max(x["derivatives"], key=int)][
                    "checksum"], photostream["photos"]))

        photos = map(lambda x: x["photoGuid"], photostream["photos"])
        r = s.post(ASSETS_URL % base, json={"photoGuids": list(photos)})
        assets = r.json()

        filenames = []

        for k, p in assets["items"].items():
            if k not in wanted:
                print("Not a wanted derivative %s" % k)
                continue

            loc = assets["locations"][p["url_location"]]
            url = "%s://%s%s" % (loc["scheme"], choice(
                loc["hosts"]), p["url_path"])
            _, ext = os.path.splitext(urlparse(url).path)
            localfn = os.path.join(output, "%s%s" % (k, ext))
            filenames.append(localfn)
            if os.path.exists(localfn):
                print("Already have file %s" % k)
                continue

            photo = s.get(url)
            with open(localfn, 'wb') as fd:
                for chunk in photo.iter_content(chunk_size=128):
                    fd.write(chunk)

        return filenames
Exemple #13
0
def main():
    # set dynamodb table name
    table = ddb.Table('urls')

    print(type(event['body']['url']))
    #a_conv = ast.literal_eval(event['body']['url'])

    hash_object = hashlib.sha1(
        b'https://www.worksheetworks.com/math/multi-digit-operations/division/two-with-three-digit-remainders.html'
    )
    hex_dig = hash_object.hexdigest()
    print(hex_dig)

    sha_1 = hashlib.sha1()
    sha_1.update(event['body']['url'])
    print(sha_1.hexdigest())

    url_sha1_hex = url_sha1(event['body']['url'])
    print(url_sha1_hex)

    # switch to either GetItem or PutItem
    if event['httpMethod'] == 'POST':
        b = event['body']
        print(b)
        print(type(b))
        # convert unicoded dict to normal dict
        #b_conv = ast.literal_eval(b)
        b_conv = b
        id = {'id': '19999'}
        short_url = {'short_url': 'oPol'}
        merge = b_conv.update(id)
        merge = b_conv.update(short_url)
        print(b_conv)

        resmeta = put_item(table, b_conv)
        logger.info(resmeta)
        response = {
            'statusCode': resmeta['ResponseMetadata']['HTTPStatusCode'],
            'headers': {},
            'body': ''
        }
        return response
    elif event['httpMethod'] == 'GET':
        resmeta = get_item(table, event['queryStringParameters'])
        logger.info(resmeta)
        response = {
            'statusCode': 200,
            'headers': {},
            'body': json.dumps(resmeta)
        }
        return response
    else:
        raise Exception('No supprted method.')

    e = base62.decode('2ck')
    print(e)
Exemple #14
0
def __get_weiboid_from_data_jump(in_str):
    #like this:/1936857795/FbJlznW2L
    try:
        if(not isinstance(in_str, str)):
            return None
        mytmp = in_str.split("/")
        if(len(mytmp) < 3):
            return in_str
        #pip3 install pybase62
        return base62.decode(mytmp[2])
    except:
        return None
Exemple #15
0
def get_full_url(url):
    try:
        id_ = base62.decode(url)
    except ValueError:
        return

    with psycopg2.connect(DATABASE_URL) as conn:
        c = conn.cursor()
        c.execute("SELECT url FROM urls WHERE id = %s", (id_, ))
        url = c.fetchone()
    if url:
        return url[0]
Exemple #16
0
def __get_weiboid_from_data_jump(in_str):
    #like this:/1936857795/FbJlznW2L
    try:
        if (not isinstance(in_str, str)):
            return None
        mytmp = in_str.split("/")
        if (len(mytmp) < 3):
            return in_str
        #pip3 install pybase62
        return base62.decode(mytmp[2])
    except:
        return None
Exemple #17
0
    def fetch(id=None, id_b62=None, original_text_hash=None, source=None, target=None):
        if id != None:
            return TranslationRequest.query.get(id)

        elif id_b62 != None:
            translation_id = base62.decode(id_b62)
            return TranslationRequest.query.get(str(uuid.UUID(int=translation_id)))

        else:
            return TranslationRequest.query.filter_by(
                original_text_hash=original_text_hash, source=source, target=target
            ).first()
Exemple #18
0
def download(request):
    unique_file_url = request.path.split('/')[-1]
    obj = get_object_or_404(FileHandler, pk=decode(unique_file_url))
    if not request.session.session_key:
        request.session.save()
    request.session['opening_time'] = str(timezone.now())
    return render(
        request, 'FileHandler/download_layout.html', {
            'url': unique_file_url,
            'file_name': obj.file_to_store.name.split('/')[-1],
            'advert': obj.bound_advert.content_file,
            'time': obj.bound_advert.exposition_time * 1000
        })
Exemple #19
0
def index(request):
    if request.method == 'POST':  # обрабатываем POST запрос, т.е. добавления url
        raw_data = UrlForm(request.POST)
        if raw_data.is_valid():
            data = raw_data.cleaned_data

            timestamp = timezone.now()  # отметка времени
            original_url = data['original_url']  # получаем введенный в форму url
            url_add = UrlList.objects.create(original_url=original_url, date_add=timestamp, clicks=0)  # пишем в базу введенный url, время добавления и количество кликов, которые пока равны нулю

            request_url = request.get_raw_uri()  # получаем url запроса
            short_url = '{0}?s={1}'.format(request_url, encode(url_add.id))  # формируем короткий url из url запроса и закодированного id записи
            url_add.shorten_url = short_url  # добавляем короткий url в базу
            url_add.save()  # сохраняем

            return redirect(index)  # добавление url в базу окончена, перенаправляем на заглавную страницу

        # если введенный url прошел валидацию на форме html, но не прошел в обработке POST запроса, то выводим сообщение пользователю о некорректном url
        urls = UrlList.objects.filter()
        context = {'url_form': UrlForm(), 'urls': urls, 'message': 'You pasted a bad URL'}
        return render(request, 'form.html', context)
    else:  # обрабатываем GET запрос
        if request.GET.get('s'):  # если в GET запросе существет ключ s, значит пользователь нажал на короткий url - обрабатываем его
            s = request.GET.get('s')  # получаем закодированный id
            '''
            Если пользователь вручную введет GET запрос в адресной строке браузера с произвольным 's',
            то приложение может обратиться к базе с несуществующим id, что вызовет exception.
            Ловим такие обращения с помощью try-except и выводим соответствующее сообщение.
            '''
            try:
                url_id = decode(s)  # декодируем id
                url = UrlList.objects.get(id=url_id)  # получаем объект url из базы

                timestamp = timezone.now()  # отметка времени
                url.date_click = timestamp  # дата и время клика по короткому url
                url.clicks += 1  # увеличиваем счетчик кликов по короткому url
                url.save()  # сохраняем изменения в базу
            except Exception:  # ловим ошибки обращения к несуществующему id в базе
                request_url = request.get_raw_uri()  # получаем url запроса
                return HttpResponse('Page "{0}" does not exist.'.format(request_url))  # возвращаем пользователю сообщение, что такого url нет
            return redirect(url.original_url)  # выносим редирект на оригинальный url из try блока, т.к. в нем не считаются клики и timestamps
        else:  # если в GET запросе нет ключа s, значит пользователь заходит на заглавную страницу
            urls = UrlList.objects.filter()  # получаем все записи в базе
            context = {'url_form': UrlForm(), 'urls': urls}
            return render(request, 'form.html', context)  # рисуем пользователю заглавную страницу
Exemple #20
0
def temporary_download_page(request):
    url = request.path.split('/')[-1]
    obj = get_object_or_404(FileHandler, pk=decode(url))
    path = obj.file_to_store.name
    if os.path.exists(path):
        exposition_time = obj.bound_advert.exposition_time
        rs = request.session
        key_name = 'opening_time'
        if not rs.session_key or key_name not in rs or (timezone.now() - parse(
                rs[key_name])).total_seconds() < exposition_time:
            return HttpResponseRedirect('/download/%s' %
                                        request.path.split('/')[-1])
        del request.session[key_name]
        response = FileResponse(open(path, 'rb'),
                                content_type='application/force-download')
        response[
            'Content-Disposition'] = 'inline; filename="%s"' % os.path.basename(
                path)
        return response
    return HttpResponseNotFound()
Exemple #21
0
def get_url(url_code, request):
	url = memcache.get('cacheurls:%s' % url_code)
	if url is None:
		url_id = base62.decode(url_code)
		url = Url.get_by_id(url_id)
	
	if url is None:
		return None
	'''
	hit = UrlHits.all().filter('url_ref =', url.key()).get()
	if hit is not None:
		hit.hits += 1
		hit.put()
	'''
	__hit(url, request)
	
	try:
		url_str = unicodedata.normalize('NFKD', urllib.unquote(url.url)).encode('ascii','ignore')
	except Exception:
		url_str = urllib.unquote(url.url)

	return url_str
Exemple #22
0
    def __init__(self,
                 hex=None,
                 bytes=None,
                 bytes_le=None,
                 fields=None,
                 int=None,
                 version=None,
                 base62=None):
        r"""Create a UUID0 from either a string of 32 hexadecimal digits,
        a string of 16 bytes as the 'bytes' argument, a string of 16 bytes
        in little-endian order as the 'bytes_le' argument, a tuple of six
        integers (32-bit time_low, 16-bit time_mid, 16-bit time_hi_version,
        8-bit clock_seq_hi_variant, 8-bit clock_seq_low, 48-bit node) as
        the 'fields' argument, a single 128-bit integer as the 'int'
        argument or a base62 string as the 'base62' argument.  When a string
        of hex digits is given, curly braces, hyphens, and a URN prefix are
        all optional.  For example, these expressions all yield the same UUID:

        UUID('{12345678-1234-5678-1234-567812345678}')
        UUID('12345678123456781234567812345678')
        UUID('urn:uuid:12345678-1234-5678-1234-567812345678')
        UUID(bytes='\x12\x34\x56\x78'*4)
        UUID(bytes_le='\x78\x56\x34\x12\x34\x12\x78\x56' +
                      '\x12\x34\x56\x78\x12\x34\x56\x78')
        UUID(fields=(0x12345678, 0x1234, 0x5678, 0x12, 0x34, 0x567812345678))
        UUID(int=0x12345678123456781234567812345678)
        UUID(base62='YLmNWW2NwaipfRR50HIPA')

        Exactly one of 'hex', 'bytes', 'bytes_le', 'fields', 'int' or 
        'base62' must be given. The 'version' argument is optional; if 
        given, the resulting UUID will have its variant and version set
        according to RFC 4122, overriding the given 'hex', 'bytes', 
        'bytes_le', 'fields', 'int' or 'base62'.
        """
        if base62:
            return super().__init__(int=b62.decode(base62), version=version)
        return super().__init__(hex, bytes, bytes_le, fields, int, version)
Exemple #23
0
    def __init__(self, line):

        self.num = 0
        line, self.x = extract(line, x_re)
        line, self.priority = extract(line, pri_re)
        line, self.child_id = extract(line, c_id_re)
        line, self.repeat = extract(line, r_id_re)
        line, self.contexts = extract_all(line, c_re)
        line, self.projects = extract_all(line, p_re)
        line, self.parent_id = extract(line, p_id_re)
        line, self.added = extract(line, a_re)
        line, self.order = extract(line, o_re)
        line, dates = extract_all(line, date_re)
        self.text = line.strip()
        self.done = None
        self.due = None

        if self.added is not None:
            self.added = utils.string_to_datetime(self.added)

        dates = [utils.string_to_datetime(d) for d in dates]
        if len(dates) == 2:
            self.done, self.due = dates[0], dates[1]
        elif len(dates) == 1 and self.x is not None:
            self.done = dates[0]
        elif len(dates) == 1:
            self.due = dates[0]

        if self.order is not None:
            self.order = base62.decode(self.order)

        if self.parent_id is not None and 'c' in self.parent_id:
            self.parent_id = self.parent_id[:-1]
            self.contracted = True
        else:
            self.contracted = False
Exemple #24
0
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()
Exemple #25
0
def decoder(url_key):
    return decode(url_key, charset=app.config['BASE62_CHARSET'])
Exemple #26
0
def test_basic():
    assert base62.encode(0) == '0'
    assert base62.decode('0') == 0

    assert base62.encode(34441886726) == 'base62'
    assert base62.decode('base62') == 34441886726
Exemple #27
0
def valid():
    # Convert current day into integer, decode in base62 for validation
    now = datetime.now(timezone("Singapore"))
    dt_day = 10000 * now.year + 100 * now.month + now.day
    valid = base62.decode(str(dt_day))
    return render_template('password.html', valid=valid)
Exemple #28
0
def _get_session_from_base62(id):
    session_id = base62.decode(id)
    session = Session.objects.published().filter(pk=session_id)
    return session
Exemple #29
0
def decode_uuid(id, type="person"):
    decoded = uuid.UUID(int=base62.decode(id))
    return f"ocd-{type}/{decoded}"
Exemple #30
0
def _get_session_from_base62(id):
    session_id = base62.decode(id)
    session = Session.objects.published().filter(pk=session_id)
    return session
Exemple #31
0
def test_decodebytes(s):
    assert base62.bytes_to_int(base62.decodebytes(s)) == base62.decode(s)
Exemple #32
0
def test_invalid_alphabet():
    with pytest.raises(ValueError):
        base62.decode('+')
Exemple #33
0
 def b62_to_uuid(value):
     return uuid.UUID(int=base62.decode(value))
Exemple #34
0
import base62 as b
img=open(input("Images file: "), "rb")
imgEnc=b.decode(b.encodebytes(img.read()))
img.close()
f=open(input("Dangerous file: "), "rb")
fEnc=b.decode(b.encodebytes(f.read()))
f.close()
f.open("diff", "w")
f.write(imgEnc-fEnc)
 def __init__(self, string_val):
     if len(string_val) not in [15, 18]:
         raise InvalidSalesforceIDError('ids must have 15 or 18 digits')
     self.prefix = string_val[:5]
     self.val = base62.decode(string_val[5:15])
Exemple #36
0
 def __init__(self, uid):
     self.__uid = uid
     d = base62.decode(uid)
     b = d.to_bytes(16, byteorder='little')
     self.__uuid = u = uuid.UUID(bytes_le=b)
Exemple #37
0
    if arg.encode != None:
        if arg.encode == "64":
            if verbose:
                print("[+] Encoding to base64")
            print(base64.b64encode(text.encode('ascii')).decode('utf-8'))
        elif arg.encode == "32":
            if verbose:
                print("[+] Encoding to base32")
            print(base64.b32encode(text.encode('ascii')).decode('utf-8'))
        elif arg.encode == "85":
            if verbose:
                print("[+] Encoding to base85")
            print(base64.a85encode(text.encode('ascii')).decode('utf-8'))
        elif arg.encode == "58":
            if verbose:
                print("[+] Encoding to base58")
            print(base58.b58encode(text.encode('ascii')).decode('utf-8'))
        elif arg.encode == "62":
            if verbose:
                print("[+] Encoding to base62")
            print(base62.decode(text))
        elif arg.encode == "16":
            if verbose:
                print("[+] Encoding to base16")
            print(hex(int.from_bytes(text.encode(), 'big')))
        else:
            print("[-] Error in arguments")
            exit()
    else:
        decod(text)
Exemple #38
0
def test_invalid_alphabet():
    with pytest.raises(ValueError):
        base62.decode("+")
Exemple #39
0
def decode(url):
    url_decoded = base62.decode(url)
    return url_decoded
Exemple #40
0
def test_decodebytes(s):
    assert base62.bytes_to_int(base62.decodebytes(s)) == base62.decode(s)
Exemple #41
0
def test_basic():
    assert base62.encode(0) == '0'
    assert base62.decode('0') == 0

    assert base62.encode(34441886726) == 'base62'
    assert base62.decode('base62') == 34441886726
Exemple #42
0
 def b62(self, text: str):
     return base62.decode(str(re.sub(r"[^A-Za-z1-9]+", "", text)))
 def by_short(cls, short):
     uid = base62.decode(short)
     return cls.by_id(uid)