I see some issues about invalid IV length or Invalid key length.
In PHP, there is a helper method (openssl_cipher_iv_length) that return the correct length for IV.
Node could have a static method for this, something like:
crypto.cipherivLength(algorithm: string): number
crypto.cipherkeyLength(algorithm: string): number
Simple example:
const ivLen = crypto.cipherivLength('des-ede3-ofb') // => 8
const keyLen = crypto.cipherkeyLength('des-ede3-ofb') // => 24
Complex example:
'use strict'
const assert = require('assert').strict
const crypto = require('crypto')
const SALT = 'foobar'
function genKey(alg) {
const keyLen = 24 // => crypto.cipherkeyLength(alg)
const hash = crypto.createHash('sha256').update(SALT).digest()
return hash.slice(0, keyLen)
}
function encrypt(value, alg = 'des-ede3-ofb') {
const ivLen = 8 // => crypto.cipherivLength(alg)
const iv = crypto.randomBytes(ivLen)
const key = genKey(alg)
const cipher = crypto.createCipheriv(alg, key, iv, {authTagLength: ivLen})
const encryptedUpdate = cipher.update(value)
const encryptedFinal = cipher.final()
const encrypted = Buffer.concat([encryptedUpdate, encryptedFinal], encryptedUpdate.byteLength + encryptedFinal.byteLength)
return [encrypted, iv]
}
function decrypt([encrypted, iv], alg = 'des-ede3-ofb') {
const ivLen = iv.byteLength
const key = genKey(alg)
const cipher = crypto.createDecipheriv(alg, key, iv, {authTagLength: ivLen})
const decryptedUpdate = cipher.update(encrypted)
const decryptedFinal = cipher.final()
return Buffer.concat([decryptedUpdate, decryptedFinal], decryptedUpdate.byteLength + decryptedFinal.byteLength)
}
// Testing
const input = 'test'
const output = decrypt(encrypt(input)).toString('utf8')
assert.strictEqual(input, output) // => OK
I see some issues about
invalid IV lengthorInvalid key length.In PHP, there is a helper method (
openssl_cipher_iv_length) that return the correct length for IV.Node could have a static method for this, something like:
crypto.cipherivLength(algorithm: string): numbercrypto.cipherkeyLength(algorithm: string): numberSimple example:
Complex example: