Reputation: 2975
I would like to create a unique ID (filename) for some of my files and would like to do so with minimal concern. My original plan was to use a base64
encoded string of random bytes but this will not work because /
is a valid base64
character.
The function I currently use looks like this:
static function uniqueID(){
return base64_encode(random_bytes(16));
}
How could I go about generating a high entropy unique ID that will always be a certain length and contain only characters that are valid in filenames?
Note: I do not wish to use a solution that accomplishes this with str_replace()
.
Edit: I appreciate the responses so far.This is one solution Ive explored locally but I am not sure how to calculate how much entropy I lose when compared to uniqueID()
.
public static function uniqueFilename(){
return bin2hex(random_bytes(12));
}
Upvotes: 1
Views: 308
Reputation: 2975
As User: Sammitch stated,
12 bytes = 96 bits. If you generated a random 96-bit value and then tried to intentionally brute-force guess a collision you'd need to build a Dyson sphere around the sun to power the computer and then wait a few centuries. Just use the random bytes.
96 bits is like concatenating 3x 32bit numbers together, the number of possibilities is: 79,228,162,514,264,337,593,543,950,336
Knowing this we can justify using the following function when $n >= 12
.
public static function uniqueFilename($n = 12){
return bin2hex(random_bytes($n));
}
Upvotes: 1
Reputation: 1016
I would recommend Ramsey's UUID: https://github.com/ramsey/uuid .
We use it in production and it does the job.
Upvotes: 0