iosswiftaesaes-gcm

How to decrypt/encrypt data using AES GCM with tag received from APIs in Swift


In API response I m getting AES GCM encrypted data with tag and trying to decrypt the same data with tage received from API response using below code, Please help here to decrypt data using AES-GCM with tag value.

func aesDecrypt(phrase:String, key: String, iv: String) throws -> String {
    
    if let data: Array<UInt8> = (Data(base64Encoded: phrase)?.bytes)
    {
        let key: Array<UInt8> = (key.data(using: .utf8)?.bytes)!
        let iv: Array<UInt8> = (iv.data(using: .utf8)?.bytes)!
        print("IVVVVVVVV:\(iv)")
        let tag: Array<UInt8> = (self.tagStr.data(using: .utf8)?.bytes)!
        
        let decGCM = GCM(iv: iv, authenticationTag: tag , mode: .detached)
        let decrypted = try AES(key: key, blockMode: decGCM, padding: .noPadding).decrypt(data)
        print("DECRYPTED:\(decrypted)")
        
        let decryptedData = Data(decrypted)
        
        guard let value = String.init(data: decryptedData, encoding: .utf8) else {
            return "error"
        }
        return value
    }
    return ""
}

Uses:

let decryptData = try self.aesDecrypt(phrase: responseData, key: key, iv: iv)

Solution

  • Thank you all for your time:

    I have solved the issue using below code, it is working fine for me. Thank you.

    func commonEncryptAESGCM(params:[String:Any]) -> (String, String)  {
        
        let jsonStr = arrayToJsonString(from: params)
        print("Array String",jsonStr!)
        
        let iv = UserDefaults.standard.object(forKey: UserDefautKeys.aesIV) as! String
        let keys = UserDefaults.standard.object(forKey: UserDefautKeys.aesKey) as! String
        print("IV Key",iv,keys)
        
        let initializationVector: Data = Data(iv.utf8) // Your IV
        let nonce = initializationVector
        
        let key = SymmetricKey(data: keys.data(using: .utf8)!)
        
        // Encrypt
        let sealedData = try! AES.GCM.seal(jsonStr!.data(using: .utf8)!, using: key,
                                           nonce: AES.GCM.Nonce(data: nonce))
        let data = sealedData.ciphertext.base64EncodedString()
        let tag = sealedData.tag.base64EncodedString()
        print("Data: \(data)")
        print("Tag: \(tag)")
        return (data, tag)
    }
    

    Uses:

    let result = commonEncryptAESGCM(params: paramStr)