3

How can I do hashing url paramaters in Laravel? I know the Hash::make method, but that's a method for passwords (those hashes are not very url-friendly). Does Laravel have a beter alternative, so I can hash parameters like http://url?key=2jd8dka72

Marcin Orlowski
  • 72,056
  • 11
  • 123
  • 141
angelique000
  • 899
  • 3
  • 10
  • 28

2 Answers2

8

you can use Laravel Encrypt function for that .

put use Illuminate\Support\Facades\Crypt; in header section and than use Crypt::encrypt($param) to encrypt param and Crypt::decrypt($param) to decrypt it.

Lakshay Jain
  • 446
  • 1
  • 3
  • 17
1

Just add base64 encoding to make it more friendly looking.

use Hash;
...
$id = 15;
$key = base64_encode(Hash::make($id));
echo "http://someurl?send_mail_to_user=$id&key=$key";

When you check it:

use Hash;
...
$keyDecoded = base64_decode($request->key);
if(Hash::check($request->id, $keyDecoded)) {
   // checked
}

Another way is to use some complicated function like a large number at another base. But it is not secured (just security through obscurity):

echo base_convert($id * 250 + 5675675, 10, 33); // converts 15 to 4q18q
echo ((base_convert('4q18q', 33, 10) - 5675675) / 250); // converts back, but this one is not being used
// checking:
if(base_convert($request->id * 250 + 5675675, 10, 33) === $request->key) {
   // checked
}
shukshin.ivan
  • 11,075
  • 4
  • 53
  • 69
  • yes I know. But I don't understand why Laravel doesn't have a default function for this. How do other laravel sites hash url parameters? – angelique000 Aug 18 '17 at 15:43
  • As for password reset token, it is generated with `str_random` and stored in another field of an entity, so it is passed as a friendly string: `reset password via link http://site.ru/password/reset/df06d70b6257690941b4130e5b293932cdb47061593aa0716e79987cad71bd78` You store just an id, password restoring stores two fields: id and token. – shukshin.ivan Aug 18 '17 at 15:47
  • Laravel has encryption class Illuminate\Support\Facades\Crypt to do all this for us. – Lakshay Jain Aug 18 '17 at 15:54
  • He needs to pass a friendly looking string and to check it then. I've introduced two ways. Does it really deserve two downs? What's up? – shukshin.ivan Aug 18 '17 at 15:57
  • It is not strictly defined to use crypting. Hashing suits his purposes as well. – shukshin.ivan Aug 18 '17 at 15:59
  • String generated from Crypt are url friendly – Lakshay Jain Aug 18 '17 at 16:07
  • `base_convert` and `base64_encode` too. It's a bad practice, to downvote another answer that does solve the problem just because it differs from yours. – shukshin.ivan Aug 18 '17 at 17:15
  • I have upvoted your answer. In my opinion your answer is the best answer for my question, I have not seen any better solutions. – angelique000 Aug 22 '17 at 10:12