在 Swift 中使用 SecRandomCopyBytes [英] Using SecRandomCopyBytes in Swift
问题描述
我想在 Swift 3.0 中使用 SecRandomCopyBytes
生成随机字节.这是我在 Swift 2.2 中的做法
I want to generate random bytes using SecRandomCopyBytes
in Swift 3.0. Here is how I did it in Swift 2.2
private static func generateRandomBytes() -> String? {
let data = NSMutableData(length: Int(32))
let result = SecRandomCopyBytes(kSecRandomDefault, 32, UnsafeMutablePointer<UInt8>(data!.mutableBytes))
if result == errSecSuccess {
return data!.base64EncodedString(options: NSData.Base64EncodingOptions(rawValue: 0))
} else {
print("Problem generating random bytes")
return nil
}
}
在 Swift 3 中,我尝试这样做,因为我知道 unsafemutablebytes 的概念现在不同了,但它不允许我返回.如果我注释掉返回部分,它仍然说 Generic Parameter ResultType could not be inferred
In Swift 3, I tried to do it like this, since I know the concept of unsafemutablebytes is different now, but it doesn't allow me to return. If I comment out the return part, it still says Generic Parameter ResultType could not be inferred
fileprivate static func generateRandomBytes() -> String? {
var keyData = Data(count: 32)
_ = keyData.withUnsafeMutableBytes {mutableBytes in
let result = SecRandomCopyBytes(kSecRandomDefault, keyData.count, mutableBytes)
if result == errSecSuccess {
return keyData.base64EncodedString(options: NSData.Base64EncodingOptions(rawValue: 0))
} else {
print("Problem generating random bytes")
return nil
}
}
return nil
}
有人知道如何解决这个问题吗?
Does anyone know how to fix this?
谢谢
推荐答案
You was close, but return
在闭包内返回来自闭包,而不是来自外部函数.因此只有 SecRandomCopyBytes()
应该在关闭,结果传回来.
You were close, but return
inside the closure returns
from the closure, not from the outer function.
Therefore only SecRandomCopyBytes()
should be called in the
closure, and the result passed back.
func generateRandomBytes() -> String? {
var keyData = Data(count: 32)
let result = keyData.withUnsafeMutableBytes {
(mutableBytes: UnsafeMutablePointer<UInt8>) -> Int32 in
SecRandomCopyBytes(kSecRandomDefault, 32, mutableBytes)
}
if result == errSecSuccess {
return keyData.base64EncodedString()
} else {
print("Problem generating random bytes")
return nil
}
}
对于单表达式闭包",闭包类型可以推断自动,所以这可以缩短为
For a "single-expression closure" the closure type can inferred automatically, so this can be shortened to
func generateRandomBytes() -> String? {
var keyData = Data(count: 32)
let result = keyData.withUnsafeMutableBytes {
SecRandomCopyBytes(kSecRandomDefault, 32, $0)
}
if result == errSecSuccess {
return keyData.base64EncodedString()
} else {
print("Problem generating random bytes")
return nil
}
}
Swift 5 更新:
func generateRandomBytes() -> String? {
var keyData = Data(count: 32)
let result = keyData.withUnsafeMutableBytes {
SecRandomCopyBytes(kSecRandomDefault, 32, $0.baseAddress!)
}
if result == errSecSuccess {
return keyData.base64EncodedString()
} else {
print("Problem generating random bytes")
return nil
}
}
这篇关于在 Swift 中使用 SecRandomCopyBytes的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!