Function

SecRandomCopyBytes(_:_:_:)

Generates an array of cryptographically secure random bytes.

Declaration

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

Parameters

rnd

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

count

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

bytes

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.

Discussion

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.
    print(bytes)
    // 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.