Skip to content

Commit

Permalink
Update Data+Extension.swift
Browse files Browse the repository at this point in the history
  • Loading branch information
pharms-eth committed Mar 6, 2023
1 parent a9b4a46 commit 2244902
Showing 1 changed file with 14 additions and 17 deletions.
31 changes: 14 additions & 17 deletions Sources/Web3Core/Utility/Data+Extension.swift
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
//

import Foundation
import Metal

extension Data {
init<T>(fromArray values: [T]) {
Expand Down Expand Up @@ -42,23 +41,21 @@ extension Data {
}

public static func randomBytes(length: Int) -> Data? {
let entropy_bit_size = length//128
//# valid_entropy_bit_sizes = [128, 160, 192, 224, 256], count: [12, 15, 18, 21, 24]
var entropy_bytes = [UInt8](repeating: 0, count: entropy_bit_size)// / 8)
let status = SecRandomCopyBytes(kSecRandomDefault, entropy_bytes.count, &entropy_bytes)

if status != errSecSuccess { // Always test the status.
} else {
entropy_bytes = [UInt8](repeating: 0, count: entropy_bit_size)// / 8)
arc4random_buf(&entropy_bytes, entropy_bytes.count)
}

let source1 = MTLCreateSystemDefaultDevice()?.makeBuffer(length: length)?.hash.description.data(using: .utf8)

let entropyData = entropy_bytes.shuffled().map{ bit in
return bit ^ (source1?.randomElement() ?? 0)
for _ in 0...1024 {
var data = Data(repeating: 0, count: length)
let result = data.withUnsafeMutableBytes { (body: UnsafeMutableRawBufferPointer) -> Int32? in
if let bodyAddress = body.baseAddress, body.count > 0 {
let pointer = bodyAddress.assumingMemoryBound(to: UInt8.self)
return SecRandomCopyBytes(kSecRandomDefault, length, pointer)
} else {
return nil
}
}
if let notNilResult = result, notNilResult == errSecSuccess {
return data
}
}
return Data(entropyData)
return nil
}

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

0 comments on commit 2244902

Please sign in to comment.