Spl*_*eer 3 encryption node.js
我正在更新我的旧函数来加密密码,因为createCipher它已被弃用。
这是我的旧功能:
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
}
Run Code Online (Sandbox Code Playgroud)
这是我尝试做的:
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()
}
Run Code Online (Sandbox Code Playgroud)
但是当我尝试这样做时出现了这个错误:
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)
Run Code Online (Sandbox Code Playgroud)
对于这一行,我尝试了多个值,如 12、16、32、124 等。但都没有工作
const iv = crypto.randomBytes(96)
Run Code Online (Sandbox Code Playgroud)
AES-192(以及 AES-128 和 AES-256)都使用 128 位块长度,因此 IV 也应该是 128 位,或 16 字节。奇怪的是,您尝试了 16 作为长度;无论如何,这段代码对我有用:
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')
}
Run Code Online (Sandbox Code Playgroud)
我假设配置如下所示:
{ secret: 'dc8a453e728fc19398178797e2c39067e1965f2061220257' }
Run Code Online (Sandbox Code Playgroud)