NodeJS Crypto 抛出“错误:错误:1C80006B:提供程序例程::最终块长度错误”

问题描述 投票:0回答:1

我正在运行 MERN 应用程序,在其中存储加密的用户数据。检索数据时,应对数据进行解密。 这是我用来加密和解密数据的代码

const crypto = require('crypto')

const { SECRET_KEY, SECRET_IV, ENCRYPTION_METHOD } = process.env

if (!SECRET_KEY || !SECRET_IV || !ENCRYPTION_METHOD) {
    throw new Error('secretKey, secretIV, and ecnryptionMethod are required')
}

// Generate secret hash with crypto to use for encryption
const key = crypto
    .createHash('sha512')
    .update(SECRET_KEY)
    .digest('hex')
    .substring(0, 32)
const encryptionIV = crypto
    .createHash('sha512')
    .update(SECRET_IV)
    .digest('hex')
    .substring(0, 16)


// Encrypt data
const encryptData = (data) => {
    const cipher = crypto.createCipheriv(ENCRYPTION_METHOD, key, encryptionIV)
    return Buffer.from(
        cipher.update(data, 'utf8', 'hex') + cipher.final('hex')
    ).toString('base64') // Encrypts data and converts to hex and base64
}

// Decrypt data
const decryptData = (encryptedData) => {
    try {
        const buff = Buffer.from(encryptedData, 'base64')
        const decipher = crypto.createDecipheriv(ENCRYPTION_METHOD, key, encryptionIV)
        const decrypted = decipher.update(buff.toString("utf8"), 'base64', 'utf8') + decipher.final('utf8');
        return decrypted;
    } catch (error) {
        console.error('Decryption Error:', error);
        return null;
    }
}

当我尝试解密时出现以下错误

Decryption Error: Error: error:1C80006B:Provider routines::wrong final block length
    at Decipheriv.final (node:internal/crypto/cipher:193:29)
    at decryptData (C:\Users\jeshu\Desktop\pizzahub\middleWare\encrypt.js:35:95)
    at C:\Users\jeshu\Desktop\pizzahub\controllers\orderController.js:101:30  
    at Array.forEach (<anonymous>)
    at findOrderForShop (C:\Users\jeshu\Desktop\pizzahub\controllers\orderController.js:100:16)
    at processTicksAndRejections (node:internal/process/task_queues:96:5) {   
  library: 'Provider routines',
  reason: 'wrong final block length',
  code: 'ERR_OSSL_WRONG_FINAL_BLOCK_LENGTH'
}

我该怎么办

javascript node.js encryption cryptography mern
1个回答
0
投票

试试这个代码:

// Encrypt data
const encryptData = (data) => {
    const cipher = crypto.createCipheriv(ENCRYPTION_METHOD, key, Buffer.from(encryptionIV, 'hex'));
    let encrypted = cipher.update(data, 'utf8', 'hex');
    encrypted += cipher.final('hex');
    return Buffer.from(encrypted, 'hex').toString('base64');
};

// Decrypt data
const decryptData = (encryptedData) => {
    try {
        const buff = Buffer.from(encryptedData, 'base64');
        const decipher = crypto.createDecipheriv(ENCRYPTION_METHOD, key, Buffer.from(encryptionIV, 'hex'));
        let decrypted = decipher.update(buff, 'utf8', 'utf8');
        decrypted += decipher.final('utf8');
        return decrypted;
    } catch (error) {
        console.error('Decryption Error:', error);
        return null;
    }
};
© www.soinside.com 2019 - 2024. All rights reserved.