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
SecRandomCopyBytesAPI from the Security framework, which produces cryptographically secure random bytes backed by the system CSPRNG. - CommonCrypto: You could use
CCRandomCopyBytesorCCRandomGenerateBytes(not documented on the Apple Developers website), which are also backed by the system CSPRNG. However, preferSecRandomCopyByteswhich is a wrapper around these functions. - Swift Standard Library: You can use the Swift Standard Library
.randomAPIs which are backed bySystemRandomNumberGenerator. However, note that their random number generator can be customized, so ensure you use the defaultSystemRandomNumberGenerator(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
SymmetricKeyfor keys andAES.GCM.Noncefor 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:
- In Flutter or Dart use
Random.secure(), which is documented as cryptographically secure. It reachesSecRandomCopyBytesthrough the platform integration layers. See this article for a security review. - In React Native use a library such as
react-native-secure-randomorreact-native-get-random-values, which internally callsSecRandomCopyByteson iOS.