Can SymmetricKey be used as substitute for SecRandomCopyBytes? I found this code snippet in WWDC19 video

var key = Array(repeating: 0, count: 32)
let err = SecRandomCopyBytes(kSecRandomDefault, keyByteCount, &key)
memset_s(&key, 32, 0, 32)

and then use this as substitute:

let key = SymmetricKey(size: .bits256)

Documentation for SymetricKey is quite lean. So I am not sure is it safe to use SymmetricKey as CPRNG? If yes, why? Thank you!

1 Answer 1


In Apple's Swift Crypto (an open-source implementation of the CrypoKit API), the constructor of SymmetricKey just generates the required number of bytes with a CSPRNG, so there's no functional difference between using the CSPRNG directly or through SymmetricKey. Any other implementation wouldn't make sense.

However, since SymmetricKey implies that it is meant for symmetric cryptography, using it for other purposes can lead to some confusion, so it may be a good idea to avoid that.

  • I followed it up to: github.com/apple/swift-crypto/blob/… So SymmetricKey uses SystemRandomNumberGenerator developer.apple.com/documentation/swift/… In the doc they say that it uses arc4random on Apple platforms. But I don't completely understand how arc4random differs from SecRandomCopy bytes. The later can return an error so they should differ somehow under the hood? May 31 at 16:07
  • All (proper) application-level CSPRNGs eventually use the CSPRNG of the operating system, be it arc4randon on Apple or /dev/(u)random on Linux. No matter how many layers of code are stacked on top of the OS system calls, the source of randomness is always the same. So it really doesn't matter. As I've said, I'd use the variant that makes sense in the context. If you need a symmetric key, use SymmetricKey. If you need a general-purpose CSPRNG, use SecCopyRandomBytes.
    – Ja1024
    May 31 at 16:22

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .