|
4 | 4 | //
|
5 | 5 |
|
6 | 6 | import Foundation
|
7 |
| -import Metal |
8 | 7 |
|
9 | 8 | extension Data {
|
10 | 9 | init<T>(fromArray values: [T]) {
|
@@ -42,23 +41,21 @@ extension Data {
|
42 | 41 | }
|
43 | 42 |
|
44 | 43 | public static func randomBytes(length: Int) -> Data? {
|
45 |
| - let entropy_bit_size = length//128 |
46 |
| - //# valid_entropy_bit_sizes = [128, 160, 192, 224, 256], count: [12, 15, 18, 21, 24] |
47 |
| - var entropy_bytes = [UInt8](repeating: 0, count: entropy_bit_size)// / 8) |
48 |
| - let status = SecRandomCopyBytes(kSecRandomDefault, entropy_bytes.count, &entropy_bytes) |
49 |
| - |
50 |
| - if status != errSecSuccess { // Always test the status. |
51 |
| - } else { |
52 |
| - entropy_bytes = [UInt8](repeating: 0, count: entropy_bit_size)// / 8) |
53 |
| - arc4random_buf(&entropy_bytes, entropy_bytes.count) |
54 |
| - } |
55 |
| - |
56 |
| - let source1 = MTLCreateSystemDefaultDevice()?.makeBuffer(length: length)?.hash.description.data(using: .utf8) |
57 |
| - |
58 |
| - let entropyData = entropy_bytes.shuffled().map{ bit in |
59 |
| - return bit ^ (source1?.randomElement() ?? 0) |
| 44 | + for _ in 0...1024 { |
| 45 | + var data = Data(repeating: 0, count: length) |
| 46 | + let result = data.withUnsafeMutableBytes { (body: UnsafeMutableRawBufferPointer) -> Int32? in |
| 47 | + if let bodyAddress = body.baseAddress, body.count > 0 { |
| 48 | + let pointer = bodyAddress.assumingMemoryBound(to: UInt8.self) |
| 49 | + return SecRandomCopyBytes(kSecRandomDefault, length, pointer) |
| 50 | + } else { |
| 51 | + return nil |
| 52 | + } |
| 53 | + } |
| 54 | + if let notNilResult = result, notNilResult == errSecSuccess { |
| 55 | + return data |
| 56 | + } |
60 | 57 | }
|
61 |
| - return Data(entropyData) |
| 58 | + return nil |
62 | 59 | }
|
63 | 60 |
|
64 | 61 | public func bitsInRange(_ startingBit: Int, _ length: Int) -> UInt64? { // return max of 8 bytes for simplicity, non-public
|
|
0 commit comments