Skip to content

Instantly share code, notes, and snippets.

@khanlou
Last active April 12, 2019 09:18
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save khanlou/baf60dd62601b879eeba209943b04973 to your computer and use it in GitHub Desktop.
Save khanlou/baf60dd62601b879eeba209943b04973 to your computer and use it in GitHub Desktop.
MD5 and SHA1 on String in Swift 3
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")
}
}
//
// Use this file to import your target's public headers that you would like to expose to Swift.
//
#import <CommonCrypto/CommonCrypto.h>
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()
}
}
@tkanzakic
Copy link

no longer needed to import CommonCrypto in the bridging header. now you can just import CommonCrypto in your swift source code

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment