Joe Scotto
Joe Scotto

Reputation: 10887

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

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
}

Upvotes: 6

Views: 2506

Answers (1)

Leo Dabus
Leo Dabus

Reputation: 236558

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() }
}

extension SHA256Digest {
    var data: Data { .init(self) }
    var hexa: String { map(\.hexa).joined() }
}

extension StringProtocol {
    var data: Data { .init(utf8) }
    var sha256Digest: SHA256Digest { data.sha256Digest }
    var sha256Data: Data { data.sha256Data }
    var sha256Hexa: String { data.sha256Hexa }
}

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

Playground testing

let password = "Pw123456"
let data = password.data
let hashed = data.sha256Digest // SHA256 digest: 47eb07beaa3a9aebec0e2bf52211db44fb5cf894b92c836e7e20aef7f623dfdb
let hashedData = hashed.data  // 32 bytes
let hashedHexa = hashed.hexa  // 47eb07beaa3a9aebec0e2bf52211db44fb5cf894b92c836e7e20aef7f623dfdb"

Upvotes: 7

Related Questions