如何使用ios swift将字符串转换为MD5哈希

时间:2022-10-28 17:29:42

I want to convert user input or assume any string like "abc" to MD5 hash. I want to do this in ios swift. I have refered the below links but the solutions are not working for me or I am confused to implement it properly as i am new to swift programing. Could someone help me with clear steps to achieve this. Thanks in advance!

我想要转换用户输入或假设任何字符串,如“abc”到MD5散列。我想在ios swift中做这个。我已经参考了下面的链接,但是解决方案并不适合我,或者我对正确地实现它感到困惑,因为我是swift编程的新手。是否有人能帮助我明确的步骤来实现这一点。提前谢谢!

Importing CommonCrypto in a Swift framework

在Swift框架中导入CommonCrypto

How to use CC_MD5 method in swift language.

如何在swift语言中使用CC_MD5方法。

http://iosdeveloperzone.com/2014/10/03/using-commoncrypto-in-swift/

http://iosdeveloperzone.com/2014/10/03/using-commoncrypto-in-swift/

To be more clear i want to achieve this in swift like what we do in php.

更明确地说,我希望用swift实现这一点,就像我们在php中所做的那样。

$str = "Hello";

echo md5($str);

Output: 8b1a9953c4611296a827abf8c47804d7

输出:8 b1a9953c4611296a827abf8c47804d7

7 个解决方案

#1


107  

There are two steps:
1. Create md5 data from a string
2. Covert the md5 data to a hex string

有两个步骤:1。从字符串2中创建md5数据。将md5数据转换为十六进制字符串

Swift 2.0

斯威夫特2.0

func md5(string string: String) -> String {
    var digest = [UInt8](count: Int(CC_MD5_DIGEST_LENGTH), repeatedValue: 0)
    if let data = string.dataUsingEncoding(NSUTF8StringEncoding) {
        CC_MD5(data.bytes, CC_LONG(data.length), &digest)
    }

    var digestHex = ""
    for index in 0..<Int(CC_MD5_DIGEST_LENGTH) {
        digestHex += String(format: "%02x", digest[index])
    }

    return digestHex
}

//Test:
let digest = md5(string:"Hello")
print("digest: \(digest)")

Output:

输出:

digest: 8b1a9953c4611296a827abf8c47804d7

文摘:8 b1a9953c4611296a827abf8c47804d7

Swift 3.0:

斯威夫特3.0:

func MD5(string: String) -> Data {
    let messageData = string.data(using:.utf8)!
    var digestData = Data(count: Int(CC_MD5_DIGEST_LENGTH))

    _ = digestData.withUnsafeMutableBytes {digestBytes in
        messageData.withUnsafeBytes {messageBytes in
            CC_MD5(messageBytes, CC_LONG(messageData.count), digestBytes)
        }
    }

    return digestData
}

//Test:
let md5Data = MD5(string:"Hello")

let md5Hex =  md5Data.map { String(format: "%02hhx", $0) }.joined()
print("md5Hex: \(md5Hex)")

let md5Base64 = md5Data.base64EncodedString()
print("md5Base64: \(md5Base64)")

Output:

输出:

md5Hex: 8b1a9953c4611296a827abf8c47804d7
md5Base64: ixqZU8RhEpaoJ6v4xHgE1w==

md5Hex:8 b1a9953c4611296a827abf8c47804d7 md5Base64:ixqZU8RhEpaoJ6v4xHgE1w = =

Notes:
#import <CommonCrypto/CommonCrypto.h> must be added to a Bridging-Header file

注:# < CommonCrypto / CommonCrypto进口。h>必须添加到桥头文件中

For how to create a Bridging-Header see this SO answer.

关于如何创建Bridging-Header,请参见这个答案。

In general MD5 should not be used for new work, SHA256 is a current best practice.

一般来说,MD5不应该用于新工作,SHA256是当前的最佳实践。

Example from deprecated documentation section:

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

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

These functions will hash either String or Data input with one of eight cryptographic hash algorithms.

这些函数将使用8种加密哈希算法中的一种对字符串或数据输入进行哈希。

The name parameter specifies the hash function name as a String
Supported functions are MD2, MD4, MD5, SHA1, SHA224, SHA256, SHA384 and SHA512 a This example requires Common Crypto
It is necessary to have a bridging header to the project:
#import <CommonCrypto/CommonCrypto.h>
Add the Security.framework to the project.

name参数指定哈希函数名,因为字符串支持的函数是MD2、MD4、MD5、SHA1、SHA224、SHA256、SHA384和SHA512。h>将Security.framework添加到项目中。



This function takes a hash name and String to be hashed and returns a Data:

此函数接受哈希名和字符串进行哈希并返回数据:

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)
}

Examples:

例子:

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)")

Output:

输出:

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

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

#2


24  

SWIFT 3 version of md5 function:

SWIFT 3版本的md5功能:

func md5(_ string: String) -> String {

    let context = UnsafeMutablePointer<CC_MD5_CTX>.allocate(capacity: 1)
    var digest = Array<UInt8>(repeating:0, count:Int(CC_MD5_DIGEST_LENGTH))
    CC_MD5_Init(context)
    CC_MD5_Update(context, string, CC_LONG(string.lengthOfBytes(using: String.Encoding.utf8)))
    CC_MD5_Final(&digest, context)
    context.deallocate(capacity: 1)
    var hexString = ""
    for byte in digest {
        hexString += String(format:"%02x", byte)
    }

    return hexString
}

Original link from http://iosdeveloperzone.com

从http://iosdeveloperzone.com原始链接

#3


13  

I just released a pure Swift implementation that does not depend on CommonCrypto or anything else.

我刚刚发布了一个纯粹的Swift实现,它不依赖于CommonCrypto或其他任何东西。

It's a single file that you can just drop into your project–or use the contained Xcode project with framework target.

它是一个文件,您可以直接放入项目中,或者使用包含的带有framework target的Xcode项目。

It's also simple to use:

使用起来也很简单:

let input = "The quick brown fox jumps over the lazy dog"
let digest = input.utf8.md5
print("md5: \(digest)")

prints: md5: 9e107d9d372bb6826bd81d3542a419d6

打印:md5:9 e107d9d372bb6826bd81d3542a419d6

#4


10  

Just two notes here:

只是两个笔记:

Using Crypto is too much overhead for achieving just this.

使用加密对实现这个目标来说开销太大。

The accepted answer is perfect! Nevertheless I just wanted to share a Swift ier code approach using Swift 2.2.

公认的答案是完美的!尽管如此,我还是想分享一种使用Swift 2.2的Swift ier代码方法。

Please bear in mind that you still have to #import <CommonCrypto/CommonCrypto.h> in your Bridging-Header file

请记住,您仍然需要#import

struct MD5Digester {
    // return MD5 digest of string provided
    static func digest(string: String) -> String? {

        guard let data = string.dataUsingEncoding(NSUTF8StringEncoding) else { return nil }

        var digest = [UInt8](count: Int(CC_MD5_DIGEST_LENGTH), repeatedValue: 0)

        CC_MD5(data.bytes, CC_LONG(data.length), &digest)

        return (0..<Int(CC_MD5_DIGEST_LENGTH)).reduce("") { $0 + String(format: "%02x", digest[$1]) }
    }
}

#5


5  

Here's an extension based on zaph answer

这是一个基于zaph答案的扩展

extension String{
    var MD5:String {
        get{
            let messageData = self.data(using:.utf8)!
            var digestData = Data(count: Int(CC_MD5_DIGEST_LENGTH))

            _ = digestData.withUnsafeMutableBytes {digestBytes in
                messageData.withUnsafeBytes {messageBytes in
                    CC_MD5(messageBytes, CC_LONG(messageData.count), digestBytes)
                }
            }

            return digestData.map { String(format: "%02hhx", $0) }.joined()
        }
    }
}

Fully compatible with swift 3.0.you still have to #import <CommonCrypto/CommonCrypto.h> in your Bridging-Header file

完全兼容swift 3.0。您仍然需要#import

#6


1  

I used Carthage and Cyrpto to do this.

我用迦太基和Cyrpto做这个。

  1. Install Carthage if you've not already done so

    如果还没有安装Carthage,请安装它

  2. Install Crypto into your project

    在项目中安装加密

  3. execute 'cartage update'

    执行“运费更新”

  4. If you're running from the commandline add in the framework in the swift file

    如果您正在运行命令行,请在swift文件中添加框架

    #!/usr/bin/env xcrun swift -F Carthage/Build/Mac
    
  5. Add import Crypto to your swift file.

    向您的swift文件添加导入加密。

  6. then it just works!

    那只是工作!

    print( "convert this".MD5 )
    

#7


0  

MD5 is a hashing algorithm, no need to use the bulky CommonCrypto library for this (and get rejected by Apple review), just use any md5 hashing library.

MD5是一种散列算法,不需要为此使用庞大的CommonCrypto库(被Apple review拒绝),只需使用任何MD5散列库。

One such library I use is SwiftHash, a pure swift implementation of MD5 (based on http://pajhome.org.uk/crypt/md5/md5.html)

我使用的一个这样的库是SwiftHash,它是MD5的一个纯粹的快速实现(基于http://pajhome.org.uk/crypt/md5 .html)

#1


107  

There are two steps:
1. Create md5 data from a string
2. Covert the md5 data to a hex string

有两个步骤:1。从字符串2中创建md5数据。将md5数据转换为十六进制字符串

Swift 2.0

斯威夫特2.0

func md5(string string: String) -> String {
    var digest = [UInt8](count: Int(CC_MD5_DIGEST_LENGTH), repeatedValue: 0)
    if let data = string.dataUsingEncoding(NSUTF8StringEncoding) {
        CC_MD5(data.bytes, CC_LONG(data.length), &digest)
    }

    var digestHex = ""
    for index in 0..<Int(CC_MD5_DIGEST_LENGTH) {
        digestHex += String(format: "%02x", digest[index])
    }

    return digestHex
}

//Test:
let digest = md5(string:"Hello")
print("digest: \(digest)")

Output:

输出:

digest: 8b1a9953c4611296a827abf8c47804d7

文摘:8 b1a9953c4611296a827abf8c47804d7

Swift 3.0:

斯威夫特3.0:

func MD5(string: String) -> Data {
    let messageData = string.data(using:.utf8)!
    var digestData = Data(count: Int(CC_MD5_DIGEST_LENGTH))

    _ = digestData.withUnsafeMutableBytes {digestBytes in
        messageData.withUnsafeBytes {messageBytes in
            CC_MD5(messageBytes, CC_LONG(messageData.count), digestBytes)
        }
    }

    return digestData
}

//Test:
let md5Data = MD5(string:"Hello")

let md5Hex =  md5Data.map { String(format: "%02hhx", $0) }.joined()
print("md5Hex: \(md5Hex)")

let md5Base64 = md5Data.base64EncodedString()
print("md5Base64: \(md5Base64)")

Output:

输出:

md5Hex: 8b1a9953c4611296a827abf8c47804d7
md5Base64: ixqZU8RhEpaoJ6v4xHgE1w==

md5Hex:8 b1a9953c4611296a827abf8c47804d7 md5Base64:ixqZU8RhEpaoJ6v4xHgE1w = =

Notes:
#import <CommonCrypto/CommonCrypto.h> must be added to a Bridging-Header file

注:# < CommonCrypto / CommonCrypto进口。h>必须添加到桥头文件中

For how to create a Bridging-Header see this SO answer.

关于如何创建Bridging-Header,请参见这个答案。

In general MD5 should not be used for new work, SHA256 is a current best practice.

一般来说,MD5不应该用于新工作,SHA256是当前的最佳实践。

Example from deprecated documentation section:

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

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

These functions will hash either String or Data input with one of eight cryptographic hash algorithms.

这些函数将使用8种加密哈希算法中的一种对字符串或数据输入进行哈希。

The name parameter specifies the hash function name as a String
Supported functions are MD2, MD4, MD5, SHA1, SHA224, SHA256, SHA384 and SHA512 a This example requires Common Crypto
It is necessary to have a bridging header to the project:
#import <CommonCrypto/CommonCrypto.h>
Add the Security.framework to the project.

name参数指定哈希函数名,因为字符串支持的函数是MD2、MD4、MD5、SHA1、SHA224、SHA256、SHA384和SHA512。h>将Security.framework添加到项目中。



This function takes a hash name and String to be hashed and returns a Data:

此函数接受哈希名和字符串进行哈希并返回数据:

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)
}

Examples:

例子:

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)")

Output:

输出:

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

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

#2


24  

SWIFT 3 version of md5 function:

SWIFT 3版本的md5功能:

func md5(_ string: String) -> String {

    let context = UnsafeMutablePointer<CC_MD5_CTX>.allocate(capacity: 1)
    var digest = Array<UInt8>(repeating:0, count:Int(CC_MD5_DIGEST_LENGTH))
    CC_MD5_Init(context)
    CC_MD5_Update(context, string, CC_LONG(string.lengthOfBytes(using: String.Encoding.utf8)))
    CC_MD5_Final(&digest, context)
    context.deallocate(capacity: 1)
    var hexString = ""
    for byte in digest {
        hexString += String(format:"%02x", byte)
    }

    return hexString
}

Original link from http://iosdeveloperzone.com

从http://iosdeveloperzone.com原始链接

#3


13  

I just released a pure Swift implementation that does not depend on CommonCrypto or anything else.

我刚刚发布了一个纯粹的Swift实现,它不依赖于CommonCrypto或其他任何东西。

It's a single file that you can just drop into your project–or use the contained Xcode project with framework target.

它是一个文件,您可以直接放入项目中,或者使用包含的带有framework target的Xcode项目。

It's also simple to use:

使用起来也很简单:

let input = "The quick brown fox jumps over the lazy dog"
let digest = input.utf8.md5
print("md5: \(digest)")

prints: md5: 9e107d9d372bb6826bd81d3542a419d6

打印:md5:9 e107d9d372bb6826bd81d3542a419d6

#4


10  

Just two notes here:

只是两个笔记:

Using Crypto is too much overhead for achieving just this.

使用加密对实现这个目标来说开销太大。

The accepted answer is perfect! Nevertheless I just wanted to share a Swift ier code approach using Swift 2.2.

公认的答案是完美的!尽管如此,我还是想分享一种使用Swift 2.2的Swift ier代码方法。

Please bear in mind that you still have to #import <CommonCrypto/CommonCrypto.h> in your Bridging-Header file

请记住,您仍然需要#import

struct MD5Digester {
    // return MD5 digest of string provided
    static func digest(string: String) -> String? {

        guard let data = string.dataUsingEncoding(NSUTF8StringEncoding) else { return nil }

        var digest = [UInt8](count: Int(CC_MD5_DIGEST_LENGTH), repeatedValue: 0)

        CC_MD5(data.bytes, CC_LONG(data.length), &digest)

        return (0..<Int(CC_MD5_DIGEST_LENGTH)).reduce("") { $0 + String(format: "%02x", digest[$1]) }
    }
}

#5


5  

Here's an extension based on zaph answer

这是一个基于zaph答案的扩展

extension String{
    var MD5:String {
        get{
            let messageData = self.data(using:.utf8)!
            var digestData = Data(count: Int(CC_MD5_DIGEST_LENGTH))

            _ = digestData.withUnsafeMutableBytes {digestBytes in
                messageData.withUnsafeBytes {messageBytes in
                    CC_MD5(messageBytes, CC_LONG(messageData.count), digestBytes)
                }
            }

            return digestData.map { String(format: "%02hhx", $0) }.joined()
        }
    }
}

Fully compatible with swift 3.0.you still have to #import <CommonCrypto/CommonCrypto.h> in your Bridging-Header file

完全兼容swift 3.0。您仍然需要#import

#6


1  

I used Carthage and Cyrpto to do this.

我用迦太基和Cyrpto做这个。

  1. Install Carthage if you've not already done so

    如果还没有安装Carthage,请安装它

  2. Install Crypto into your project

    在项目中安装加密

  3. execute 'cartage update'

    执行“运费更新”

  4. If you're running from the commandline add in the framework in the swift file

    如果您正在运行命令行,请在swift文件中添加框架

    #!/usr/bin/env xcrun swift -F Carthage/Build/Mac
    
  5. Add import Crypto to your swift file.

    向您的swift文件添加导入加密。

  6. then it just works!

    那只是工作!

    print( "convert this".MD5 )
    

#7


0  

MD5 is a hashing algorithm, no need to use the bulky CommonCrypto library for this (and get rejected by Apple review), just use any md5 hashing library.

MD5是一种散列算法,不需要为此使用庞大的CommonCrypto库(被Apple review拒绝),只需使用任何MD5散列库。

One such library I use is SwiftHash, a pure swift implementation of MD5 (based on http://pajhome.org.uk/crypt/md5/md5.html)

我使用的一个这样的库是SwiftHash,它是MD5的一个纯粹的快速实现(基于http://pajhome.org.uk/crypt/md5 .html)