0
iQi - 面白いアプリを開発中
A bridging header with 「#import <CommonCrypto/CommonCrypto.h> 」が必要です。
または、
extension String {
var md5: String! {
let str = self.cStringUsingEncoding(NSUTF8StringEncoding)
let strLen = CC_LONG(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.dealloc(digestLen)
return String(format: hash)
}
}
または、
extension Int {
func hexString() -> String {
return NSString(format:"%02x", self)
}
}
extension NSData {
func hexString() -> String {
var string = String()
for i in UnsafeBufferPointer<UInt8>(start: UnsafeMutablePointer<UInt8>(bytes), count: length) {
string += Int(i).hexString()
}
return string
}
func MD5() -> NSData {
let result = NSMutableData(length: Int(CC_MD5_DIGEST_LENGTH))!
CC_MD5(bytes, CC_LONG(length), UnsafeMutablePointer<UInt8>(result.mutableBytes))
return NSData(data: result)
}
func SHA1() -> NSData {
let result = NSMutableData(length: Int(CC_SHA1_DIGEST_LENGTH))!
CC_SHA1(bytes, CC_LONG(length), UnsafeMutablePointer<UInt8>(result.mutableBytes))
return NSData(data: result)
}
}
extension String {
func MD5() -> String {
return (self as NSString).dataUsingEncoding(NSUTF8StringEncoding)!.MD5().hexString()
}
func SHA1() -> String {
return (self as NSString).dataUsingEncoding(NSUTF8StringEncoding)!.SHA1().hexString()
}
}