Best way to generate NSData object with random bytes of a specific length?

后端 未结 9 1312
佛祖请我去吃肉
佛祖请我去吃肉 2021-02-05 11:37

If I create a new NSData object of a specific size using dataWithBytes:length:, what is the most efficient way to create the input bytes (20 Mb worth) of random characters, pref

9条回答
  •  臣服心动
    2021-02-05 12:04

    Swift 3:

    import Security
    
    func randomBytes(length: Int) -> Data {
        var data = Data(capacity: length)
        data.withUnsafeMutableBytes { (bytes: UnsafeMutablePointer) -> Void in
            let _ = SecRandomCopyBytes(kSecRandomDefault, length, bytes)
        }
        return data
    }
    

提交回复
热议问题