【问题标题】:Ruby OPENSSL AES128 CBC decrypting with random iv not workingRuby OPENSSL AES128 CBC 用随机 iv 解密不起作用
【发布时间】:2019-06-24 19:38:23
【问题描述】:

我正在使用一个相当简单的加密/解密 Ruby 脚本,它似乎可以工作 - 但是解密位会破坏消息的前几个字节。我错过了什么?

代码如下:

key = OpenSSL::Random.random_bytes(16)
plain_text = "Some important txt we want to encrypt"
cipher = OpenSSL::Cipher::AES128.new(:CBC)
cipher.encrypt
cipher.key = key
cipher.random_iv
cipher_text = cipher.update(plain_text) + cipher.final

cipher = OpenSSL::Cipher::AES128.new(:CBC)
cipher.decrypt
cipher.key = key
cipher.random_iv
decrypted_plain_text = cipher.update(cipher_text) + cipher.final

puts "AES128 in CBC mode"
puts "Plain text: " + plain_text
puts "Cipher text: " + urlsafe_encode64(cipher_text)
puts "Decrypted plain text: " + decrypted_plain_text

结果:

AES128 in CBC mode Plain text: Some important txt we want to encrypt
Cipher text:
P2fdC7cApQvxHnfxSEfB2iJaueK3xRoj-NN3bDR8JheL_VPFYTDF_RxpLfBwoRfp
Decrypted plain text: �܇�Σ }w�D�A:xt we want to encrypt

【问题讨论】:

  • 这里的每一行末尾都有大量的空格。有几个是可以理解的,但超过 190 个!
  • @tadman 已修复 :)

标签: ruby encryption openssl aes cbc-mode


【解决方案1】:

您在解密时使用了不同的随机 IV。此值必须相同。那就是你在加密时捕获它:

iv = cipher.random_iv

然后你用那个解密:

cipher.iv = iv

然后它会正确解密。您需要相同的密钥 + IV 对才能成功解密。

【讨论】:

  • 但这不是重点吗?依赖秘密/密钥而不是 IV?
  • 密钥是用户定义的(例如密码),但 IV 是生成或预定义的。两者都需要解锁内容。如果您愿意,您始终可以对特定的 IV 进行硬编码,或者随机生成它并将其与密钥一起存储。请注意,对 IV 进行硬编码可能会使您面临更多安全风险,但如果风险很低,这并不是什么大问题。它只是让您更容易猜测您的密码,因为使用固定 IV,您无需测试所有可能的 IV。
猜你喜欢
  • 2011-12-10
  • 1970-01-01
  • 2013-03-13
  • 1970-01-01
  • 1970-01-01
  • 2014-07-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多