如何解密NodeJS中的字符串

时间:2017-09-18 08:52:37

标签: javascript node.js encryption aes

我目前正在开发一个项目,该项目接收来自Amazons SQS(简单队列服务)的传入消息。

我已建立与SQS服务的连接并接收消息。

接收消息采用以下格式:

   { MessageId: '124a42b-657d-481d-348f-ddd9b8d8b143b',
  ReceiptHandle: 'AQEBSSVzlCbqsSUQ3E.....',
  MD5OfBody: '7ba46c7c8874fc6d0c4a141a2d3d4d5a721',
  Body: '10987235@PUBLISH;aSeIgjS78Iy4KRZHSeAy43...' }

邮件正文已加密,我已获得密码进行解密。

我的问题是如何在nodeJS中解密消息Body?

任何例子都将非常感谢!

更新:

到目前为止,这是我的代码的副本:

        const Consumer = require('sqs-consumer');
const AWS = require('aws-sdk');
const fs = require('fs');
const path = require("path");
const unzipper = require('unzipper');

const app = Consumer.create({
  queueUrl: 'https://sqs.us-west-1.amazonaws.com/QueueName',
  handleMessage: (message, done) => {

    saveToFile(message.Body)
      .then(() => {
        return unzipFile();
      })
      .then((success) => {
        // read content of XML file and save to DB
        console.log('success:', success);
      })
      .catch(e => {
        console.log('Error:', e);
      });

  },
  sqs: new AWS.SQS()
});

app.on('error', (err) => {
  console.log(err.message);
});

app.start();


const saveToFile = (message) => {
  debugger;
  console.log('saveToFile fired!');
  return new Promise((resolve, reject) => {
    fs.appendFile(path.resolve(__dirname) + '/zips/decodeMsg.zip', message, (err) => {
      if (err) reject(error);
      resolve();
    });
  });
}

const unzipFile = () => {
  return unzipper.Open.file(path.resolve(__dirname) + '/zips/decodeMsg.zip') // Fails To Read The File Here.
    .then(function (directory) {
      console.log('directory', directory);
      return new Promise(function (resolve, reject) {
        directory.files[0].stream(password)  // PASSING IN PASSWORD HERE
          .pipe(fs.createWriteStream('readablefile')) // should be XML
          .on('error', reject)
          .on('finish', resolve)
      });
    });
}

再次更新:

好的,我正在尝试使用以下代码解密消息Body。

    var crypto = require("crypto")
require('./config');

function decrypt(key, data) {
        var decipher = crypto.createDecipher('aes-256-cbc', key);
        var decrypted = decipher.update(data, 'hex', 'utf-8');
        decrypted += decipher.final('utf-8');

        return decrypted;
}

decryptedText = decrypt(process.env.password, process.env.encryptedMessage);
console.log("Decrypted Text: " + decryptedText);

但是我在控制台中收到以下错误:

      var ret = this._handle.update(data, inputEncoding);
                         ^

TypeError: Bad input string
    at TypeError (native)
    at Decipher.Cipher.update (crypto.js:145:26)
    at decrypt (/Users/dave/Tests/sqs-consumer/app.js:6:34)

0 个答案:

没有答案