Generates an array of cryptographically secure random bytes.


func SecRandomCopyBytes(_ rnd: SecRandomRef?, _ count: Int, _ bytes: UnsafeMutableRawPointer) -> Int32



The random number generator object to use. Specify kSecRandomDefault to use the default random number generator.


The number of random bytes to return in the array pointed to by the bytes parameter.


A pointer to an array that the function fills with cryptographically secure random bytes. Use an array that is large enough to hold at least count bytes.

Return Value

A result code set to errSecSuccess or some other value on failure.


Always test the returned status to make sure that the array has been updated with new, random data before trying to use the values. For example, to create 10 random bytes:

var bytes = [Int8](repeating: 0, count: 10)
let status = SecRandomCopyBytes(kSecRandomDefault, bytes.count, &bytes)

if status == errSecSuccess { // Always test the status.
    // Prints something different every time you run.

See Also

Random Numbers

typealias SecRandomRef

An abstract Core Foundation-type object containing information about a random number generator.

let kSecRandomDefault: SecRandomRef

An alias for the default random number generator.