Reputation: 349
I found we can hash some string with CommonCrypto. and I see some examples but they don't use salt. how can i use the SHA256 with salt?
Upvotes: 5
Views: 5778
Reputation: 3020
Complete solution for Swift 4:
extension Data {
var hexString: String {
return map { String(format: "%02hhx", $0) }.joined()
}
var sha256: Data {
var digest = [UInt8](repeating: 0, count: Int(CC_SHA256_DIGEST_LENGTH))
self.withUnsafeBytes({
_ = CC_SHA256($0, CC_LONG(self.count), &digest)
})
return Data(bytes: digest)
}
}
extension String {
func sha256(salt: String) -> Data {
return (self + salt).data(using: .utf8)!.sha256
}
}
Example:
let hash = "test".sha256(salt: "salt").hexString
Upvotes: 5
Reputation: 2306
Combine your indata with a salt and run the hash calculation;
func hash(input: String, salt: String) -> String {
let toHash = input + salt
// TODO: Calculate the SHA256 hash of "toHash" and return it
// return sha256(toHash)
// Return the input data and hash for now
return toHash
}
print(hash("somedata", salt: "1m8f")) // Prints "somedata1m8f"
Upvotes: 4