Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error while trying to encrypt using AES-128-ECB algorithm

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!

like image 224
0rka Avatar asked Apr 24 '26 03:04

0rka


1 Answers

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.

like image 118
Maarten Bodewes Avatar answered Apr 25 '26 20:04

Maarten Bodewes