priore

MD5 and SH1 Digest

May 5th, 2018
106
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // remembers to import in Bridging-Header.h :
  2. // #import <CommonCrypto/CommonDigest.h>
  3.  
  4. extension String {
  5.  
  6.     public func sha1() -> Data? {
  7.        
  8.         guard let messageData = self.data(using:.utf8) else {
  9.             return nil
  10.         }
  11.        
  12.         var digestData = Data(count: Int(CC_SHA1_DIGEST_LENGTH))
  13.        
  14.         _ = digestData.withUnsafeMutableBytes {digestBytes in
  15.             messageData.withUnsafeBytes {messageBytes in
  16.                 CC_SHA1(messageBytes, CC_LONG(messageData.count), digestBytes)
  17.             }
  18.         }
  19.        
  20.         return digestData
  21.     }
  22.    
  23.     public func md5() -> Data? {
  24.        
  25.         guard let messageData = self.data(using:.utf8) else {
  26.             return nil
  27.         }
  28.        
  29.         var digestData = Data(count: Int(CC_MD5_DIGEST_LENGTH))
  30.        
  31.         _ = digestData.withUnsafeMutableBytes {digestBytes in
  32.             messageData.withUnsafeBytes {messageBytes in
  33.                 CC_MD5(messageBytes, CC_LONG(messageData.count), digestBytes)
  34.             }
  35.         }
  36.        
  37.         return digestData
  38.     }
  39. }
RAW Paste Data