Skip to content

Instantly share code, notes, and snippets.

@prat14k
Forked from khanlou/MD5StringTest.swift
Created March 19, 2019 09:26
Show Gist options
  • Save prat14k/28c4a936e8ac74e25d1009857d64b5a2 to your computer and use it in GitHub Desktop.
Save prat14k/28c4a936e8ac74e25d1009857d64b5a2 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()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment