0

If I have a string FOOBAR-efkem4x-dnj3mn-efjn2j-lf4m2l (in this format) I need to convert into a shorter string consisting of just numerical values [0-9] so I can put it as a unique number in the URL for my Django project.

So that string should be converted into something like 324982984829 (can be higher or lower length, doesn't matter as long it is all numeric). Decoding 324982984829 should get me back to FOOBAR-efkem4x-dnj3mn-efjn2j-lf4m2l.

The end numerical value should be unique for every unique string.

Is there any way of doing this?

VertigoRay
  • 5,935
  • 6
  • 39
  • 48
user1757703
  • 2,925
  • 6
  • 41
  • 62
  • Look at https://gist.github.com/sekondus/4322469 – Paul Draper May 25 '14 at 22:03
  • 1
    If you happen to want obscurity, not security, see http://stackoverflow.com/questions/2490334/simple-way-to-encode-a-string-according-to-a-password – Paul Draper May 25 '14 at 22:03
  • 2
    You can't encode the string to a shorter numerical string, but if you want a longer why not simply translate every character to its `ord` and add some 0's if needed for padding (if you are using only regular characters, 3 numerals per letter will be enough) – tbrisker May 25 '14 at 22:15
  • This is actually called encoding, not encryption (encryption requires a key to be used). tbrisker comment makes a good starting point. It may not be optimal though, you should create a special mapping from character to decimal value for that (that's tricky though, so if ordinals suffice, go for it). – Maarten Bodewes May 25 '14 at 23:21

1 Answers1

1

Try a two-way dictonary which is a nice way to do that task. An working example looks like that:

class TwoWayDict(dict):
    def __setitem__(self, key, value):
        # Remove any previous connections with these values
        if key in self:
            del self[key]
        if value in self:
            del self[value]
        dict.__setitem__(self, key, value)
        dict.__setitem__(self, value, key)

    def __delitem__(self, key):
        dict.__delitem__(self, self[key])
        dict.__delitem__(self, key)

    def __len__(self):
        """Returns the number of connections"""
        # The int() call is for Python 3
        return int(dict.__len__(self) / 2)

d = TwoWayDict()
for i in range(10):
    d["FOOBAR-efkem4x-dnj3mn-efjn2j-lf4m2l"+str(i)] = str(i)



for i in range(10):
    print d['FOOBAR-efkem4x-dnj3mn-efjn2j-lf4m2l'+str(i)], "<->", d[str(i)]

Of course you can use any other numerical hash aswell.

Community
  • 1
  • 1