Ruby OPENSSL AES128 CBC 随机 iv 解密不工作

Ruby OPENSSL AES128 CBC decrypting with random iv not working

我使用的是相当简单的 encryption/decryption 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 对才能成功解密。