Last active
March 19, 2018 03:22
-
-
Save dankogai/f1698d85edff8671ae76939d0f3e9b20 to your computer and use it in GitHub Desktop.
CommonCrypto in Swift
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
// | |
// digest.swift | |
// CryptoDigest | |
// | |
// Created by Dan Kogai on 2018/03/19. | |
// Copyright © 2018 Dan Kogai. All rights reserved. | |
// | |
import Foundation | |
import CommonCrypto | |
public enum CryptoAlgorithm { | |
case MD5, SHA1, SHA224, SHA256, SHA384, SHA512 | |
public var digestLength: Int { | |
switch self { | |
case .MD5: return Int(CC_MD5_DIGEST_LENGTH) | |
case .SHA1: return Int(CC_SHA1_DIGEST_LENGTH) | |
case .SHA224: return Int(CC_SHA224_DIGEST_LENGTH) | |
case .SHA256: return Int(CC_SHA256_DIGEST_LENGTH) | |
case .SHA384: return Int(CC_SHA384_DIGEST_LENGTH) | |
case .SHA512: return Int(CC_SHA512_DIGEST_LENGTH) | |
} | |
} | |
public func rawDigest(data: UnsafeRawPointer!, length:Int) -> [CUnsignedChar] { | |
let clen = CC_LONG(length) | |
var result = [CUnsignedChar](repeating: 0, count: self.digestLength) | |
switch self { | |
case .MD5: CC_MD5(data, clen, &result) | |
case .SHA1: CC_SHA1(data, clen, &result) | |
case .SHA224: CC_SHA224(data, clen, &result) | |
case .SHA256: CC_SHA256(data, clen, &result) | |
case .SHA384: CC_SHA384(data, clen, &result) | |
case .SHA512: CC_SHA512(data, clen, &result) | |
} | |
return result | |
} | |
public func hexDigest(data: UnsafeRawPointer!, length:Int) -> String { | |
return self.rawDigest(data:data, length:length) | |
.map{ String(format:"%02hhx", $0) }.joined() | |
} | |
} | |
extension String { | |
public func hexDigest(algorithm: CryptoAlgorithm) -> String { | |
guard let cstr = self.cString(using: String.Encoding.utf8) else { | |
fatalError("UTF-8 conversion failed!") | |
} | |
return algorithm.hexDigest(data: cstr, length: cstr.count - 1) | |
} | |
public var md5: String { return self.hexDigest(algorithm: .MD5) } | |
public var sha1: String { return self.hexDigest(algorithm: .SHA1) } | |
public var sha224: String { return self.hexDigest(algorithm: .SHA224) } | |
public var sha256: String { return self.hexDigest(algorithm: .SHA256) } | |
public var sha384: String { return self.hexDigest(algorithm: .SHA384) } | |
public var sha512: String { return self.hexDigest(algorithm: .SHA512) } | |
} |
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
module CommonCrypto [system] { | |
header "/usr/include/CommonCrypto/CommonCrypto.h" | |
export * | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment