Reputation: 293
Here is my code
const crypto = require('crypto')
const algorithm = 'aes-256-cbc';
const key = 't\ufffdy\u0005\ufffdH\ufffd\u0015\ufffdCh\ufffdı\ufffd\ufffd\ufffd>\ufffd(d\ufffd3\ufffd\ufffd\ufffd\ufffd\ufffd\' 4'
const iv = '\u0005\ufffd\ufffd\ufffd\ufffdKV`\u0007z\ufffd\"H\ufffd\u0013\ufffd'
exports.postMessage = (req,res,next) =>{
// var buf= Buffer.from(crypto.randomBytes(16)).toString()
// return res.json(iv.length)
function encrypt(text) {
let cipher = crypto.createCipheriv('aes-256-cbc', Buffer.from(key), iv);
let encrypted = cipher.update(text);
encrypted = Buffer.concat([encrypted, cipher.final()]);
return res.json({ iv: iv.toString('hex').slice(0, 16), encryptedData: encrypted.toString('hex') });
}
encrypt('some text')
}
Error: Error: Invalid IV length at Cipheriv.createCipherBase (internal/crypto/cipher.js:79:18) at Cipheriv.createCipherWithIV (internal/crypto/cipher.js:115:20) at new Cipheriv (internal/crypto/cipher.js:217:22) at Object.createCipheriv (crypto.js:109:10)
Upvotes: 0
Views: 7831
Reputation: 5636
The 256 after the AES represents the key size not block size. AES has 128, 192, and 256-bit sizes and has always 128-bit block sizes. When you are using CBC mode that requires an IV to randomize the encryption and the IV size is equal to block size. In this case, it is 128-bit i.e. 16-bytes. Therefore make sure that your IV is exactly, 16-bytes.
If you are just starting for a project, don't use CBC mode it is an old mode of operation and has many problems. For example, in your case, it is fixed and that is catastrophic, you turned CBC into ECB. In CBC mode under the same key the IV must not be reused. More than this, the IV must be unpredictable. You can use
var iv = Crypto.randomBytes(16);
to create a random IV.
Under the key size 128, one should stop way before generating 2^64 random IVs, see the birthday paradox. In your case, the key size is 256 and we don't expect that a good random IV generator will hit the same IV again.
For starting a new project, prefer authenticated encryption modes like AES-GCM that will provide you confidentiality, integrity, and authentication.
Upvotes: 1