Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

@tkanzakic tkanzakic commented Nov 28, 2018

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
You can’t perform that action at this time.