swift md5

swift3 对类型检查严格了

1
2
3
4
5
6
7
8
9
10
11
12
13
14
/// 返回md5 32位小写
var MD5:String {
let cString = self.cString(using: String.Encoding.utf8)
let length = CUnsignedInt(
self.lengthOfBytes(using: String.Encoding.utf8)
)
//let result = UnsafeMutablePointer<CUnsignedChar>(allocatingCapacity: Int(CC_MD5_DIGEST_LENGTH))
let result:UnsafeMutablePointer<CUnsignedChar> = UnsafeMutablePointer.allocate(capacity: (Int(CC_MD5_DIGEST_LENGTH)))
CC_MD5(cString!,length,result)
return String(format:"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
result[0],result[1],result[2],result[3],result[4],result[5],result[6],result[7],result[8],
result[9],result[10],result[11],result[12],result[13],result[14],result[15])
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/**
* 加密系统头
*/
#import <CommonCrypto/CommonDigest.h> 桥接头文件加入
extension String{
/// 返回md5 32位小写
var MD5:String {
let cString = self.cStringUsingEncoding(NSUTF8StringEncoding)
let length = CUnsignedInt(
self.lengthOfBytesUsingEncoding(NSUTF8StringEncoding)
)
let result = UnsafeMutablePointer<CUnsignedChar>.alloc(Int(CC_MD5_DIGEST_LENGTH))
CC_MD5(cString!,length,result)
return String(format:"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
result[0],result[1],result[2],result[3],result[4],result[5],result[6],result[7],result[8],
result[9],result[10],result[11],result[12],result[13],result[14],result[15])
}
}

oc 版本 头文件 <CommonCrypto/CommonDigest.h>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/// md5 小写
- (NSString *)MD5{
const char *cStr = [self UTF8String];
unsigned char result[16];
CC_MD5(cStr, (unsigned)strlen(cStr), result);
return [NSString stringWithFormat:
@"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
result[0], result[1], result[2], result[3],
result[4], result[5], result[6], result[7],
result[8], result[9], result[10], result[11],
result[12], result[13], result[14], result[15]];
}

此方法得到的MD5值中的字母为小写,如果想要大写的MD5值,将@”%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x” 中的x替换成X即可

Author

陈昭

Posted on

2016-08-23

Updated on

2021-12-27

Licensed under

You need to set install_url to use ShareThis. Please set it in _config.yml.
You forgot to set the business or currency_code for Paypal. Please set it in _config.yml.

Kommentare

You forgot to set the shortname for Disqus. Please set it in _config.yml.