Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Preview
Start a free Courses trial
to watch this video
What is Easy User-land CSPRNG? A user-land (refers to an application space that is external to the kernel and is protected by privilege separation) API for an easy to use and reliable Cryptographically secure pseudorandom number generator in PHP.
Documentation
What is C-spring?
0:00
Cryptographically secure
pseudorandom number generator.
0:02
A secure way of generating random data.
0:06
There are random number generators in PHP,
RAN for instance.
0:09
But none of the options in
version five are very secure.
0:13
In PHP seven, they put together a system
interface to the operating systems
0:17
random number generator.
0:22
Because we can now use the operating
system's random number generator,
0:24
if that gets hacked,
we have bigger problems.
0:28
It probably means your entire
system is compromised, and
0:31
there's a flaw in your
operating system itself.
0:34
Secure random numbers are especially
useful when generating random passwords or
0:38
password.
0:43
What does this look like for
you as a developer?
0:45
You now have two new functions to use,
random int and random bytes.
0:48
When using random_bytes you
supply a single argument link,
0:53
which is the link of the random string,
that should be returned it bytes.
0:58
random_bytes then returns a string
1:03
containing the requested number of
cryptographically secure random bytes.
1:06
If we combine this with
something like bin2hex,
1:11
we can get the hexadecimal representation.
1:15
These are bytes, not integers.
1:18
If you are looking to
return a random number, or
1:21
integer, you should use
the random_int function.
1:24
When using random_int,
you supply two arguments, min and max.
1:28
This is the minimum and
maximum numbers you want to use.
1:34
For example, random_int(1,20) would
return a random number between 1 and
1:38
20, including the possibility of 1 and 20.
1:45
Some random errors and exceptions to note.
1:51
Min and max must be between the system
setting of PHP_INT_MIN and PHP_INT_MAX.
1:53
If an appropriate source of
randomness cannot be found,
2:00
an exception will be thrown.
2:03
If invalid parameters are given,
a TypeError will be thrown.
2:06
If max is less than min,
an Error will also be thrown.
2:10
Although this isn't really a gotcha,
if you are using the ran function for
2:15
anything even remotely secure, you'll want
to change that ran function to randomint.
2:19
You need to sign up for Treehouse in order to download course files.
Sign up