Skip to content

MASTG-BEST-0025: Use Secure Random Number Generator APIs

Use secure random number generator APIs that are backed by the operating system cryptographically secure pseudorandom number generator (CSPRNG). Do not build your own pseudorandom number generator (PRNG).

Swift / Objective-C

  • Security Framework (preferred): Use the SecRandomCopyBytes API from the Security framework, which produces cryptographically secure random bytes backed by the system CSPRNG.
  • CommonCrypto: You could use CCRandomCopyBytes or CCRandomGenerateBytes (not documented on the Apple Developers website), which are also backed by the system CSPRNG. However, prefer SecRandomCopyBytes which is a wrapper around these functions.
  • Swift Standard Library: You can use the Swift Standard Library .random APIs which are backed by SystemRandomNumberGenerator. However, note that their random number generator can be customized, so ensure you use the default SystemRandomNumberGenerator (e.g., by not specifying a custom generator) or a secure alternative (ensure it is cryptographically secure).
  • CryptoKit: CryptoKit doesn't expose a direct random byte generator, but it provides secure random nonces and keys through its cryptographic operations, which are backed by the system CSPRNG. For example, you can use SymmetricKey for keys and AES.GCM.Nonce for nonces without needing to manage raw random bytes directly.

See Random Number Generator for code examples of these APIs.

Other Languages

Consult the standard library or framework to locate the API that exposes the operating system CSPRNG. This is usually the safest path, provided the library itself has no known weaknesses.

For cross-platform or hybrid apps on iOS rely on frameworks that forward calls to the underlying system CSPRNG. For example:

Tests

MASTG-TEST-0311: Insecure Random API Usage