Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AES128 encryption in swift

I’ve an issue with AES-128 encryption. The encrypted string in iOS is different as compared to Android.

Below is android code :

public class Encryption {
    private static final String ALGORITHM = "AES";
    private static final String UNICODE_FORMAT = "UTF8";

    public static String encryptValue(String valueToEnc) {
        try {
            Key key = generateKey();
            Cipher c = Cipher.getInstance(ALGORITHM);
            c.init(Cipher.ENCRYPT_MODE, key);
            byte[] encValue = c.doFinal(valueToEnc.getBytes());
            String encryptedValue = new Base64().encode(encValue);
            String urlEncodeddata = URLEncoder.encode(encryptedValue, "UTF-8");
            return urlEncodeddata;
        } catch (Exception e) {

        }
        return valueToEnc;
    }

    private static Key generateKey() throws Exception {
        byte[] keyAsBytes;
        keyAsBytes = "MySixteenCharKey".getBytes(UNICODE_FORMAT);
        Key key = new SecretKeySpec(keyAsBytes, ALGORITHM);
        return key;
    }
}
like image 750
Jayprakash Dubey Avatar asked Dec 17 '25 21:12

Jayprakash Dubey


1 Answers

Create string extension and use library CryptoSwift

//  String+Addition.swift
import CryptoSwift
extension String {
func aesEncrypt(key: String) throws -> String {
        
        var result = ""
        
        do {
            
            let key: [UInt8] = Array(key.utf8) as [UInt8]
            
            let aes = try! AES(key: key, blockMode: ECB() , padding:.pkcs5) // AES128 .ECB pkcs7
            
            let encrypted = try aes.encrypt(Array(self.utf8))
            
            result = encrypted.toBase64()!
            
            
            print("AES Encryption Result: \(result)")
            
        } catch {
            
            print("Error: \(error)")
        }
        
        return result
    }

func aesDecrypt(key: String) throws -> String {
    
    var result = ""
    
    do {
        
        let encrypted = self
        let key: [UInt8] = Array(key.utf8) as [UInt8]
        let aes = try! AES(key: key, blockMode: ECB(), padding: .pkcs5) // AES128 .ECB pkcs7
        let decrypted = try aes.decrypt(Array(base64: encrypted))
        
        result = String(data: Data(decrypted), encoding: .utf8) ?? ""
        
        print("AES Decryption Result: \(result)")
        
    } catch {
        
        print("Error: \(error)")
    }
    
    return result
}

}

and to use

@IBAction func onBtnClicked(_ sender: Any) { 
        let value = "My value to be encrypted"
        let key = "MySixteenCharKey"
        
        print(key!)
        let encryptedValue = try! value.aesEncrypt(key: key!)

        print(encryptedValue)
        
    }

For citation of this particular encryption code:

  1. The 16 char length key implies AES-128
  2. The code is without iVector, This implies ECB mode
  3. Using padding as pkcs5 or pkcs7 did not made any difference in my case
like image 152
jeet.chanchawat Avatar answered Dec 20 '25 10:12

jeet.chanchawat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!