Skip to content

Commit 2244902

Browse files
committed
Update Data+Extension.swift
1 parent a9b4a46 commit 2244902

File tree

1 file changed

+14
-17
lines changed

1 file changed

+14
-17
lines changed

Sources/Web3Core/Utility/Data+Extension.swift

Lines changed: 14 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@
44
//
55

66
import Foundation
7-
import Metal
87

98
extension Data {
109
init<T>(fromArray values: [T]) {
@@ -42,23 +41,21 @@ extension Data {
4241
}
4342

4443
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+
}
6057
}
61-
return Data(entropyData)
58+
return nil
6259
}
6360

6461
public func bitsInRange(_ startingBit: Int, _ length: Int) -> UInt64? { // return max of 8 bytes for simplicity, non-public

0 commit comments

Comments
 (0)