javascript - 16字符长度的 iv 和32字符长度的 key 怎么在 nodejs 用 aes-128-cbc 解密。

查看:342
本文介绍了javascript - 16字符长度的 iv 和32字符长度的 key 怎么在 nodejs 用 aes-128-cbc 解密。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

用网上提供的方法总是报错:Invalid key length
有什么办法吗?

const hash = '56e71d68a230081a0fe562ae4daaf58451db4ce4bde4f881b65b713cc8c3248405a3a2c8520cb8a7215f9ebaa604dae62d320f2c77bda679a2d3df1ecc790ee5a7113afe6974e5e89d2a10d0e63a2b5cbe05923fe6765f0eca1ddea969e4fe39b1d951554b0dfe66aafd4b24bd138d848c479186ed13139328b37e34200ecd4a718b7f3f268fdc6d1a174a192c8d1150a8c56686783f19dbeaa7f03a943ce4089768655843311e5c3ac8ae05d0d5990723521e04dcb5137e470c20990365f742ae78492178cb2d512cb7cb55d229218dc66f1f5234e3546cca534d3e8787dfb6b720c069dbb9a344d944d22aaf01e921'
const iv = 'e6db271db12d4d47'
const key = '9cd5b4cf899492077b4a125a79af8e76'
const crypto = require('crypto')

 const aesDecrypt = function(data, secretKey, iv) {
   const cipherEncoding = 'base64'
   const clearEncoding = 'utf8'
   const cipher = crypto.createDecipheriv('aes-128-cbc',secretKey, iv)
   return cipher.update(data,cipherEncoding,clearEncoding) + cipher.final(clearEncoding)
 }

console.log(aesDecrypt(hash, key, iv))

解决方案

1.key的长度不对,既然是128位的aes加密算法,采用cbc的加密模式,那么key长度为16就好了。
2.既然你指定你的密文的编码格式是base64,但是你的hash的编码并不是base64的。解密还是会失败的。
3.修改了一下你的例子,下面的代码运行一下即可获得明文输出。

// base64 encode cipher
const hash = 'riX6dKnCg8vOt+Z3LxnM/oZThZEjOSUQJR9v+DSDY3E='
const iv = 'e6db271db12d4d47'
// length of key is 16 of 128 bit
const key = '9cd5b4cf89949207'
const crypto = require('crypto')
const aesDecrypt = function(data, secretKey, iv) {
    const cipherEncoding = 'base64'
    const clearEncoding = 'utf8'
    const cipher = crypto.createDecipheriv('aes-128-cbc',secretKey, iv)
    return  cipher.update(data,cipherEncoding,clearEncoding) + cipher.final(clearEncoding)
 }

console.log(aesDecrypt(hash, key, iv)) // base64-encoded-encrypted-data

这篇关于javascript - 16字符长度的 iv 和32字符长度的 key 怎么在 nodejs 用 aes-128-cbc 解密。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆