基於Swift的iOS應用程序開發:對字符串進行MD5加密

1、創建橋街頭文件

首先,我們需要建立Swift與Objective-C的橋街頭文件,詳細建立過程請點擊以下鏈接:

基於Swift的iOS應用程序開發:創建Swift與Objective-C之間的橋街頭文件

2、引入Objective-C庫

在橋街頭文件中,引入相關的庫:
#import <CommonCrypto/CommonDigest.h>

3、編寫加密方法

這一步非常簡單了,直接貼上源代碼:
func md5String(strIn:String) ->String{
    let str = strIn.cString(using: String.Encoding.utf8)
    let strLen = CC_LONG(strIn.lengthOfBytes(using: String.Encoding.utf8))
    let digestLen = Int(CC_MD5_DIGEST_LENGTH)
    let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen);
        
    CC_MD5(str!, strLen, result);
        
    let hash = NSMutableString();
    for i in 0 ..< digestLen {
        hash.appendFormat("%02x", result[i]);
    }
    result.deinitialize();
        
    return String(format: hash as String)
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章