Reputation: 1264
I'm updating my old function to encrypt password since createCipher
is deprecated.
Here are my old functions:
encrypt(payload) {
let AES192 = crypto.createCipher('aes192', Buffer.from(config.secret))
let crypted = AES192.update(payload, 'utf8', 'hex')
crypted += AES192.final('hex')
return crypted
},
decrypt(payload) {
let AES192 = crypto.createDecipher('aes192', Buffer.from(config.secret))
let decrypted = AES192.update(payload, 'hex', 'utf8')
decrypted += AES192.final('utf8')
return decrypted
}
Here is what I tried to do:
encrypt(payload) {
const iv = crypto.randomBytes(96)
const cipher = crypto.createCipheriv('aes192', Buffer.from(config.secret, 'hex'), iv)
const encrypted = cipher.update(payload)
encrypted = Buffer.concat([encrypted, cipher.final()])
return iv.toString('hex') + ':' + encrypted.toString('hex')
},
decrypt(payload) {
let textParts = payload.split(':')
let iv = Buffer.from(textParts.shift(), 'hex')
let encryptedText = Buffer.from(textParts.join(':'), 'hex')
let decipher = crypto.createDecipheriv('aes192', Buffer.from(config.secret, 'hex'), iv)
let decrypted = decipher.update(encryptedText)
decrypted = Buffer.concat([decrypted, decipher.final()])
return decrypted.toString()
}
But I got this error when I try to do it:
Error: Invalid IV length
at Cipheriv.createCipherBase (internal/crypto/cipher.js:103:19)
at Cipheriv.createCipherWithIV (internal/crypto/cipher.js:121:20)
at new Cipheriv (internal/crypto/cipher.js:225:22)
at Object.createCipheriv (crypto.js:119:10)
For this line I tried multiple values like 12, 16, 32, 124 etc. But none are working
const iv = crypto.randomBytes(96)
Upvotes: 3
Views: 1757
Reputation: 30715
AES-192 (and for that matter AES-128 and AES-256) all use a 128 bit block length, so the IV should also be 128 bits, or 16 bytes. It's weird that you tried 16 as the length; at any rate this code is working for me:
function encrypt(payload) {
const iv = crypto.randomBytes(16);
const cipher = crypto.createCipheriv('aes192', Buffer.from(config.secret, 'hex'), iv)
let encrypted = cipher.update(payload)
encrypted = Buffer.concat([encrypted, cipher.final()])
return iv.toString('hex') + ':' + encrypted.toString('hex')
}
I'm assuming config looks like this:
{ secret: 'dc8a453e728fc19398178797e2c39067e1965f2061220257' }
Upvotes: 6