1

I'm looking for a for a way to generate a md5 hash (or equivalent 32 character) string using only the security module in Xcode 8 with Swift 3. In other words a method that does not require CommonCrypto.

I've only found one post that mentions this approach. This post claims this approach is only for OS X (not iOS).

I know md5 is not super secure but I need compatibility with an older site, so assistance would be greatly appreciated.

Community
  • 1
  • 1
Michael Garito
  • 3,005
  • 1
  • 11
  • 11

1 Answers1

0

What is wrong with CommonCrypto? It is already available on every device, simple, fast and well tested:

extension Data {

    var hexString: String {
        return map { String(format: "%02hhx", $0) }.joined()
    }

    var md5: Data {
        var digest = [Byte](repeating: 0, count: Int(CC_MD5_DIGEST_LENGTH))
        self.withUnsafeBytes({
            _ = CC_MD5($0, CC_LONG(self.count), &digest)
        })
        return Data(bytes: digest)
    }

}

As far as i know the only other possibility to calculate md5 is to add the algorithm by yourself like the one used in CryptoSwift.

sundance
  • 2,930
  • 1
  • 20
  • 25