<!--
{
  "availability" : [
    "iOS: 2.0.0 -",
    "iPadOS: 2.0.0 -",
    "macCatalyst: 13.1.0 -",
    "macOS: 10.7.0 -",
    "tvOS: 9.0.0 -",
    "visionOS: 1.0.0 -",
    "watchOS: 2.0.0 -"
  ],
  "documentType" : "symbol",
  "framework" : "Security",
  "identifier" : "/documentation/Security/SecRandomCopyBytes(_:_:_:)",
  "metadataVersion" : "0.1.0",
  "role" : "Function",
  "symbol" : {
    "kind" : "Function",
    "modules" : [
      "Security"
    ],
    "preciseIdentifier" : "c:@F@SecRandomCopyBytes"
  },
  "title" : "SecRandomCopyBytes(_:_:_:)"
}
-->

# SecRandomCopyBytes(_:_:_:)

Generates an array of cryptographically secure random bytes.

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

## Parameters

`rnd`

The random number generator object to use. Specify [`kSecRandomDefault`](/documentation/Security/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`](/documentation/Security/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:

```swift
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.
}
```

---

Copyright &copy; 2026 Apple Inc. All rights reserved. | [Terms of Use](https://www.apple.com/legal/internet-services/terms/site.html) | [Privacy Policy](https://www.apple.com/privacy/privacy-policy)