1

hello fellow programmers,

It's about ios(Swift3) encrypt/decrypt: I'm an ios swift beginner. I followed a tutorial at https://www.funboxpower.com/php_android_ios_aes to complete encrypt/decrypt between Android and PHP.

Now I wanna to do the same on iOS(Swift3), the author mentioned ios(object-c) method as this Wanted Compatible AES code Encrypt/Decrypt for Iphone, Android, Windows/XP

so I find CryptoSwift 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) ?

Here is the code for encryption on Swift:

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) -> 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
}
Rich Guo
  • 11
  • 2
  • 1
    You can look at [RNCryptor](https://github.com/RNCryptor). Many languages are covered. So you can use this in your `Swift`, `Java` and `PHP` flawlessly and with pretty much same functionality. – nayem Jul 04 '17 at 06:11
  • Did you find any code for Swift to encrypt and decrypt. – Himanshu Parashar Oct 24 '17 at 14:15

1 Answers1

0
  1. Use Java 8 on Android.
  2. Install Java Cryptography Extension on Android machine.
  3. Check your Base64 class.
  4. Test it here: http://aesencryption.net.
  5. Check what bit is compatible.
  6. Check key size.

Testing tips: Use same (iv)intigrated vector & key on all three platform encrypt from one platform and try decrypt on other use harcdoded encrypted decrypted text.

Anh Pham
  • 2,108
  • 9
  • 18
  • 29
  • thanks for tips. in my project, java and php code is fine. but how to use Swift to encrypt to get the same result? – Rich Guo Jul 04 '17 at 09:57