3

I've been trying to encrypt some messages using "crypto" library in NodeJS, and I'm getting the following error:

(node:31732) UnhandledPromiseRejectionWarning: Error: error:0607F08A:digital envelope routines:EVP_EncryptFinal_ex:data not multiple of block length

at Cipheriv.final (internal/crypto/cipher.js:164:28)
at self.test (...)

self.test = async function(info, object) {
    let message = {
        info: info,
        object: object
    };

    let iv = crypto.randomBytes(16)
    let key = Buffer.from(config.key, 'utf8');
    let cipher = crypto.createCipheriv("aes-128-ecb", key, '');
    cipher.setAutoPadding(false)
    let encrypted = cipher.update(JSON.stringify(message));
    encrypted = Buffer.concat([iv, encrypted, cipher.final()]);
    encrypted = encrypted.toString('base64');

    console.log(encrypted);
}

The error is originating from the cipher.final() call as seen in the stack above.

I can't figure out what this error says and how to resolve it. Unfortunately due to constraints (I'm trying to send encrypted data over UDP) I'm not able to use algorithms like CBC (messages are not received in the same order they are encrypted).

Any help is greatly appreciated!

Community
  • 1
  • 1
0rka
  • 2,246
  • 2
  • 11
  • 20
  • 1
    I've downvoted your question as [the `setAutoPadding()`method](https://nodejs.org/api/crypto.html#crypto_cipher_setautopadding_autopadding) is pretty well documented. If you are too lazy to read through the documentation of the methods you are calling then there is not much hope... – Maarten Bodewes Feb 27 '19 at 15:32

1 Answers1

3

cipher.setAutoPadding(false) sets padding to false, and ECB and CBC only operate on full blocks - which is the reason why padding is required for anything that is not a multiple of the block size. You should remove the line (preferred) or create your own padding (and fall in a trap of inventing your own crypto).

Note that both ECB and CBC are inherently vulnerable to plaintext / padding oracle attacks. ECB is insecure anyway and it doesn't use an IV. For transport mode security you need a MAC or you should use an authenticated cipher. Transport security is hard to accomplish, try DTLS.

Maarten Bodewes
  • 90,524
  • 13
  • 150
  • 263