0
public func createSecureRandomKey(numberOfBits: Int) -> Any {
    let attributes: [String: Any] =
        [kSecAttrKeyType as String:CFString.self,
         kSecAttrKeySizeInBits as String:numberOfBits]

    var error: Unmanaged<CFError>?
    guard let privateKey = SecKeyCreateRandomKey(attributes as CFDictionary, &error) else {
        return ""
    }
    return privateKey
}

I am trying to create Secure random number like above way, but returning nothing, Could any one please help me. Thanks.

3
  • have you tried printing error? Commented Jun 7, 2018 at 17:16
  • Yes.. But No error displyed, always going to return "" Commented Jun 7, 2018 at 17:34
  • 3
    Add print(error) inside the guard. Commented Jun 7, 2018 at 21:21

1 Answer 1

2

It looks like you are using the wrong function. With your function you are generating a new key. But as your title says you want to generate secure random numbers. For this there is a function called: SecRandomCopyBytes(::_:)

Here is a code snippet taken from the official apple documentation how to use it:

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

Source: Apple doc

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.