【问题标题】:OpenSSL::Cipher::CipherError: wrong final block lengthOpenSSL::Cipher::CipherError:错误的最终块长度
【发布时间】:2016-08-19 07:39:16
【问题描述】:
source = ... # encrypted string - Base64.encode64(string)
cipher = OpenSSL::Cipher::Cipher.new('AES-128-ECB')
cipher.decrypt
cipher.key = ['YOUR_CHANNEL_SECRET'].pack('H*')
decoded = Base64.decode64(source)
decrypted = cipher.update(decoded) + cipher.final

对于 YOUR_CHANNEL_SECRET 我将我的密钥转换为十六进制字符串

参考 - https://developers.line.me/in_app_web/api-reference#get_token_access_token

我在 cipher.final 上遇到错误,我不知道为什么会出现这个错误以及解决方案是什么?

我遵循参考链接中定义的相同但仍然出现错误。

【问题讨论】:

  • 您的代码看起来不错。问题是加密数据的长度应该是 16 字节的倍数,而事实并非如此。要么你在尝试解密数据之前以某种方式破坏了数据,要么在你收到数据时它是错误的。

标签: ruby-on-rails ruby ruby-on-rails-4 openssl caesar-cipher


【解决方案1】:

改为:

source = ... # encrypted string - Base64.encode64(string)
cipher = OpenSSL::Cipher::Cipher.new('AES-128-ECB')
cipher.decrypt
cipher.key = ['YOUR_CHANNEL_SECRET'].pack('H*')
decoded = Base64.decode64(source)
decrypted = cipher.update(decoded) + cipher.final

我喜欢这样做:

def decrypt(encrypted_data, key, iv=nil, cipher_type="AES-256-CBC")
  cipher = OpenSSL::Cipher::Cipher.new(cipher_type)
  cipher.decrypt
  cipher.key = key
  cipher.iv = iv if iv != nil
  cipher.update([encrypted_data].pack("H*")) + cipher.final
end

【讨论】:

  • 不工作 - cipher.key 和最后一行出错。 NoMethodError:#<0xc531bd0>
猜你喜欢
  • 1970-01-01
  • 2014-03-20
  • 1970-01-01
  • 1970-01-01
  • 2013-01-11
  • 1970-01-01
  • 1970-01-01
  • 2017-12-20
  • 1970-01-01
相关资源
最近更新 更多