2
0

String+MD5.swift 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. //
  2. // String+MD5.swift
  3. // Kingfisher
  4. //
  5. // Copyright (c) 2017 Wei Wang <onevcat@gmail.com>
  6. //
  7. // Permission is hereby granted, free of charge, to any person obtaining a copy
  8. // of this software and associated documentation files (the "Software"), to deal
  9. // in the Software without restriction, including without limitation the rights
  10. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  11. // copies of the Software, and to permit persons to whom the Software is
  12. // furnished to do so, subject to the following conditions:
  13. //
  14. // The above copyright notice and this permission notice shall be included in
  15. // all copies or substantial portions of the Software.
  16. //
  17. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  18. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  19. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  20. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  21. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  22. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  23. // THE SOFTWARE.
  24. //
  25. // adding CommonCrypto to a Swift framework See:
  26. // http://stackoverflow.com/questions/25248598/importing-commoncrypto-in-a-swift-framework
  27. import Foundation
  28. import CCommonCrypto
  29. public struct StringProxy {
  30. fileprivate let base: String
  31. init(proxy: String) {
  32. base = proxy
  33. }
  34. }
  35. extension String: KingfisherCompatible {
  36. public typealias CompatibleType = StringProxy
  37. public var kf: CompatibleType {
  38. return StringProxy(proxy: self)
  39. }
  40. }
  41. extension StringProxy {
  42. var md5: String {
  43. guard let cStr = base.cString(using: .utf8) else {
  44. return base
  45. }
  46. let bytesLength = CUnsignedInt(base.lengthOfBytes(using: .utf8))
  47. let md5DigestLenth = Int(CC_MD5_DIGEST_LENGTH)
  48. let md5StringPointer = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: md5DigestLenth)
  49. defer {
  50. md5StringPointer.deallocate(capacity: md5DigestLenth)
  51. }
  52. CC_MD5(cStr, bytesLength, md5StringPointer)
  53. var md5String = ""
  54. for i in 0 ..< md5DigestLenth {
  55. md5String = md5String.appendingFormat("%02x", md5StringPointer[i])
  56. }
  57. return md5String
  58. }
  59. }