title: Encrypt / Decrypt Between iOS(swift3), Android and PHP
body: <p>hello fellow programmers,</p>
  
  <p>It's about ios(Swift3) encrypt/decrypt:
  I'm an ios swift beginner. I followed a tutorial at <a href="https://www.funboxpower.com/php_android_ios_aes" rel="nofollow noreferrer">https://www.funboxpower.com/php_android_ios_aes</a> to complete encrypt/decrypt between Android and PHP.</p>
  
  <p>Now I wanna to do the same on iOS(Swift3), the author mentioned ios(object-c) method as this <a href="https://stackoverflow.com/questions/5928915/wanted-compatible-aes-code-encrypt-decrypt-for-iphone-android-windows-xp">Wanted Compatible AES code Encrypt/Decrypt for Iphone, Android, Windows/XP</a></p>
  
  <p>so I find <a href="https://github.com/krzyzanowskim/CryptoSwift" rel="nofollow noreferrer">CryptoSwift</a> and it help me to encrypt my string. but the result is not same as Android and PHP. How can I do that use iOS(Swift3) with CryptoSwift to encrypt/decrypt like the tutorial(Android/PHP) ?</p>
  
  <p>Here is the code for encryption on Swift:</p>
  
  <pre><code>import CryptoSwift
  
  class LoginViewController: UIViewController {
     @IBAction func loginAction(sender: AnyObject) {
          let account = self.accountTextField.text
          let password = self.passwordTextField.text
  
          let key = "itakeylengthtotalis32keykeykey00"
          let iv = "0000000000000000"
          let encryptedAccount = try! account?.aesEncrypt(key:key, iv: iv)
          let encryptedPassword = try! password?.aesEncrypt(key:key, iv: iv)
  
          //result here ------------------------------
          print( "encryptedAccount: " + encryptedAccount! )
          print( "encryptedPassword: " + encryptedPassword! )
     }
  }
  
  
  
  extension String {
  
      func aesEncrypt(key: String, iv: String) -&gt; String? {
          var result: String?
          do {
            // 用UTF8的编碼方式將字串轉成Data / use Data func for a UT8 string
            let data: Data = self.data(using: String.Encoding.utf8, allowLossyConversion: true)!
  
            // 用AES的方式將Data加密 / use AES to encrypt Data
            let aecEnc: AES = try AES(key: key, iv: iv, blockMode: .CBC, padding:PKCS7())
            let enc = try aecEnc.encrypt(data.bytes)
  
            // 使用Base64編碼方式將Data轉回字串 / use Base64 to encode string
            let encData: Data = Data(bytes: enc, count: enc.count)
            result = encData.base64EncodedString()
         } catch {
          print("\(error.localizedDescription)")
         }
  
        return result
  }
  </code></pre>