Create a gist now

Instantly share code, notes, and snippets.

Swift3でStringをMD5に変換する
/* (メモ)
* Bridging-Header.hに
* #import <CommonCrypto/CommonDigest.h>
* を書いておく。
*/
func md5(_ string: String) -> String {
var md5String = ""
let digestLength = Int(CC_MD5_DIGEST_LENGTH)
let md5Buffer = UnsafeMutablePointer<UInt8>.allocate(capacity: digestLength)
if let data = string.data(using: .utf8) {
data.withUnsafeBytes({ (bytes: UnsafePointer<CChar>) -> Void in
CC_MD5(bytes, CC_LONG(data.count), md5Buffer)
md5String = (0..<digestLength).reduce("") { $0 + String(format:"%02x", md5Buffer[$1]) }
})
}
return md5String
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment