md5(uniqid) makes sense for random unique tokens?

前端 未结 8 905
半阙折子戏
半阙折子戏 2020-12-12 17:12

I want to create a token generator that generates tokens that cannot be guessed by the user and that are still unique (to be used for password resets and confirmation codes)

8条回答
  •  既然无缘
    2020-12-12 17:55

    First, the scope of this kind of procedure is to create a key/hash/code, that will be unique for one given database. It is impossible to create something unique for the whole world at a given moment. That being said, you should create a plain, visible string, using a custom alphabet, and checking the created code against your database (table). If that string is unique, then you apply a md5() to it and that can't be guessed by anyone or any script. I know that if you dig deep into the theory of cryptographic generation you can find a lot of explanation about this kind of code generation, but when you put it to real usage it's really not that complicated.

    Here's the code I use to generate a simple 10 digit unique code.

    $alphabet = "aA1!bB2@cC3#dD5%eE6^fF7&gG8*hH9(iI0)jJ4-kK=+lL[mM]nN{oO}pP\qQ/rR,sS.tT?uUvV>xX~yY|zZ`wW$";
    $code = '';
    $alplhaLenght = strlen($alphabet )-1;
    for ($i = 1; $i <= 10; $i++) {
        $n = rand(1, $alplhaLenght );
        $code .= $alphabet [$n];
    }
    

    And here are some generated codes, although you can run it yourself to see it work:

    SpQ0T0tyO%
    Uwn[MU][.
    D|[ROt+Cd@
    O6I|w38TRe

    Of course, there can be a lot of "improvements" that can be applied to it, to make it more "complicated", but if you apply a md5() to this, it'll become, let's say "unguessable" . :)

提交回复
热议问题