MD2 MD4 MD5 SHA1 SHA224 SHA256 SHA384 SHA512(Swift 3)

這些函式將使用八種加密雜湊演算法之一對 String 或 Data 輸入進行雜湊。

name 引數指定雜湊函式名稱為字串
支援的函式是 MD2,MD4,MD5,SHA1,SHA224,SHA256,SHA384 和 SHA512

此示例需要 Common Crypto
必須為專案提供橋接頭:
#import <CommonCrypto/CommonCrypto.h>
將 Security.framework 新增到專案中。

此函式採用雜湊名稱和要雜湊的資料並返回資料:

name: A name of a hash function as a String  
data: The Data to be hashed  
returns: the hashed result as Data  
func hash(name:String, data:Data) -> Data? {
    let algos = ["MD2":    (CC_MD2,    CC_MD2_DIGEST_LENGTH),
                 "MD4":    (CC_MD4,    CC_MD4_DIGEST_LENGTH),
                 "MD5":    (CC_MD5,    CC_MD5_DIGEST_LENGTH),
                 "SHA1":   (CC_SHA1,   CC_SHA1_DIGEST_LENGTH),
                 "SHA224": (CC_SHA224, CC_SHA224_DIGEST_LENGTH),
                 "SHA256": (CC_SHA256, CC_SHA256_DIGEST_LENGTH),
                 "SHA384": (CC_SHA384, CC_SHA384_DIGEST_LENGTH),
                 "SHA512": (CC_SHA512, CC_SHA512_DIGEST_LENGTH)]
    guard let (hashAlgorithm, length) = algos[name]  else { return nil }
    var hashData = Data(count: `Int(length)`)

    _ = hashData.withUnsafeMutableBytes {digestBytes in
        data.withUnsafeBytes {messageBytes in
            hashAlgorithm(messageBytes, `CC_LONG(data.count)`, digestBytes)
        }
    }
    return hashData
}

此函式接受雜湊名稱和要雜湊的 String 並返回一個資料:

name: A name of a hash function as a String  
string: The String to be hashed  
returns: the hashed result as Data  
func hash(name:String, string:String) -> Data? {
    let data = string.data(using:.utf8)!
    return hash(name:name, data:data)
}

例子:

let clearString = "clearData0123456"
let clearData   = clearString.data(using:.utf8)!
print("clearString: `(clearString)`")
print("clearData: \(clearData as NSData)")

let hashSHA256 = hash(name:"SHA256", string:clearString)
print("hashSHA256: \(hashSHA256! as NSData)")

let hashMD5 = hash(name:"MD5", data:clearData)
print("hashMD5: \(hashMD5! as NSData)")

輸出:

clearString: clearData0123456
clearData: <636c6561 72446174 61303132 33343536>

hashSHA256: <aabc766b 6b357564 e41f4f91 2d494bcc bfa16924 b574abbd ba9e3e9d a0c8920a>
hashMD5: <4df665f7 b94aea69 695b0e7b baf9e9d6>