WWDC19 announcements came with CryptoKit ; a new framework designed for making cryptography easy.
Today, I want to show how to use CryptoKit to generate numbers.
It’ll a better generator than arc4random used by default on iOS since it generate cryptographic keys, keys that are supposed to be the most random and entropic possible!
A model to generate lottery numbers
First, what are lottery draws?
It’s one or more k among n draws!
We can then define a lottery as an array of Draws:
The most popular french lotteries can then be defined easily within the application:
Once the Draw.random() method gets implemented, we will be able to generate lottery numbers very easily:
Randomness using default implementation
Generating k number among a range is quite straightforward:
In this example, the random is handled by randomElement().
That uses by default the SystemRandomNumberGenerator that will be either:
arc4random_buf on Apple platforms
getrandom if available or /dev/urandom on unix platforms.
Using CryptoSwift’s randomness
Okay, here it becomes a little hacky ; why not using the random bytes securely generated for a key as random source for the lottery numbers?
Doing so is quite easy, since we can use randomElement(using generator: inout RandomNumberGenerator)
And now we can pick numbers using our new generator:
And, in our previous Draw.random() implementation, it’ll give us this:
And this is it, you can now generate draws for all sort of Lotteries you may define using this snippet of code
Okay, let’s face it, I really think that using CryptoKit here is a bit overkill; but why not? It’s so easy to do!
CryptoKit make things like generating secure keys, encrypting, and many more cryptographic operation fairly easy! If you’re into cryptography, you should definitely give it a try in a Playground right away!
And if you have questions about CryptoKit: contact-me via GitHub or Twitter ;)