0

I am using common crypto encryption and decryption. I am using AES for API calling and response.

I have done everything right but whenever I am doing decryption of the received response, only the first key in response in not getting decrypted, rest other response string is decrypted in good format.

Decrypted Response:

enter image description here

AES Struct Code:

struct AES {

    // MARK: - Value
    // MARK: Private
    private let key: Data
    private let iv: Data


    // MARK: - Initialzier
    init?(key: String, iv: String) {
        guard key.count == kCCKeySizeAES128 || key.count == kCCKeySizeAES256, let keyData = key.data(using: .utf8) else {
            debugPrint("Error: Failed to set a key.")
            return nil
        }


        guard iv.count == kCCBlockSizeAES128, let ivData = iv.data(using: .utf8) else {
            debugPrint("Error: Failed to set an initial vector.")
            return nil
        }


        self.key = keyData
        self.iv  = ivData
    }


    // MARK: - Function
    // MARK: Public

    func encrypt(string: String) -> String? {
        let data =  crypt(data: string.data(using: .utf8), option: CCOperation(kCCEncrypt))
        let str = data?.base64EncodedString()
        let ivStr = UIConstants.IV.base64Encoded

        let str1 = (str?.replacingOccurrences(of: " ", with: ""))! + ":" + ivStr!
        let str2 = str1.replacingOccurrences(of: "+", with: ".")
        let str3 = str2.replacingOccurrences(of: "/", with: "_")
        let str4 = str3.replacingOccurrences(of: "=", with: "-")
        let str5 = str4.replacingOccurrences(of: "\n", with: "")

        return str5

    }

    func decrypt(data: Data?) -> String? {
        guard let decryptedData = crypt(data: data, option: CCOperation(kCCDecrypt)) else { return nil }
        return String(bytes: decryptedData, encoding: .ascii)

    }

    func crypt(data: Data?, option: CCOperation) -> Data? {
        guard let data = data else { return nil }

        let cryptLength = [UInt8](repeating: 0, count: data.count + kCCBlockSizeAES128).count
        var cryptData   = Data(count: cryptLength)

        let keyLength = [UInt8](repeating: 0, count: kCCBlockSizeAES128).count
        let options   = CCOptions(kCCOptionPKCS7Padding)

        var bytesLength = Int(0)

        let status = cryptData.withUnsafeMutableBytes { cryptBytes in
            data.withUnsafeBytes { dataBytes in
                iv.withUnsafeBytes { ivBytes in
                    key.withUnsafeBytes { keyBytes in
                        CCCrypt(option, CCAlgorithm(kCCAlgorithmAES), options, keyBytes, keyLength, ivBytes, dataBytes, data.count, cryptBytes, cryptLength, &bytesLength)
                    }
                }
            }
        }

        guard UInt32(status) == UInt32(kCCSuccess) else {
            debugPrint("Error: Failed to crypt data. Status \(status)")
            return nil
        }

        cryptData.removeSubrange(bytesLength..<cryptData.count)
        return cryptData
    }
}

API Response Decryption Code:

                let responseDic = response.object! as [String: Any]
                let responseString = responseDic["data"] as! String

                let str2 = responseString.replacingOccurrences(of: ".", with: "+")
                let str3 = str2.replacingOccurrences(of: "_", with: "/")
                let str4 = str3.replacingOccurrences(of: "-", with: "=")

                let index = str4.range(of: ":")?.lowerBound
                let substring = str4[..<index!]
                let stringRemovingIV = String(substring)
                print(stringRemovingIV)

                let data = Data(base64Encoded: stringRemovingIV, options: NSData.Base64DecodingOptions.ignoreUnknownCharacters)

                var decryptString =  aes256?.decrypt(data: data) as! String
                print(decryptString)

                let responseObject = NSDictionary.convertStringToDictionary(text: String(decryptString))
                print(responseObject as Any)
Suhas Arvind Patil
  • 1,732
  • 1
  • 19
  • 31

0 Answers0