struct MD5Utility {
static func getMD5FromString(string: String) -> NSMutableString {
let original = string.cStringUsingEncoding(NSUTF8StringEncoding)
let digest = UnsafeMutablePointer.alloc(16)
let length = UInt32(strlen(original!))
CC_MD5(original!, length, digest)
return getMD5Str(digest)
}
static func getMD5FromData(data: NSData) ->NSMutableString {
let original = data.bytes
let ori = unsafeBitCast(original, UnsafePointer.self)
let MD5Length = Int(CC_MD5_DIGEST_LENGTH)
let digest = UnsafeMutablePointer.alloc(MD5Length)
let length = UInt32(strlen(ori))
CC_MD5(original, length, digest)
return getMD5Str(digest)
}
static func getMD5FromFilePath(path: String) -> NSMutableString {
let handel = NSFileHandle(forReadingAtPath: path)
if handel == nil {
print("failed")
return NSMutableString(string: "file is not opened")
}
// 先声明一个context上下文
var context = CC_MD5_CTX()
// 初始化一个上下文
CC_MD5_Init(&context)
var done = true
while done {
var data = handel?.readDataOfLength(1024)
// 对上下文进行更新
CC_MD5_Update(&context, &data, UInt32((data?.length)!))
if data?.length == 0 {
done = false
}
}
let digest = UnsafeMutablePointer.alloc(16)
// 最终确定上下文
CC_MD5_Final(digest, &context)
return getMD5Str(digest)
}
private static func getMD5Str(digest: UnsafeMutablePointer) -> NSMutableString {
let md5String = NSMutableString(capacity: 16 * 2)
for index in 0..<16 {
md5String.appendFormat("%02x", digest[index])
}
digest.destroy()
return md5String
}
}