I am using cryptoSwift library for encryption and decryption. But it's working with only string 16 bytes. If i am passing small string or less than 16 bytes then getting nil result.
I am using Incremental operations use instance of Cryptor and encrypt/decrypt one part at a time.
Please help me here, is there anything which i am doing wrong.
Thanks in advance.
I am using Incremental operations use instance of Cryptor and encrypt/decrypt one part at a time.
Please help me here, is there anything which i am doing wrong.
Thanks in advance.
Code Block func encAndDec(){ do { // Encryption start let data = Data.init(base64Encoded: "12345678901234567890123456789012".base64Encoded()!) let iv : Array<UInt8> = [0,0,0,0,0,0,0,0,0,0,0,0] let nIv = Data(iv) let gcmEnc = GCM(iv: nIv.bytes, mode: .detached) var enc = try? AES(key: data!.bytes, blockMode: gcmEnc, padding: .noPadding).makeEncryptor() let arrStr = ["My name is tarun"] // Working //let arrStr = ["tarun"] // Not working for this string var ciphertext = Array<UInt8>() for txt in arrStr{ let ciperText = try? enc?.update(withBytes: Array(txt.utf8)) // Getting nil for small string. ciphertext.append(contentsOf: ciperText!) } var res = try? enc?.finish() gcmEnc.authenticationTag = self.randomGenerateBytes(count: 16)?.bytes res?.append(contentsOf: (gcmEnc.authenticationTag)!) let cipherData = Data(ciphertext) + Data(res!) let strEnc = String(decoding: cipherData, as: UTF8.self) print(strEnc) // Decryption start from here do { let gcmDec = GCM.init(iv: nIv.bytes, additionalAuthenticatedData: nil, tagLength: 16, mode: .detached) var aesDec = try! AES(key: data!.bytes, blockMode: gcmDec, padding: .noPadding).makeDecryptor() let tag_length = 16 let encData = cipherData.subdata(in: 0..<cipherData.count - tag_length) let tag = cipherData.subdata(in: encData.count ..< cipherData.count) let decData = try? aesDec.update(withBytes: encData.bytes) //Getting nil here for small string let strData = String(decoding: decData!, as: UTF8.self) print(strData) do{ var res = try? aesDec.finish(withBytes: tag.bytes) res?.append(contentsOf: tag) }catch{ } } catch { // failed } } } func randomGenerateBytes(count: Int) -> Data? { let bytes = UnsafeMutableRawPointer.allocate(byteCount: count, alignment: 1) defer { bytes.deallocate() } let status = CCRandomGenerateBytes(bytes, count) guard status == kCCSuccess else { return nil } return Data(bytes: bytes, count: count) }