【问题标题】:Can't decrypt using crypto module in Nodejs无法在 Nodejs 中使用加密模块解密
【发布时间】:2019-03-06 23:22:30
【问题描述】:

我正在尝试编写一个相当于php opensssl解密的脚本,这是我尝试过的,

var crypto = require('crypto');
var ct = 'jKscKK6E/aQ50hAck0YZkA==';
var key = 'gxmo872UXsU6u41t2zXzRNcU9H1cfuNvu/fnI/q1vIc=';
var iv = 'sd+XF3bRJ/WMT9woe8LOkQ==';
var decipher = crypto.createDecipheriv('aes-128-cbc', new Buffer(key, 'base64'), new Buffer(iv, 'base64'));
var content = decipher.update(new Buffer(ct, 'base64'), "binary", "utf8");
content += decipher.final("utf8");
console.log("Decrypted: " + content);

但我得到了这个错误,

错误:密钥长度无效

这是我试图等效的 php 代码

openssl_decrypt(base64_decode($ct), 'aes-128-cbc', base64_decode($key), OPENSSL_RAW_DATA, base64_decode($iv))

【问题讨论】:

  • 你不是 base64 解码你的密钥/IV 任何地方。
  • 什么 PHP OpenSSL 解密会是什么?提供源码!
  • @LukeJoshuaPark,我错过了缓冲区中的解码参数,在添加了现在错误提示无效密钥长度之后。

标签: php node.js codeigniter encryption cryptography


【解决方案1】:

我的目的是写一个相当于Codeiginiter默认解密的脚本,所以我从代码的底部开始,这就是我发现上面错误的地方,最后我能够编写整个脚本,希望这可能是对某人有帮助。

  let crypto = require("crypto");
  let secret = 'xxxxxxxxxxxxxxxxxxxx';

  // ikm is initial keying material
  var hkdf = function (hashAlg, salt, ikm) {
      this.hashAlg = hashAlg;

      // create the hash alg to see if it exists and get its length
      var hash = crypto.createHash(this.hashAlg);
      this.hashLength = hash.digest().length;
      this.salt = salt || new Buffer(this.hashLength).fill(0).toString();
      this.ikm = ikm;

      // now we compute the PRK
      var hmac = crypto.createHmac(this.hashAlg, this.salt);
      hmac.update(this.ikm);
      this.prk = hmac.digest();
 };

 hkdf.prototype = {
    derive: function(info, size, cb) {
      var prev = new Buffer(0);
      var output;
      var buffers = [];
      var num_blocks = Math.ceil(size / this.hashLength);
      info = new Buffer(info);

      for (var i=0; i<num_blocks; i++) {
        var hmac = crypto.createHmac(this.hashAlg, this.prk);
        hmac.update(prev);
        hmac.update(info);
        hmac.update(new Buffer([i + 1]));
        prev = hmac.digest();
        buffers.push(prev);
      }

      output = Buffer.concat(buffers, size);
      return output;
    }
 };

 function decrypt(code)
 {
    if (typeof code !== 'string')
       return false;
    code = code.substring(128);
    var buff = new Buffer(code, 'base64');
    var iv = buff.slice(0, 16);
    var encyptedText = buff.slice(16).toString('base64');
    var _hkdf = new hkdf('sha512', null, secret);
    var derive_key = _hkdf.derive('encryption', secret.length);
    var key = derive_key.slice(0, 16);
    var decipher = crypto.createDecipheriv('aes-128-cbc', key, iv);
    var result = decipher.update(encyptedText, 'base64');
    result += decipher.final();
    return result.replace(/[']/g, '');
 }

【讨论】:

    猜你喜欢
    • 2019-03-08
    • 1970-01-01
    • 2019-12-20
    • 2018-07-04
    • 1970-01-01
    • 1970-01-01
    • 2021-07-08
    • 1970-01-01
    • 2020-07-01
    相关资源
    最近更新 更多