Last active
October 19, 2016 03:36
-
-
Save takopom/78461bc5e26fd625e0efb5449dd8fd44 to your computer and use it in GitHub Desktop.
Swift3でStringをMD5に変換する
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* (メモ) | |
* 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