Get just the hash from SHA256.hash(data:)?

Viewed 767

I'm trying to get just a hash from SHA256.hash(data:) but in order to do this I need to grab the description and then use .replacingOccurrences(of: "SHA256 digest: ", with: ""). Is there a way that I can just get the full SHA256 hash as a string?

func getId<T>(input: T) -> String {
    let input = "\(input)".utf8
    let data = Data(input)
        
    let hash = SHA256.hash(data: data).description.replacingOccurrences(of: "SHA256 digest: ", with: "")
        
    return hash
}
1 Answers

You can simply map SHA256Digest bytes into an hexa string:

import CryptoKit

extension UnsignedInteger where Self: CVarArg {
    var hexa: String { .init(format: "%ll*0x", bitWidth / 4, self) }
}

extension DataProtocol {
    var sha256Digest: SHA256Digest { SHA256.hash(data: self) }
    var sha256Data: Data { .init(sha256Digest) }
    var sha256Hexa: String { sha256Digest.map(\.hexa).joined() }
}

func getId<D: DataProtocol>(data: D) -> String {
    data.sha256Hexa
}
Related