Node.js 错误:06065064:数字信封例程:EVP_DecryptFinal_ex:错误解密

Node.js 错误:06065064:数字信封例程:EVP_DecryptFinal_ex:错误解密,node.js,express,mongoose,cryptography,Node.js,Express,Mongoose,Cryptography,请注意,我正在尝试将加密数据存储在数据库中,并在前端显示解密数据。 加密工作正常,但尝试解密时显示以下错误错误:06065064:数字信封例程:EVP_decrypt final_ex:bad decrypt 这是我的密码: const express = require('express'); const router = express.Router(); const { check, validationResult } = require('express-validator'); co

请注意,我正在尝试将加密数据存储在数据库中,并在前端显示解密数据。 加密工作正常,但尝试解密时显示以下错误错误:06065064:数字信封例程:EVP_decrypt final_ex:bad decrypt

这是我的密码:

const express = require('express');
const router = express.Router();
const { check, validationResult } = require('express-validator');
const User = require('../models/Users');
const Message = require('../models/Messages');
const auth = require('../middleware/auth');
const AES = require('../config/aes-encryption');

// @route GET api/messages
// @desc get all messages
// @access private 
    router.get('/', auth, async(req, res) => {
    try {

        const messages = await Message.find();

        messages.forEach((msg) => {
            console.log(msg.text);
            
    // Here is where i have the error
            AES.decrypt(msg.text);
        });
        
        res.json(messages);
        

        
    } catch (error) {
        console.error(error.message);
        res.status(500).json({ msg: "Internal Sever Error" }); 
    }
});

// @route POST api/messages
// @desc add messages
// @access private 

router.post('/', [auth, [check('text', 'Please enter a message').not().isEmpty(),]], async(req, res) => {

    const errors = validationResult(req);
    if (!errors.isEmpty()) {
        return res.status(400).json({ errors: errors.array() });
    }

    try {
        const user = await User.findById(req.user.id).select('-password');
        const encrytedText = AES.encrypt(req.body.text);
        
        const message = new Message({
            text: encrytedText,
            user: req.user.id,
            name: user.name,
            avatar: user.avatar
        });

        const msg = await message.save();

        res.json(msg);
        
    } catch (error) {
        console.error(error.message);
        res.status(500).json({ msg: "Internal Sever Error" }) 
        
    }
});

这是我的加密和解密函数

  const crypto = require("crypto");
const algorithm = "aes-256-cbc";
const key = crypto.randomBytes(32);
const iv = crypto.randomBytes(16);

exports.encrypt= function (text) {
  let cipher = crypto.createCipheriv(algorithm, Buffer.from(key), iv);
  let encrypted = cipher.update(text);
  encrypted = Buffer.concat([encrypted, cipher.final()]);
  return { iv: iv.toString("hex"), encryptedData: encrypted.toString('hex') };
}

exports.decrypt = function (text) {
  let iv = Buffer.from(text.iv, 'hex');
  let encryptedText = Buffer.from(text.encryptedData, 'hex');
  let decipher = crypto.createDecipheriv(algorithm, Buffer.from(key), iv);
  let decrypted = decipher.update(encryptedText);
  decrypted = Buffer.concat([decrypted, decipher.final()]);
  return decrypted.toString();
}
消息模型

const mongoose = require('mongoose');

const MessagesSchema = mongoose.Schema({
    user: { type: mongoose.Schema.Types.ObjectId, ref: 'users' },
    text: {type: Object, required: true},
    name: { type: String },
    avatar: { type: String },
    date: { type: Date, default: Date.now }
});

module.exports = Message = mongoose.model('messages', MessagesSchema);


我找到了解决办法。我需要使用一个不变的永久密钥

const crypto = require("crypto");
const algorithm = "aes-128-cbc";
const salt = "foobar";
const hash = crypto.createHash("sha1");

hash.update(salt);

// `hash.digest()` returns a Buffer by default when no encoding is given
let key = hash.digest().slice(0, 16);
crypto.createHash('sha256').update(String(secretkey)).digest('base64').substr(0, 32);
const iv = crypto.randomBytes(16);

exports.encrypt= function (text) {
  
  let cipher = crypto.createCipheriv(algorithm, key, iv);
  let encrypted = cipher.update(text);
  encrypted = Buffer.concat([encrypted, cipher.final()]);
  return { iv: iv.toString("hex"), encryptedData: encrypted.toString('hex') };
}

exports.decrypt = function (text) {
  let iv = Buffer.from(text.iv, 'hex');
  let encryptedText = Buffer.from(text.encryptedData, 'hex');
  
  let decipher = crypto.createDecipheriv(algorithm, key, iv);
  let decrypted = decipher.update(encryptedText);
  decrypted = Buffer.concat([decrypted, decipher.final()]);
  
  return decrypted.toString();
}


我找到了解决办法。我需要使用一个不变的永久密钥

const crypto = require("crypto");
const algorithm = "aes-128-cbc";
const salt = "foobar";
const hash = crypto.createHash("sha1");

hash.update(salt);

// `hash.digest()` returns a Buffer by default when no encoding is given
let key = hash.digest().slice(0, 16);
crypto.createHash('sha256').update(String(secretkey)).digest('base64').substr(0, 32);
const iv = crypto.randomBytes(16);

exports.encrypt= function (text) {
  
  let cipher = crypto.createCipheriv(algorithm, key, iv);
  let encrypted = cipher.update(text);
  encrypted = Buffer.concat([encrypted, cipher.final()]);
  return { iv: iv.toString("hex"), encryptedData: encrypted.toString('hex') };
}

exports.decrypt = function (text) {
  let iv = Buffer.from(text.iv, 'hex');
  let encryptedText = Buffer.from(text.encryptedData, 'hex');
  
  let decipher = crypto.createDecipheriv(algorithm, key, iv);
  let decrypted = decipher.update(encryptedText);
  decrypted = Buffer.concat([decrypted, decipher.final()]);
  
  return decrypted.toString();
}


加密和解密似乎有效()。检查解密是否使用与加密相同的密钥。另外,将
encrypt()
返回的密文和IV与传递给
decrypt()
的密文和IV进行比较(即检查数据是否有变化)。我想我发现了问题。总是有一个用于解密的活动密钥,因此当我将数据存储在数据库中并稍后对其进行解密时,密钥已更改。请问有没有办法修复此问题?加密和解密似乎有效()。检查解密是否使用与加密相同的密钥。另外,将
encrypt()
返回的密文和IV与传递给
decrypt()
的密文和IV进行比较(即检查数据是否有变化)。我想我发现了问题。总是有一个用于解密的活动密钥,因此当我将数据存储在数据库中并稍后对其进行解密时,密钥已更改。请问有没有办法解决这个问题