Search code examples
node.jsswiftencryptioncryptographycryptoswift

Data encrypted by CryptoSwift is not same as Node.js


I used CryptoSwift to encrypt some data, and then encrypted the same data using Node.js. But the results are not same. I asked the author, he said it's not a bug.

I don't know where I made a mistake. Here are pictures of how I used CryptoSwift and Node.js:

Cipher algorithm: aes-256-cfb

key: 32 bytes 1

iv: 16 bytes 0

CryptoSwift: develop-branch 0.1.1

Node.js: LTS 4.2.3

Data encrypted by CryptoSwift

Data encrypted by Node.js 4.2.3

Here is swift code:

    func testAES() {
    let key = [UInt8](count: 32, repeatedValue: 1)
    let iv = [UInt8](count: 16, repeatedValue: 0)
    print(key)
    print(iv)

    let aes256cfb = try! AES(key: key, iv: iv, blockMode: .CFB)

    let en1 = try! aes256cfb.encrypt([0x5, 0x77], padding: nil)
    print(en1.map({ i in String(format: "%2x", i)}))

    let en2 = try! aes256cfb.encrypt([0x5, 0x0, 0x3, 0x89, 0x20], padding: nil)
    print(en2.map({ i in String(format: "%2x", i)}))
}

CryptoSwift: 
["77", "ef"]
["77", "98", "c9", "2c", "45"]

Node.js: 
<Buffer 77 ef>
<Buffer cf a5 66 8a 3e>

You can see, the first two bytes are same, but the rest are not. Why? Is my code writing wrong? I don't know much about crypto, please tell me the reason. Thank you so much.


Solution

  • Unless the data is a multiple of the block size (16-bytes) and the data size is known by both sides a-priori to meet the requirement padding is required. The generally used padding is PKCS#7 (PKCS#5 is essentially the same).

    In the code no padding is specified so the balance of the block will be whatever junk is in the buffer or perhaps the algorithm may null pad it, it is always best not to rely on non-standard defaults.

    See the SO Answer for an example of using Common Crypto.

    But the best thing to do is use RNCryptor for your encryption, it is available for several languages and platforms. It also handles all the bits that make encryption secure. It is well vetted and being actively developed.