Skip to content

Instantly share code, notes, and snippets.

@wszdwp
Last active April 8, 2020 11:29
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save wszdwp/58811f685ddcf97a79a3 to your computer and use it in GitHub Desktop.
MD5 Hash in Swift(import #import <CommonCrypto/CommonCrypto.h> in yourapplication_Bridging_Header_h)
// Need to create Bridging_Header file and import <CommonCrypto/CommonCrypto.h>
// How to create YourApplication_Briging_Header file?
// Ref: http://stackoverflow.com/questions/24002369/how-to-call-objective-c-code-from-swift/24005242#24005242
func md5(inputString: String) -> String! {
let str = inputString.cStringUsingEncoding(NSUTF8StringEncoding)
let strLen = CC_LONG(inputString.lengthOfBytesUsingEncoding(NSUTF8StringEncoding))
let digestLen = Int(CC_MD5_DIGEST_LENGTH)
let result = UnsafeMutablePointer<CUnsignedChar>.alloc(digestLen)
CC_MD5(str!, strLen, result)
var hash = NSMutableString()
for i in 0..<digestLen {
hash.appendFormat("%02x", result[i])
}
result.dealloc(digestLen)
return String(format: hash)
}
@iosdeveloper480
Copy link

When i was trying to use your function in my Custom Swift Framework, i get these errors. Would you like to tell me how to get ride of them.
Use of unresolved identifier 'CC_LONG'
Use of unresolved identifier 'CC_MD5_DIGEST_LENGTH'
Use of unresolved identifier 'CC_MD5'

@Afrah-Tayyab
Copy link

updated Code For Swift 4 or >

    **func md5(paramString: String) -> String! {
        let str = paramString.cString(using: String.Encoding.utf8)
        let strLen = CUnsignedInt(paramString.lengthOfBytes(using: String.Encoding.utf8))
        let digestLen = Int(CC_MD5_DIGEST_LENGTH)
        let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen)
        CC_MD5(str!, strLen, result)
        let hash = NSMutableString()
        for i in 0..<digestLen {
            hash.appendFormat("%02x", result[i])
        }
        result.deallocate()

       return String(format: hash as String)
    }**

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment