1

I am trying to figure out a way to encrypt a user id number. My idea is to encrypt the id ( between 1 and 5 characters ) in combination with some letters ( like _wordtouse ). The only two requirements are

  1. The crypted version can only contain a maximum of 15 characters
  2. I need to be able to decrypt the string on a different page

The reason for all of this is that i am trying to "hide" user id numbers when someone enters a users profile. So i am trying to find a way to deliver an encrypted version of the user id through the url as a get parameter.

Does anyone have an idea on how to solve this?

Dennis
  • 595
  • 1
  • 6
  • 22
  • 2
    At [so] you are expected to try to **write the code yourself**. After **[doing more research](//meta.stackoverflow.com/questions/261592)** if you have a problem you can **post what you've tried** with a **clear explanation of what isn't working** and providing a [**Minimal, Complete, and Verifiable example**](//stackoverflow.com/help/mcve). I suggest reading [ask] a good question and [the perfect question](http://codeblog.jonskeet.uk/2010/08/29/writing-the-perfect-question/). Also, be sure to take the [tour] and read **[this](//meta.stackoverflow.com/questions/347937/)**. – John Conde May 02 '17 at 19:50

3 Answers3

6

I would suggest just using the hashids library which is pretty popular and what many url shortening services use. While it isn't really "encryption", it is likely good enough to hide a user's id number in a url. Example:

$userID = 1234;
$hashids = new Hashids\Hashids('some random secret string');

//encode the user id
$encodedID = $hashids->encode($user_id);

//on the other page, decode the user id
$decodedID = $hashids->decode($encodedID);
Jonathan Kuhn
  • 15,279
  • 3
  • 32
  • 43
1

https://stackoverflow.com/a/30189841/1325575 explains this in-depth.

However, the short version, which requires no 3rd party installs:

  1. Use openssl_encrypt for encryption
  2. Use openssl_decrypt for decryption

I'm confident that with those 3 links you're gonna find what you're after.

Community
  • 1
  • 1
The Onin
  • 5,068
  • 2
  • 38
  • 55
0

This question was already answered here I believe: Encrypt/Encoding an ID in URL string

But I would like to add that instead of using mcrypt (the project is abandoned) you should use: Libsodium, or defuse/php-encryption or OpenSSL

Community
  • 1
  • 1
lloiacono
  • 4,714
  • 2
  • 30
  • 46
  • 1
    If the question has been answered elsewhere you should delete your answer and flag it as a duplicate – Machavity May 02 '17 at 19:55
  • @Machavity, the previous answer advices to use mcrypt which is abandoned, that is why I added which alternatives to use IMO – lloiacono May 02 '17 at 19:56