Search code examples
swiftsecurityrandom

Generate secure random number in range Swift


I need to generate a secure random number in range (e.g. between 0 and 56, or any other range). But I can't find a way to do that, I looked through this thread. Most of the answers there are generating pseudo random numbers; but those that generate secure random numbers, don't allow to specify a range. For example this answer only allows generating numbers between 0 and 128, but I need to specify a different range.

I have no idea how to do this properly with SecRandomCopyBytes. In particular, I need to do this on iOS.


Solution

  • This is almost a duplicate of How to generate a random number in Swift?, but I'm going to treat it as different because your question is really "which answers there are secure."

    The accepted answer from @Catfish_man is a secure random number. The stdlib Int.random(in: 0...56) is what you want. There is no need to create a special method.

    As documented in Int.random:

    This method is equivalent to calling the version that takes a generator, passing in the system’s default random generator.

    The system's default random number generator is SystemRandomNumberGenerator:

    SystemRandomNumberGenerator is automatically seeded, is safe to use in multiple threads, and uses a cryptographically secure algorithm whenever possible. (emphasis added)

    If you are running on an unknown platform and do not know whether it will have an available CSPRNG (or the default CSPRNG is insufficient for your purposes), then there may be reason to worry about .random(in:) (but then you will have a lot of work ahead of you because your other solutions are broken, too). But for all Apple platforms, and the vast majority of non-Apple platforms supported by Swift, you should use the default tool and not try to reinvent this.