5

I have some entities(objects), each one having an id(unique) and a name.
When i want to display oneof these , i have a url like www.domain.com/view/key:xxx.
The key is just the id of the entity encoded with base64_encode, so it's not straightforward from the url what the id is.

What i'm trying to do now (due to the projects specifications) is have the key contain only numbers and letters (base64_encode provides a result like eyJpZCI6IjM2In0= or eyJpZCI6IjM2In0%3D after url encode).

Is there a simple alternative to this? It's not a high-security issue - there are many ways the id can be revealed -, i just need to have a key that contains only letters and numbers that is produced by the entity ID (maybe in combination with its name) that can be decoded to give me the ID back.

All different encode methods i've found can contain special characters as well.
Any help here?
Thanks in advance

2 Answers 2

8

This answer doesn't really apply encryption, but since your question was tagged with encoding as well ...

Since PHP 5 you can use bin2hex:

$s = base64_decode('eyJpZCI6IjM2In0=');
echo bin2hex($s);

Output:

7b226964223a223336227d

To decode:

$s = hex2bin($data);

Or:

$s = pack('H*', $data);

Btw, if the id is sensitive you might want to consider tamper proofing it as an alternative to full-blown encryption.


Forgot to mention how you can make base64 encoded data URL safe:

function base64_url_encode($input)
{
    return strtr(base64_encode($input), '+/=', '-_,');
}

function base64_url_decode($input)
{
    return base64_decode(strtr($input, '-_,', '+/='));
}
Sign up to request clarification or add additional context in comments.

4 Comments

@dynamic of course, but you can always use pack('H*', $str); as the alternative for php < 5.3
Is php.net down for anyone else? I'm trying to look at the hex2bin function. and yeah Jack, thanks.
@dynamic yeah, i've been using us2.php.net for the time being :(
Same for me ... You can use the mirrrors like de.php.net though (even if you're not from Germany :-))
0

There are many PHP encoding/decoding functions. You can find a lot here and here.

Alternatively just get rid of the = at the end of the base64_encode and add it in the PHP code for base64_decode to find the ID.

2 Comments

Can't just get rid of the '=', it may have more than one, and then i will not be able to know how many '=' there where...
@CrisDeBlonde: if you make your ID a fixed length, say by padding the ID on left with leading zeros, then you will always know how many '=' there will be on the end and you can remove them.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.