Esempio n. 1
0
def random_base_32_string(length):
    """
    Return a random number encoded as a zero-padded base 32 string of the
    specified length.
    """
    maximum = pow(32, length) - 1
    return base32_crockford.encode(random.randint(0, maximum)).zfill(length)
 def generate_alias(self, plan):
     md5 = hashlib.md5()
     md5.update(self.get_alias_seed())
     md5.update(plan[b"id"])
     md5.update(plan[b"description"])
     num = int(md5.hexdigest(), 16)
     return base32_crockford.encode(num)[:self.get_alias_len()]
Esempio n. 3
0
 def test_temporary_redirect(self):
     """
     A non-tracking redirect should return a temporary redirect to
     the target URL.
     """
     key = base32_crockford.encode(self.shorturl2.pk)
     response = self.client.get(reverse('deflect:redirect', args=[key]))
     self.assertRedirectsNoFollow(response, 'http://www.example.com',
                                  status_code=302)
Esempio n. 4
0
 def setUp(self):
     """
     Create a user and model instance to test against.
     """
     user = get_user_model()
     self.user = user.objects.create_user('testing')
     self.shorturl = ShortURL.objects.create(long_url='http://www.example.com',
                                             creator=self.user,
                                             campaign='Example',
                                             medium='Email',
                                             content='Test')
     self.shorturl2 = ShortURL.objects.create(long_url='http://www.example.com',
                                              creator=self.user,
                                              is_tracking=False)
     self.alias = ShortURLAlias.objects.create(redirect=self.shorturl,
                                               alias='test')
     self.key = base32_crockford.encode(self.shorturl.pk)
     self.invalid_key = base32_crockford.encode(self.shorturl.pk + 2)
Esempio n. 5
0
def gen_doi(prefix):
    """
    Generate a random alphanumeric string (Format: xxxx-xxxx)
    as the suffix of a DOI.
    args: (str) prefix: prefix of the DOI
    returns: (str) DOI: the string of DOI
    """
    number = random.randrange(32**(8))
    suffix = base32_crockford.encode(number, split=4).lower()
    DOI = '{}/{}'.format(prefix,suffix)
    return DOI
def uuid_to_str26( _uuid: uuid ) -> str:
    '''
    In: uuid
    Returns: 26-char representation of uuid
    '''
    res = encode( _uuid.int )
    l = len( res )
    if l < 26:
        prefix = ''.join( '0' for _ in range ( 26-l ) )
        res = prefix + res
    return res
def ulid(used_ulid):
    if not used_ulid:
        new_sequence = 0
        old_timestamp = 0
    while new_sequence <= 32767:  # serial search of new_sequence
        new_timestamp = int(round(time.time() * 1000))  # timestamp calculation
        new_randomness = secrets.randbits(65)  # randomness calculation
        if old_timestamp == new_timestamp:  # within a millisecond
            new_sequence += 1  # sequence increment
        else:  # new millisecond
            new_sequence = 0
        yield (base32_crockford.encode(new_timestamp).zfill(10) +
               base32_crockford.encode(new_sequence).zfill(3) +
               base32_crockford.encode(new_randomness).zfill(13))
        old_timestamp = new_timestamp
    else:

        while old_timestamp == int(round(time.time() * 1000)):
            pass
        ulid(used_ulid)
Esempio n. 8
0
def generate_ror_id():
    """Generates random ROR ID.

    The checksum calculation is copied from
    https://github.com/datacite/base32-url/blob/master/lib/base32/url.rb
    to maintain the compatibility with previously generated ROR IDs.
    """

    n = random.randint(0, 200000000)
    n_encoded = base32_crockford.encode(n).lower().zfill(6)
    checksum = str(98 - ((n * 100) % 97)).zfill(2)
    return '{}0{}{}'.format(ROR_API['ID_PREFIX'], n_encoded, checksum)
Esempio n. 9
0
#!/usr/bin/env python3
#
import sys

import datetime

import base32_crockford
#from bases import Bases
#bases = Bases()

strdate = 0
if len(sys.argv) == 2:
    strdate = sys.argv[1]
    sys.stdout.write(str(base32_crockford.encode(strdate)))
else:
    print("Err: no args")
    exit(1)
def test_base32_crockford(input_int):
    assert base32_crockford.decode(
        base32_crockford.encode(input_int)) == input_int
Esempio n. 11
0
def encode_timestamp(val):
    b32 = base32_crockford.encode(val)
    return f"{b32:0>9s}"
Esempio n. 12
0
def encode_random(val):
    b32 = base32_crockford.encode(val)
    return f"{b32:0>5s}"
Esempio n. 13
0
 def test_encode_checksum(self):
     self.assertEqual(b32.encode(1234, checksum=True), '16JD')
Esempio n. 14
0
 def test_encode_split(self):
     self.assertEqual(b32.encode(123456, split=2), '3R-J0')
     self.assertEqual(b32.encode(123456, split=3), '3RJ-0')
Esempio n. 15
0
 def test_encode_zero_checksum(self):
     self.assertEqual(b32.encode(0, checksum=True), '00')
def uprn(uprn):
    return redirect("/address/" + encode(uprn), 301)
Esempio n. 17
0
def generate_doi(prefix, intid, offset, url=False):
    """ Generates a DOI based on Crockford's base32
    http://www.crockford.com/wrmg/base32.html
    
    Args:
        prefix (str): DOI prefix
        intid (int): Internal ID, usually consecutive numbering.
                     Must be < 2e6.
        offset (int): Is added to the internal ID. Assign offsets
                      0, 2e6, 4e6, ... 26e6 to different data centers.
    Returns:
        A 6 character string suited as DOI (without prefix)

    We want a checksum symbol and the resulting suffix
    should have 6 characters (including checksum character).
    If the suffix has a shorter length, it is padded with zeros.
 
    We want to avoid checksums 32 to 36, so that only
    alphanumerical characters are used.

    Since 32**5 - 1 =  906876 * 37 + 19, this leaves us with
    #([0, 906875] X [0, 31] + [0, 19])
    = 906876 * 32 + 20 = 29020052 different DOIs.

    We suggest to split this DOI-suffix-space into 13 ranges, each of them
    with room for 2e6 suffixes. OK, we waste 1.020052 mio suffixes here.

    """
    MAXI = 29020051
    RANGESIZE = int(2e6)
    OFFSETS = range(0, MAXI - RANGESIZE + 2, RANGESIZE)

    intid = int(intid)
    offset = int(offset)
    ## Avoid overlapping ranges for different datacenters
    assert (0 <= intid and intid < RANGESIZE)
    ## Valid offsets to serve max. 13 offset-defined ranges (datacenters)
    ## with 2 mio DOIs each. If each datacenter has its own prefix,
    ## this is mostly aesthetics.
    assert (offset in OFFSETS)

    def intid2i(intid, offset):
        '''
        Calculates the integer which is suited to be converted to base32,
        so that the checksum chracter is alphanumeric.
        
        Args:
            intid (int): internal ID
            offset (int): Offset for data center
        Returns:
            An integer that can be converted to base32 (Crockford)

        '''
        intid += offset
        n = int(intid / 32.)
        c = intid - n * 32
        return 37 * n + c

    suffix = b32.encode(intid2i(intid, offset), checksum=True)
    padding = 6 - len(suffix)
    suffix = padding * '0' + suffix
    proxy = 'https://doi.org/' if url else ''
    return '{}{}/{}'.format(proxy, prefix, suffix)
Esempio n. 18
0
 def generator():
     return '{0}_{1:0>8}'.format(prefix,
                                 b32.encode(random.randint(0, 32**8 - 1)))
Esempio n. 19
0
 def test_encode(self):
     self.assertEqual(b32.encode(1234), '16J')
Esempio n. 20
0
def _create_proposition(request,
                        ballot,
                        appstruct,
                        document=None,
                        section=None):
    appstruct['tags'] = get_or_create_tags(request.db_session,
                                           appstruct['tags'])
    editing_remarks = appstruct.pop('editing_remarks')

    submitter_invitation_key = base32_crockford.encode(secrets.randbits(64))

    proposition = Proposition(
        author=request.current_user,
        ballot=ballot,
        status=PropositionStatus.DRAFT,
        submitter_invitation_key=submitter_invitation_key,
        visibility=PropositionVisibility.HIDDEN,
        external_fields={
            'external_draft': {
                'editing_remarks': editing_remarks
            }
        },
        **appstruct)

    if document is not None and section is not None:
        changeset = Changeset(document=document,
                              section=section,
                              proposition=proposition)
        request.db_session.add(changeset)

    request.db_session.add(proposition)

    is_admin = request.identity.has_global_admin_permissions

    if not is_admin:
        supporter = Supporter(member=request.current_user,
                              proposition=proposition,
                              submitter=True)
        request.db_session.add(supporter)

    request.db_session.flush()
    proposition_url = request.link(proposition)

    exporter_name = ballot.area.department.exporter_settings.get(
        'exporter_name')
    if exporter_name and not is_admin:
        try:
            with start_action(action_type="push_draft",
                              exporter=exporter_name):
                exporter_config = {
                    **getattr(request.app.settings.exporter, exporter_name)
                }
                external_content_template = customizable_text(
                    request, 'push_draft_external_template')
                portal_content_template = customizable_text(
                    request, 'push_draft_portal_template')
                push_draft_to_discourse(exporter_config,
                                        external_content_template,
                                        portal_content_template, proposition,
                                        proposition_url)

        except DiscourseError:
            pass

    return proposition_url
Esempio n. 21
0
def hash(data):
    h = hashlib.sha256(data).hexdigest()
    i = int(h[0:16], 16)
    return base32_crockford.encode(i).strip()
Esempio n. 22
0
 def test_encode_float(self):
     self.assertEqual(b32.encode(4.2), '4')
Esempio n. 23
0
 def get_absolute_url(self):
     return reverse('blog:detail', args=[b32.encode(self.pk), self.slug])
        padding = 8 - (len(result) % 8)
    else:
        padding = 0
    return result + "0" * padding

table = {227: '\xe1', 6: 'C', 199: ',', 200: '\xae', 73: '\xfd', 236: '\xe8', 242: '\x96', 18: '\x0b', 52: 'H',
         105: '\xfa', 184: '\xe0', 159: '\xf6', 253: '\x16', 95: '\xb5'}

table = {0: 'a', 166: 'M', 6: '\xbf', 136: ' ', 236: 'V', 110: '\x0c', 241: '\x9e', 146: '\x9b', 19: '5', 142: 'T', 86: '\xad', 26: '\xa9', 59: '\xda', 92: 'K', 223: ','}

for key in sorted(table.keys()):
    print key, hex(ord(table[key]))


def invert(s):
    temp = hex(int("0b" + s, 2))[2:-1]
    print temp
    temp = binascii.unhexlify(temp)[::-1]
    temp = binascii.hexlify(temp)
    return temp


result = encode_table(table)
print result
result = invert(result)
number = int("0x" + result, 0x10)
print result, len(result)
print hex(number), len(hex(number)),  b32.encode(number)[::-1]


def test_post_absolute_url(post):
    assert post.get_absolute_url() == '/%s/first-post' % b32.encode(post.pk)
Esempio n. 26
0
    def save(self, *args, **kwargs):
        super(Short, self).save(*args, **kwargs)

        if not self.key:
            self.key = base32_crockford.encode(self.pk)
            self.save()
Esempio n. 27
0
 def key(self):
     return base32_crockford.encode(self.pk)
 def generate_code(cls):
     return base32_crockford.encode(random.randint(2**25, 3**18), split=3)