0

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.

acmpo6ou
  • 840
  • 1
  • 12
  • 21

2 Answers2

1

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.

Rob Napier
  • 286,113
  • 34
  • 456
  • 610
  • Thanks! This is exactly what I wanted, I was a bit worried about `uses a cryptographically secure algorithm whenever possible`. But I guess on all Apple platforms it should be fine. – acmpo6ou Jul 19 '23 at 14:30
  • 1
    Yeah, they left themselves some wiggle room so they could run on smaller embedded platforms where a proper CSPRNG can sometimes be impossible. – Rob Napier Jul 19 '23 at 14:36
-1

I would add answer how to do fast generation in the interval, this is now implemented in C++ library in GCC and in Visual C++.

If you have chunk of random bits coming in the range [0...N) (N-256 in your case), and you want output in the range [0...M), Daniel Lemire proposed fast method to do that. Check his paper for details.

https://arxiv.org/abs/1805.10941

Severin Pappadeux
  • 18,636
  • 3
  • 38
  • 64