Advertisement
Guest User

Untitled

a guest
Oct 19th, 2019
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.82 KB | None | 0 0
  1. import Foundation
  2. import CryptoKit
  3.  
  4. private protocol ByteCountable {
  5. static var byteCount: Int { get }
  6. }
  7.  
  8. extension Insecure.MD5: ByteCountable { }
  9. extension Insecure.SHA1: ByteCountable { }
  10.  
  11. public extension String {
  12.  
  13. func insecureMD5Hash(using encoding: String.Encoding = .utf8) -> String? {
  14. return self.hash(algo: Insecure.MD5.self, using: encoding)
  15. }
  16.  
  17. func insecureSHA1Hash(using encoding: String.Encoding = .utf8) -> String? {
  18. return self.hash(algo: Insecure.SHA1.self, using: encoding)
  19. }
  20.  
  21. private func hash<Hash: HashFunction & ByteCountable>(algo: Hash.Type, using encoding: String.Encoding = .utf8) -> String? {
  22. guard let data = self.data(using: encoding) else {
  23. return nil
  24. }
  25.  
  26. return algo.hash(data: data).prefix(algo.byteCount).map {
  27. String(format: "%02hhx", $0)
  28. }.joined()
  29. }
  30.  
  31. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement