使用Swift在iOS中创建安全随机数? [英] Create a Secure Random number in iOS using Swift?
本文介绍了使用Swift在iOS中创建安全随机数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
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.
推荐答案
您似乎在使用错误的函数。使用您的功能,您将生成一个新密钥。但是正如您的标题所述,您想生成安全的随机数。
为此,有一个函数叫做: SecRandomCopyBytes(::_:)
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.
}
资料来源: Apple文档
这篇关于使用Swift在iOS中创建安全随机数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文