Created
September 22, 2020 00:13
-
-
Save divyeshmakwana96/62c97117b8ceed3b43f26e470280b438 to your computer and use it in GitHub Desktop.
MD5 and SHA1 with CommonCrypto in Swift 5.0
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 Foundation | |
import CommonCrypto | |
extension String { | |
func sha1() -> [UInt8] { | |
let data = Data(string.utf8) | |
var digest = [UInt8](repeating: 0, count:Int(CC_SHA1_DIGEST_LENGTH)) | |
data.withUnsafeBytes { _ = CC_SHA1($0.baseAddress, CC_LONG(data.count), &digest) } | |
return digest | |
} | |
func sha1String() -> String { | |
return sha1().map { String(format: "%02x", $0) }.joined() | |
} | |
func md5() -> [UInt8] { | |
let data = Data(string.utf8) | |
var digest = [UInt8](repeating: 0, count:Int(CC_MD5_DIGEST_LENGTH)) | |
data.withUnsafeBytes { _ = CC_MD5($0.baseAddress, CC_LONG(data.count), &digest) } | |
return digest | |
} | |
func md5String() -> String { | |
return md5().map { String(format: "%02x", $0) }.joined() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment