Last active
April 18, 2018 02:27
-
-
Save dhl613/6acb2faf1f1265acbc06ec31c98ca1f4 to your computer and use it in GitHub Desktop.
MD5编码代码片段 OC实现 Swift实现
This file contains hidden or 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
#### OC版 | |
/// #import <CommonCrypto/CommonDigest.h> | |
/// (Category) | |
- (NSString *)md5 { | |
const char *str = [self UTF8String]; | |
if (str == NULL) { | |
str = ""; | |
} | |
unsigned char r[CC_MD5_DIGEST_LENGTH]; | |
CC_MD5(str, (CC_LONG)strlen(str), r); | |
NSString *md5Str = [NSString stringWithFormat:@"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",r[0],r[1],r[2],r[3],r[4],r[5],r[6],r[7],r[8],r[9],r[10],r[11],r[12],r[13],r[14],r[15]]; | |
return md5Str; | |
} | |
#### Swift版 | |
extension String { | |
func md5() ->String!{ | |
let str = self.cString(using: String.Encoding.utf8) | |
let strLen = CUnsignedInt(self.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.deinitialize() | |
return String(format: hash as String) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment