2
\$\begingroup\$

Will this code be random enough to generate user ids for a website where people can create posts? Would there be a better method other than running this function and validating it doesn't exist in the database? I would prefer to have a method that I don't need to run a database check but the resulting UID should be 8 characters at most.

/**
 * Creates a UID
 * @return string 64 Character UID
 */
public static function createUid($length) {
    $bytes = random_bytes($length / 2);
    $uid = bin2hex($bytes);

    return $uid;
}
\$\endgroup\$
4
  • \$\begingroup\$ As far as I understand it, the only demands you have is that the UID should be unique and no more than 8 characters. Please define what you mean by 'secure'? \$\endgroup\$ Nov 26, 2017 at 20:28
  • \$\begingroup\$ @KIKOSoftware by secure I️ mean basically never will repeat. I️m not storing sensitive info. \$\endgroup\$
    – Joe Scotto
    Nov 28, 2017 at 22:54
  • \$\begingroup\$ That is normally not meant by 'secure', it's called 'unique'. They are two very different concepts. \$\endgroup\$ Nov 29, 2017 at 0:42
  • \$\begingroup\$ php.net/manual/ru/function.uniqid.php#94959 \$\endgroup\$ Nov 29, 2017 at 10:13

1 Answer 1

1
\$\begingroup\$

Personally, when I need something to be secure and consistently unique is to add a secret to an incrementing ID, which I assume your DB already has.

Your members have ID's and they are incremental, but then you can design a secret phrase or some sort of algorithm to append to that number, and then mcrypt it, or, depending on how secure you need your UID, encrypt in other ways and then concatenate it to your desired length.

\$\endgroup\$

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.