Search code examples
node.jsswiftencryptionaesnode-crypto

AES256 Issue using swift 5


I am using AES256 algorithm CBC mode with pkc7 padding. I have backend in Node.js. But getting first 12 random characters.

Here is my swift code:

    func encrypt(data: Data, key: Data, iv: Data) throws -> Data? {

        // Output buffer (with padding)
        let outputLength = data.count + kCCBlockSizeAES128

        var outputBuffer = Array<UInt8>(repeating: 0,
                                        count: outputLength)
        //var outputBuffer: [UInt8] = []
        var numBytesEncrypted = 0
        let status = CCCrypt(CCOperation(kCCEncrypt),
                             CCAlgorithm(kCCAlgorithmAES),
                             CCOptions(kCCOptionPKCS7Padding),
                             Array(key),
                             kCCKeySizeAES256,
                             Array(iv),
                             Array(data),
                             data.count,
                             &outputBuffer,
                             outputLength,
                             &numBytesEncrypted)

        guard status == kCCSuccess else { return nil }

        let outputBytes = iv + outputBuffer.prefix(numBytesEncrypted)

        return Data(bytes: outputBytes)
    }

How can I do without padding? Or what should be done from backend?

enter image description here


Solution

  • You can use tags before and after payload you want to share. That tag will be your headers.

    like <tag>string</tag>

    So if you encrypt you will get first 12 random bytes

    so you need to ignore text other than between **<tag>...</tag>**