priore

AES256 decrypt

May 5th, 2018
95
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // remember to import in Bridging-Header.h :
  2. //#import <CommonCrypto/CommonCryptor.h>
  3.  
  4. enum AESError: Error {
  5.         case KeyError((String, Int))
  6.     case IVError((String, Int))
  7.     case CryptorError((String, Int))
  8. }
  9.  
  10. extension String {
  11.  
  12.     public func aes256Decrypt(key: String) throws -> Data? {
  13.        
  14.         guard let data = Data(base64Encoded: self, options: Data.Base64DecodingOptions.ignoreUnknownCharacters) else {
  15.             return nil
  16.         }
  17.        
  18.         guard let keyData = key.data(using: .utf8) else {
  19.             return nil
  20.         }
  21.        
  22.         let clearLength = size_t(data.count + kCCBlockSizeAES128)
  23.         var clearData = Data(count:clearLength)
  24.        
  25.         var numBytesDecrypted: size_t = 0
  26.         let options = CCOptions(kCCOptionECBMode + kCCOptionPKCS7Padding)
  27.        
  28.         let cryptStatus = clearData.withUnsafeMutableBytes {cryptBytes in
  29.             data.withUnsafeBytes {dataBytes in
  30.                 keyData.withUnsafeBytes {keyBytes in
  31.                     CCCrypt(CCOperation(kCCDecrypt), CCAlgorithm(kCCAlgorithmAES), options,
  32.                             keyBytes, kCCKeySizeAES256,
  33.                             nil,
  34.                             dataBytes + kCCBlockSizeAES128, clearLength,
  35.                             cryptBytes, clearLength,
  36.                             &numBytesDecrypted)
  37.                 }
  38.             }
  39.         }
  40.        
  41.         if UInt32(cryptStatus) == UInt32(kCCSuccess) {
  42.             clearData.count = numBytesDecrypted
  43.         }
  44.         else {
  45.             throw AESError.CryptorError(("Decryption failed", Int(cryptStatus)))
  46.         }
  47.        
  48.         return clearData
  49.     }
  50. }
RAW Paste Data