String+MD5.swift 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. //
  2. // String+MD5.swift
  3. // Kingfisher
  4. //
  5. // To date, adding CommonCrypto to a Swift framework is problematic. See:
  6. // http://stackoverflow.com/questions/25248598/importing-commoncrypto-in-a-swift-framework
  7. // We're using a subset and modified version of CryptoSwift as an alternative.
  8. // The following is an altered source version that only includes MD5. The original software can be found at:
  9. // https://github.com/krzyzanowskim/CryptoSwift
  10. // This is the original copyright notice:
  11. /*
  12. Copyright (C) 2014 Marcin Krzyżanowski <marcin.krzyzanowski@gmail.com>
  13. This software is provided 'as-is', without any express or implied warranty.
  14. In no event will the authors be held liable for any damages arising from the use of this software.
  15. Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions:
  16. - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required.
  17. - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
  18. - This notice may not be removed or altered from any source or binary distribution.
  19. */
  20. import Foundation
  21. import CommonCrypto
  22. extension String: KingfisherCompatible { }
  23. extension Kingfisher where Base == String {
  24. var md5: String {
  25. guard let data = base.data(using: .utf8) else {
  26. return base
  27. }
  28. var digest = [UInt8](repeating: 0, count: Int(CC_MD5_DIGEST_LENGTH))
  29. _ = data.withUnsafeBytes { bytes in
  30. return CC_MD5(bytes, CC_LONG(data.count), &digest)
  31. }
  32. return digest.map { String(format: "%02x", $0) }.joined()
  33. }
  34. }