Skip to content

Instantly share code, notes, and snippets.

@takopom
Last active October 19, 2016 03:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save takopom/78461bc5e26fd625e0efb5449dd8fd44 to your computer and use it in GitHub Desktop.
Save takopom/78461bc5e26fd625e0efb5449dd8fd44 to your computer and use it in GitHub Desktop.
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