OC获取文件MD5值与swift字符串MD5加密方法

前端之家收集整理的这篇文章主要介绍了OC获取文件MD5值与swift字符串MD5加密方法前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

OC:

使用前需先#import<CommonCrypto/CommonDigest.h>

//path为文件路径

+(NSString *)getImageMD5:(NSString *)path{

NSFileHandle *handle = [NSFileHandle fileHandleForReadingAtPath:path];

if( handle== nil ) {

return nil;

}

CC_MD5_CTX md5;

CC_MD5_Init(&md5);

BOOL done = NO;

while(!done)

{

NSData* fileData = [handle readDataOfLength: 256 ];

CC_MD5_Update(&md5,[fileData bytes],[fileData length]);

if( [fileData length] == 0 ) done = YES;

}

unsigned char digest[CC_MD5_DIGEST_LENGTH];

CC_MD5_Final(digest,&md5);

NSString* s = [NSString stringWithFormat: @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",

digest[0],digest[1],

digest[2],digest[3],

digest[4],digest[5],

digest[6],digest[7],

digest[8],digest[9],

digest[10],digest[11],

digest[12],digest[13],

digest[14],digest[15]];

return s;

}

swift:

使用方法,1,在header文件导入<CommonCrypto/CommonDigest.h>

2,在任意swift类中添加下边的方法

3,调用var fielad :NSString = 字符串.md5()

//字符串MD5加密

extension String{

func md5() ->String!{

let str = self.cStringUsingEncoding(NSUTF8StringEncoding)

let strLen = CUnsignedInt(self.lengthOfBytesUsingEncoding(NSUTF8StringEncoding))

let digestLen = Int(CC_MD5_DIGEST_LENGTH)

let result = UnsafeMutablePointer<CUnsignedChar>.alloc(digestLen)

CC_MD5(str!,strLen,result)

var hash = NSMutableString()

for i in 0 ..< digestLen {

hash.appendFormat("%02x",result[i])

}

result.destroy()

return String(format: hash as String)

}

}

原文链接:https://www.f2er.com/swift/324253.html

猜你在找的Swift相关文章