Ruby 微信小程序 Ruby AES 对称解密的问题

ad583255925 · 2018年03月14日 · 最后由 ad583255925 回复于 2018年03月14日 · 3219 次阅读
require "base64"
require "openssl"

class DecodeWechatEncrypted
  attr_accessor :appId, :sessionKey
  def initialize appId, sessionKey
    self.appId = appId
    self.sessionKey = sessionKey
  end

  def decryptData encryptedData, iv
    sessionKey = Base64.decode64(self.sessionKey)
    encryptedData = Base64.decode64(encryptedData)
    iv = Base64.decode64(iv)

    cipher = OpenSSL::Cipher::Cipher.new("AES-128-ECB")
    cipher.decrypt
    cipher.key = sessionKey
    cipher.iv = iv

    cipher.update(encryptedData) + cipher.final
  end
end

其中

cipher.iv = iv

这一行,报了一个

iv=': iv must be 0 bytes (ArgumentError)

这个我就不太懂了,有人写过这个吗

顺便贴一下官方的 nodeJs 版本

var crypto = require('crypto')

function WXBizDataCrypt(appId, sessionKey) {
  this.appId = appId
  this.sessionKey = sessionKey
}

WXBizDataCrypt.prototype.decryptData = function (encryptedData, iv) {
  // base64 decode
  var sessionKey = new Buffer(this.sessionKey, 'base64')
  encryptedData = new Buffer(encryptedData, 'base64')
  iv = new Buffer(iv, 'base64')

  try {
     // 解密
    var decipher = crypto.createDecipheriv('aes-128-cbc', sessionKey, iv)
    // 设置自动 padding 为 true,删除填充补位
    decipher.setAutoPadding(true)
    var decoded = decipher.update(encryptedData, 'binary', 'utf8')
    decoded += decipher.final('utf8')

    decoded = JSON.parse(decoded)

  } catch (err) {
    throw new Error('Illegal Buffer')
  }

  if (decoded.watermark.appid !== this.appId) {
    throw new Error('Illegal Buffer')
  }

  return decoded
}

module.exports = WXBizDataCrypt

iv 传空,ECB 模式不需要 iv

w7938940 回复

找到原因了😂 不是"AES-128-ECB""AES-128-CBC"

ad583255925 关闭了讨论。 03月14日 18:49
liuminhan 求教, 支付宝小程序 AES 解密 提及了此话题。 09月20日 16:42
需要 登录 后方可回复, 如果你还没有账号请 注册新账号