Blake2 is a cryptographic hash function. https://www.blake2.net/
Let’s now explore how to implement this algorithm in Swift. The first option is to find the test vectors and implement the algorithm in Swift. A second option is to find reliable c code and wrap it in a swift package. (http://trikalabs.com/how-to-wrap-c-code-in-a-swift-package/)
In our Cardano wallet side project we explore the second option. We use the c code from https://github.com/BLAKE2/BLAKE2 and we wrap in a swift package.
https://github.com/arnot-project/swift-blake2b-224
We grabbed also the opportunity to provide a simpler api and handling the memory management also.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
import Foundation import Blake2bC public struct Blake2b { public init() {} public func computeHash(_ input: [UInt8]) -> [UInt8] { let capacity = 28 let inputPointer = UnsafeMutablePointer<UInt8>.allocate(capacity: input.count) let output = UnsafeMutablePointer<UInt8>.allocate(capacity: capacity) var pkCopy: [UInt8] = Array(repeating: 0, count: capacity) for i in 0..<input.count { (inputPointer + i).initialize(to: input[i]) } for i in 0..<capacity { (output + i).initialize(to: 0) } blake2b(output, capacity, inputPointer, input.count, nil, 0) for index in 0..<pkCopy.count { pkCopy[index] = (output + index).pointee } output.deallocate() inputPointer.deallocate() return pkCopy } } |