user3697446 user3697446 - 4 months ago 38
Swift Question

Swift Equivant to Python's - hash.digest().encode('base64').strip()?

Basically I'm trying to convert my Python code to Swift, and can't seem to find an equivalent/alternative for this line of code (md5 Hash Digest to base64):

return hash.digest().encode('base64').strip()


Source: http://stackoverflow.com/a/32041572/3697446

It returns a 24-character String, which is exactly what is needed for my usage. I tried using this for base64 but creates a string much to long (I'm guessing because it was base64 encoding the hexdigest rather than digest?):

func toBase64(url: String) -> String{
let data = url.dataUsingEncoding(NSUTF8StringEncoding)
return data!.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0))
}


This is my md5 set up (with bridging header for CommonCrypto/CommonCrypto.h):

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

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

return digestHex
}


any help is much appricieated!

Answer

As you are saying yourself, your md5(string:) is an equivalent to hexdigest, not digest. The result of md5 digest is a byte sequence, and you'd better hold it in NSData in Swift.

With defining this:

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

    let digestData = NSData(bytes: digest, length: Int(CC_MD5_DIGEST_LENGTH))

    return digestData
}

You can write something like this:

let result = md5Data(string: "test").base64EncodedStringWithOptions([])
print(result) //->"CY9rzUYh03PK3k6DJie09g=="
Comments