ruby - Ruby OPENSSL AES128 CBC 用随机 iv 解密不起作用
问题描述
我正在使用一个相当简单的加密/解密 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
解决方案
您在解密时使用了不同的随机 IV。此值必须相同。那就是你在加密时捕获它:
iv = cipher.random_iv
然后你使用它解密:
cipher.iv = iv
然后它正确解密。您需要相同的密钥 + IV 对才能成功解密。
推荐阅读
- javascript - 在测试使用 jasmine 在 Angular 中获取注入表单控件的自定义指令时无法读取未定义的属性“值”
- python - 使用 python 请求将字节发送到 POST 请求
- r - 如何使用 Purrr 将因子的级别作为参数传递给函数
- javascript - 在页面加载和单选输入点击上运行 jQuery 函数
- node.js - 如何在 React 上使用 Material Ui。收到错误无效的挂钩调用
- javascript - 信封:无法读取sails.js 中未定义的属性“id”
- angular - 增加垫表角度中垫子行之间的间隙
- data-science - 使用 ARIMA 进行多特征预测
- javascript - 发生未处理的异常:在 Angular 9 的构建产品上超出了调用重试次数
- c - remove() 返回文件未找到错误(errno = 2),当我之前使用相同的文件字符串打开文件时