iOS 可以用SecRandomCopyBytes
函数生成密码学安全的伪随机数,下面是使用示例:
// Swift
import Foundation
func securityRandom(length: Int) -> (Data, OSStatus) {
var data = Data(count: length)
var local = data
let result = local.withUnsafeMutableBytes { mutableBytes in
SecRandomCopyBytes(kSecRandomDefault, data.count, mutableBytes)
}
return (local, result)
}
let (data, result) = securityRandom(length: 16)
if (result == errSecSuccess) {
let str = data.base64EncodedString()
print(str)
}
网友评论