Damien Bannerot Damien Bannerot - 3 months ago 130
Swift Question

Hash string with SHA512 in swift

Anyone knows how to reproduce PHP hashing method hash(‘SHA512’, $value, true) in swift ? I tried to use CommonCrypto C library with this code :

extension String {
func digest(length:Int32, gen:(data: UnsafePointer<Void>, len: CC_LONG, md: UnsafeMutablePointer<UInt8>) -> UnsafeMutablePointer<UInt8>) -> String {
var cStr = [UInt8](self.utf8)
var result = [UInt8](count:Int(length), repeatedValue:0)
gen(data: &cStr, len: CC_LONG(cStr.count), md: &result)
let output = NSMutableString(capacity:Int(length))
for r in result {
output.appendFormat("%02x", r)
}
return String(output)
}
}


and used it like this :

var digest = salted.digest(CC_SHA512_DIGEST_LENGTH, gen: {(data, len, md) in CC_SHA512(data,len,md)})


But I don't get the right output

EDIT :

I have some PHP code :

echo base64_encode(hash('sha512', '8yOrBmkd', true)); // output: rlltLWeWaQCrfNTYMa0CcIs0mfLoHGAynrd+d8H65+rGAzHS/BSWsumwSmcxF9aAG9TIzXx+HOjArPyLL3herg==


And I want my swift code to output the same. The Base64 encoding is ok :

let utf8str = input.dataUsingEncoding(NSUTF8StringEncoding)!.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
let base64Encoded = utf8str!.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
print("Encoded: \(base64Encoded)")


But the hashing part return an output the same value as this PHP code :

echo base64_encode(hash('sha512', '8yOrBmkd', false)); // output: YWU1OTZkMmQ2Nzk2NjkwMGFiN2NkNGQ4MzFhZDAyNzA4YjM0OTlmMmU4MWM2MDMyOWViNzdlNzdjMWZhZTdlYWM2MDMzMWQyZmMxNDk2YjJlOWIwNGE2NzMxMTdkNjgwMWJkNGM4Y2Q3YzdlMWNlOGMwYWNmYzhiMmY3ODVlYWU=

Answer

The code does not need to be so complex or an extension:

func sha512Hex(string string: String) -> String {
    var digest = [UInt8](count: Int(CC_SHA512_DIGEST_LENGTH), repeatedValue: 0)
    if let data = string.dataUsingEncoding(NSUTF8StringEncoding) {
        CC_SHA512(data.bytes, CC_LONG(data.length), &digest)
    }

    var digestHex = ""
    for index in 0..<Int(CC_SHA512_DIGEST_LENGTH) {
        digestHex += String(format: "%02x", digest[index])
    }

    return digestHex
}

//Test:

let hexDigest = sha512Hex(string:"8yOrBmkd")
print("hexDigest:\n\(hexDigest)")

Output:

hexDigest: ae596d2d67966900ab7cd4d831ad02708b3499f2e81c60329eb77e77c1fae7eac60331d2fc1496b2e9b04a673117d6801bd4c8cd7c7e1ce8c0acfc8b2f785eae

Just returing the byte array:

func sha512(string string: String) -> [UInt8] {
    var digest = [UInt8](count: Int(CC_SHA512_DIGEST_LENGTH), repeatedValue: 0)
    let data = string.dataUsingEncoding(NSUTF8StringEncoding)!
    CC_SHA512(data.bytes, CC_LONG(data.length), &digest)

    return digest
}

//Test:

let digestRaw = sha512(string:"8yOrBmkd")
print("decimal array:\n\(digestRaw)")
print("hexadecimal:\n\(NSData(bytes:digestRaw, length:digestRaw.count).description)")

Output:

decimal array: [174, 89, 109, 45, 103, 150, 105, 0, 171, 124, 212, 216, 49, 173, 2, 112, 139, 52, 153, 242, 232, 28, 96, 50, 158, 183, 126, 119, 193, 250, 231, 234, 198, 3, 49, 210, 252, 20, 150, 178, 233, 176, 74, 103, 49, 23, 214, 128, 27, 212, 200, 205, 124, 126, 28, 232, 192, 172, 252, 139, 47, 120, 94, 174]

hexadecimal:
ae596d2d67966900ab7cd4d831ad02708b3499f2e81c60329eb77e77c1fae7eac60331d2fc1496b2e9b04a673117d6801bd4c8cd7c7e1ce8c0acfc8b2f785eae

Base64 output:

func sha512Base64(string string: String) -> String {
    let digest = NSMutableData(length: Int(CC_SHA512_DIGEST_LENGTH))!
    if let data = string.dataUsingEncoding(NSUTF8StringEncoding) {
        CC_SHA512(data.bytes, CC_LONG(data.length), UnsafeMutablePointer<UInt8>(digest.mutableBytes))
    }
    return digest.base64EncodedStringWithOptions(NSDataBase64EncodingOptions([]))
}

//Test:

let digestBase64 = sha512Base64(string:"8yOrBmkd")
print("Base64:\n\(digestBase64)")

Output:

Base64: rlltLWeWaQCrfNTYMa0CcIs0mfLoHGAynrd+d8H65+rGAzHS/BSWsumwSmcxF9aAG9TIzXx+HOjArPyLL3herg==