Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift language: How to call SecRandomCopyBytes

From Objective-C, I could do this:

NSMutableData *data = [NSMutableData dataWithLength:length];
int result = SecRandomCopyBytes(kSecRandomDefault, length, data.mutableBytes);

When attempting this in Swift, I have the following:

let data = NSMutableData(length: Int(length))
let result = SecRandomCopyBytes(kSecRandomDefault, length, data.mutableBytes)

but I get this compiler error:

'Void' is not identical to 'UInt8'

The data.mutableBytes parameter is rejected because the types do not match, but I can't figure out how to coerce the parameter (and I'm presuming it's somehow safe to do).

like image 917
Daniel Avatar asked Aug 27 '14 00:08

Daniel


3 Answers

This appears to work:

let data = NSMutableData(length: Int(length))
let result = SecRandomCopyBytes(kSecRandomDefault, length, UnsafeMutablePointer<UInt8>(data.mutableBytes))
like image 182
Daniel Avatar answered Oct 15 '22 11:10

Daniel


Swift 5

let count: Int = <byteCount>
var data = Data(count: count)
let result = data.withUnsafeMutableBytes {    
    SecRandomCopyBytes(kSecRandomDefault, count, $0.baseAddress!) 
}

Swift 4:

var data = Data(count: <count>)
let result = data.withUnsafeMutableBytes { mutableBytes in
    SecRandomCopyBytes(kSecRandomDefault, data.count, mutableBytes)
}
like image 9
Ondrej Stocek Avatar answered Oct 15 '22 11:10

Ondrej Stocek


Swift 4 version:

let count = 16
var data = Data(count: count)
_ = data.withUnsafeMutableBytes {
    SecRandomCopyBytes(kSecRandomDefault, count, $0)
}
like image 3
sundance Avatar answered Oct 15 '22 12:10

sundance