Last active
April 12, 2019 09:18
-
-
Save khanlou/baf60dd62601b879eeba209943b04973 to your computer and use it in GitHub Desktop.
MD5 and SHA1 on String in Swift 3
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import XCTest | |
@testable import <#project#> | |
class StringMD5Test: XCTestCase { | |
func testMD5() { | |
let string = "soroush khanlou" | |
XCTAssertEqual(string.md5, "954d741d14b14002d1ba88f600eee635") | |
} | |
func testSHA1() { | |
let string = "soroush khanlou" | |
XCTAssertEqual(string.sha1, "fceb4911d567baae6c2027b3024e3b03175450d3") | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// Use this file to import your target's public headers that you would like to expose to Swift. | |
// | |
#import <CommonCrypto/CommonCrypto.h> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extension String { | |
var md5: String? { | |
guard let data = self.data(using: String.Encoding.utf8) else { return nil } | |
let hash = data.withUnsafeBytes { (bytes: UnsafePointer<Data>) -> [UInt8] in | |
var hash: [UInt8] = [UInt8](repeating: 0, count: Int(CC_MD5_DIGEST_LENGTH)) | |
CC_MD5(bytes, CC_LONG(data.count), &hash) | |
return hash | |
} | |
return hash.map { String(format: "%02x", $0) }.joined() | |
} | |
var sha1: String? { | |
guard let data = self.data(using: String.Encoding.utf8) else { return nil } | |
let hash = data.withUnsafeBytes { (bytes: UnsafePointer<Data>) -> [UInt8] in | |
var hash: [UInt8] = [UInt8](repeating: 0, count: Int(CC_SHA1_DIGEST_LENGTH)) | |
CC_SHA1(bytes, CC_LONG(data.count), &hash) | |
return hash | |
} | |
return hash.map { String(format: "%02x", $0) }.joined() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
no longer needed to import
CommonCrypto
in the bridging header. now you can justimport CommonCrypto
in your swift source code